How to set initial state for useState Hook in jest and enzyme?

Srigar picture Srigar · Jul 14, 2019 · Viewed 26k times · Source

Currently Im using functional component with react hooks. But I'm unable to test the useState hook completely. Consider a scenario like, in useEffect hook I'm doing an API call and setting value in the useState. For jest/enzyme I have mocked data to test but I'm unable to set initial state value for useState in jest.

const [state, setState] = useState([]);

I want to set initial state as array of object in jest. I could not find any setState function as similar like class component.

Answer

Jimmy picture Jimmy · Aug 6, 2019

You can mock React.useState to return a different initial state in your tests:

// Cache original functionality
const realUseState = React.useState

// Stub the initial state
const stubInitialState = ['stub data']

// Mock useState before rendering your component
jest
  .spyOn(React, 'useState')
  .mockImplementationOnce(() => realUseState(stubInitialState))

Reference: https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga