【问题标题】:What is the alternative the function waitForNextUpdate (@testing-library/react-hooks) in @testing-library/react for async hooks?@testing-library/react 中用于异步挂钩的函数 waitForNextUpdate (@testing-library/react-hooks) 的替代方案是什么?
【发布时间】:2023-01-13 04:14:44
【问题描述】:
我想测试我的自定义钩子,但在 React 18 中 @testing-library/react-hooks 库不起作用,我使用的是 @testing-library/react 它具有 renderHook 函数并且工作正常,但该库没有 waitForNextUpdate异步挂钩函数。出于这个原因,我无法测试我的自定义异步挂钩。
【问题讨论】:
标签:
reactjs
testing
react-hooks
react-testing-library
react-testing
【解决方案1】:
另一种方法是将其替换为 waitFor。
前:
await waitForNextUpdate();
expect(fetch).toHaveBeenCalledTimes(1)
后
await waitFor(() => {
expect(fetch).toHaveBeenCalledTimes(1)
}
【解决方案2】:
它只在我使用act和waitFor时对我有用:
await act(async () => {
await waitFor(() => {
expect(result.current.isAuthenticated).toBeUndefined();
});
});