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.

Answers:

Answer

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

Answer

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.

Answer
  • Below function will return state
const setHookState = (newState) => jest.fn().mockImplementation(() => [
  newState,
  () => {},
]);
  • 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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.