我有几个用 Jest 和 React 测试库编写的测试。它们都模拟获取并使用 userEvent.click 调用来触发发出获取请求的提交按钮。组件中的状态得到更新,我做出断言。我正在使用 useEffect 挂钩来填充数据数组,但它仅在初始加载时运行,因为我向它传递了一个空的依赖项数组。目前我所有的测试都通过了。如果我一起运行它们,我会得到一个错误的 act() 错误,该错误源于 useEffect:
Warning: It looks like you're using the wrong act() around your test interactions.
Be sure to use the matching version of act() corresponding to your renderer:
// for react-dom:
import {act} from 'react-dom/test-utils';
// ...
act(() => ...);
// for react-test-renderer:
import TestRenderer from react-test-renderer';
const {act} = TestRenderer;
// ...
act(() => ...);
Run Code Online (Sandbox Code Playgroud)
但是,当我单独运行其中一个时,我没有收到警告。我可以单独运行其中任何一个,并且不会收到任何警告。仅当我同时运行两个或多个测试时,我才会收到警告。
我的测试是:
Warning: It looks like you're using the wrong act() around your test …
Run Code Online (Sandbox Code Playgroud) 我正在测试一个组件,该组件使用一个useEffect
钩子从 API 获取数据,更新状态,然后构建组件。我已经使用Stack Overflow 答案作为示例成功模拟了几次测试的 API 响应。我现在正在尝试编写一个测试,在其中模拟从 API 返回的错误。我收到一条错误,TypeError: Cannot read property 'then' of undefined
指出fetch
. 我正在尝试使用相同的示例,但没有成功。
我成功地使用测试数据获取模拟如下所示:
global.fetch = jest.fn().mockImplementationOnce(() =>
Promise.resolve({
json: () => Promise.resolve(successMockData),
})
)
Run Code Online (Sandbox Code Playgroud)
我尝试的模拟错误响应当前如下所示:
global.fetch = jest.fn().mockImplementationOnce(() => {
Promise.resolve({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
})
})
Run Code Online (Sandbox Code Playgroud)
如果我拒绝承诺,我仍然会得到相同的错误,但也会引发抛出的异常:
global.fetch = jest.fn().mockImplementationOnce(() => {
Promise.reject({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
}) …
Run Code Online (Sandbox Code Playgroud)