如何在笑话和酶中为 useState Hook 设置初始状态? [英] How to set initial state for useState Hook in jest and enzyme?
问题描述
目前我正在使用带有反应钩子的功能组件.但我无法完全测试 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屋!