我正在执行我的第一步,使用以下内容测试 React 功能组件:
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
的使用有问题。 - 我的测试设置/配置有问题(我基本上使用的是普通的 create-react-app typescript 模板)。
- 我正在测试的组件出现问题。
有什么想法可能会导致这种情况:尽管已经包装在 act
中,但我仍收到“未包装在 act 中”警告?
最佳答案
事实证明我只需要这个:
test('basic app rendering', async () => {
await act(async () => {
render(<App />);
})
});
这已被提出为 issue在 16.8 版本中。与该链接问题类似,我的问题是 useEffect
中的异步函数。
在 16.9+ 版本中(我使用的是 17.0),可以使用异步版本的 act
。
我问这个问题的原因是我第一次尝试异步变体时犯了一个愚蠢的错误:
test('basic app rendering', async () => {
await act(() => { // note missing async here
render(<App />);
})
});
也就是说,我忘记将传递给 act
的函数也注释为 async
。在这种情况下它不起作用(事实上有一个警告'await'对此表达式的类型没有影响。
)。
关于javascript - 尽管使用了 act,什么可能会导致 "update to ... inside a test was not wrapped in act"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64900573/