gpt4 book ai didi

javascript - 如何在jest和enzyme中设置useState Hook的初始状态?

转载 作者:行者123 更新时间:2023-12-03 13:16:25 25 4
gpt4 key购买 nike

目前我正在使用带有反应钩子(Hook)的功能组件。但我无法完全测试 useState Hook 。考虑这样一个场景,在 useEffect Hook 中,我正在执行 API 调用并在 useState 中设置值。对于 jest/enzyme,我已模拟数据进行测试,但无法在 jest 中设置 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

关于javascript - 如何在jest和enzyme中设置useState Hook的初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com