目前我正在使用带有反应钩子的功能组件。但我无法测试useState
完全挂钩。考虑这样一个场景:useEffect
钩子我正在执行 API 调用并在中设置值useState
。对于笑话/酶,我模拟了要测试的数据,但我无法设置初始状态值useState
开玩笑。
const [state, setState] = useState([]);
我想将初始状态设置为玩笑中的对象数组。我找不到任何类似于类组件的 setState 函数。
你可以嘲笑React.useState
在测试中返回不同的初始状态:
// 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 https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)