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

我只是一个虾纸丫 提交于 2020-02-23 10:32:15

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/57025753/how-to-set-initial-state-for-usestate-hook-in-jest-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!