Satoru Kikuchi
Satoru Kikuchi

Reputation: 1209

In the custom hook test, the state is not changed from the initial value

I'm testing my custom hook with Jest and React testing library.

In the custom hook test, I tried to change the state value and test it, but it changes from the initial value.

I'm going to explain it in detail with examples.

Firstly, take look at my custom hook and test code.

This is my custom hook.

import * as React from 'react';

export const useCount = () => {
  const [count, setCount] = React.useState(100);

  const increment = () => {
    console.log(count, 'inside increment');
    setCount(count + 1)
  }
  const decrement = () => {
    console.log(count, 'inside decrement');
    setCount(count - 1)
  }

  return { count, setCount, increment, decrement }
}

This is the test code.

import React from 'react';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router-dom';
import { fireEvent, render } from '@testing-library/react';
import { act, renderHook } from '@testing-library/react-hooks';

import { useCount } from '../src/usecase/useCount';

describe('test', () => {
  test('test', () => {
    const { result, rerender } = renderHook(() => useCount());
    act(() => {
      result.current.setCount(0);
      result.current.increment();
    })
    expect(result.current.count).toBe(1) // In this line, I hope count is 1 but it is 101 because initial value is 100 and it was added to 1.
  })
});

The count is 100 initially, and increase method adds 1 to the count from the count current value.

So I want the score in the test code to be 1. Because the score was set 0 firstly in the test code, and after that, the score was added 1 by increase method.

Upvotes: 1

Views: 1671

Answers (1)

darkscripter
darkscripter

Reputation: 425

Because you change initialValue and run the function in the same render. so the expected will become your init (100) + 1 @testing-library

and in test code you can put them like this

...

describe('test', () => {
  test('test', () => {
    const { result, rerender } = renderHook(() => useCount());
      
    //run setCount to change initial value
    act(() => {
    result.current.setCount(0);
  })

  // make it rerender
    rerender()
  
  // run your count
    act(() => {
      result.current.increment();
    })
    expect(result.current.count).toBe(1) // In this line, I hope count is 1 but it is 101 because initial value is 100 and it was added to 1.
  })
});

...

Upvotes: 3

Related Questions