【发布时间】:2021-12-31 00:18:37
【问题描述】:
我正在使用 React-Testing-Library,到目前为止我的测试都通过了,但我有一个警告,我无法理解或不知道如何解决。
警告是……
console.error
Warning: An update to App 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
at App
在我的 App.js 中出现错误。
let newData = await random();
27 | setData(newData[0]);
> 28 | setLoading(false);
| ^
29 | };
30 | useEffect(() => {
31 | getter();
这是我的 App.test 文件。
describe("async call to render Home component", () => {
test("happy, with data - testing the async call", async () => {
fetch.mockResponseOnce(JSON.stringify([{ test: "data" }]));
render(<App />)
const element = await screen.findByTestId('homeComponent')
expect(element).toBeInTheDocument()
})
test("sad, no data - testing the async call", async () => {
fetch.mockResponseOnce(JSON.stringify({}))
render(<App />)
const element = await screen.getByText(/loading.../i)
expect(element).toBeInTheDocument()
})
})
我不确定这是否只是使用异步功能进行测试的过程。但是还是有点不确定,如果以后警告可能是个问题,我宁愿现在解决。
任何帮助将不胜感激。
【问题讨论】:
-
请提供被测组件的完整代码。
标签: reactjs unit-testing testing jestjs react-testing-library