如何在玩笑和酶中为useState Hook设置初始状态? [英] How to set initial state for useState Hook in jest and enzyme?
问题描述
目前,Im使用带有React钩子的功能组件。但是我无法完全测试 useState
挂钩。考虑一种情况,例如,在 useEffect
挂钩中,我正在进行API调用并在 useState
中设置值。对于玩笑/酶,我已经模拟了数据进行测试,但是无法在玩笑中设置 useState
的初始状态值。
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([]);
我想将初始状态设置为对象数组。我找不到类似于类组件之类的任何setState函数。
I want to set initial state as array of object in jest. I could not find any setState function as similar like class component.
推荐答案
您可以模拟 React.useState
返回测试中的其他初始状态:
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))
参考: https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga
这篇关于如何在玩笑和酶中为useState Hook设置初始状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!