在测试时,应将导致反应状态更新的代码包装到ACT中 [英] When testing, code that causes React state updates should be wrapped into act
本文介绍了在测试时,应将导致反应状态更新的代码包装到ACT中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的测试:
import {
render,
cleanup,
waitForElement
} from '@testing-library/react'
const TestApp = () => {
const { loading, data, error } = useFetch<Person>('https://example.com', { onMount: true });
return (
<>
{loading && <div data-testid="loading">loading...</div>}
{error && <div data-testid="error">{error.message}</div>}
{data &&
<div>
<div data-testid="person-name">{data.name}</div>
<div data-testid="person-age">{data.age}</div>
</div>
}
</>
);
};
describe("useFetch", () => {
const renderComponent = () => render(<TestApp/>);
it('should be initially loading', () => {
const { getByTestId } = renderComponent();
expect(getByTestId('loading')).toBeDefined();
})
});
测试通过,但我收到以下警告:
警告:测试内的TestApp更新未包含在 动作(...)。控制台。错误 Node_modules/react-dom/cjs/react-dom.development.js:506 警告:测试中对TestApp的更新未包含在操作(...)中。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 in TestApp
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 in TestApp
推荐答案
关键是await
act
,然后使用async
箭头功能。
await act( async () => render(<TestApp/>));
来源:
https://stackoverflow.com/a/59839513/3850405
这篇关于在测试时,应将导致反应状态更新的代码包装到ACT中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文