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

Currently Im using functional component with react hooks. But i unable to test the useState Hook completely. Consider a scenario like, in useEffect hook i'm doing api call and setting value in the useState. For jest/enzyme i have mock data to test but i 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.



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
  .spyOn(React, 'useState')
  .mockImplementationOnce(() => realUseState(stubInitialState))



If I recall correctly, you should try to avoid mocking out the built-in hooks like useState and useEffect. If it is difficult to trigger the state change using enzyme's invoke(), then that may be an indicator that your component would benefit from being broken up.

  • Below function will return state
const setHookState = (newState) => jest.fn().mockImplementation(() => [
  () => {},
  • Add below to use react

const reactMock = require('react');

In your code, you must use React.useState() to this work, else it won't work

const [arrayValues, setArrayValues] = React.useState();

const [isFetching, setFetching] = React.useState();

  • Then in your test add following, mock state values

reactMock.useState = setHookState({ arrayValues: [], isFetching: false, });

Inspiration: Goto


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.