我正在进行第一步的测试,用如下所示的方法来响应功能组件:
import React from 'react';
import { render } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import App from './App';
test('basic app rendering', () => {
act(() => {
render(<App />);
})
});然而,这导致了臭名昭著的警告,即我们必须使用act。
Warning: An update to SomeSubComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act这个链接让我回到了我所来自的地方,并且基本上展示了一个例子,就是像我一样使用act。
我看到了几种可能性:
act的使用出了问题。任何可能导致这种情况的想法--尽管已经在act中包装了--我还是得到了“未包装在行动中”的警告。
发布于 2020-11-18 20:12:49
原来我只需要这样:
test('basic app rendering', async () => {
await act(async () => {
render(<App />);
})
});这是在16.8版中作为问题引发的。与链接问题类似,我的问题是useEffect中的异步函数。
在16.9+版本(我在17.0版)中,act的异步版本是可用的。
我之所以问这个问题,是因为我第一次尝试异步变体时犯了一个愚蠢的错误:
test('basic app rendering', async () => {
await act(() => { // note missing async here
render(<App />);
})
});也就是说,我也忘记注释传递给act的函数为async。在这种情况下,它不起作用(事实上,有一个警告'await' has no effect on the type of this expression.)。
https://stackoverflow.com/questions/64900573
复制相似问题