reactjs - 测试时,导致 React 状态更新的代码应该被封装到 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 的更新未包含在 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 in TestApp
console.error node_modules/react-dom/cjs/react-dom.development.js:506 警告:测试中对 TestApp 的更新未包含在 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 in TestApp
解决方案
关键是要await
act
然后使用async
箭头函数。
await act( async () => render(<TestApp/>));
资源:
推荐阅读
- reactjs - componentDidUpdate 导致无限循环
- oauth - 通过 SAML 作为 IDP 协议使用 O365 进行 Outlook 身份验证 (SSO) - 资源无效错误
- python - 尝试在字典中使用函数,失败:NameError: name 'function_name' is not defined
- javascript - ElectronStore 不允许访问家中的配置以进行“严格”限制?
- ios - Braintree 的 PayPal 集成所需的 Firebase 客户端 ID
- ruby-on-rails - 在 gems 中使用 require false 后,我是否必须在需要的地方一次又一次地加载 gem,否则它会被缓存?
- c# - Unity Facebook 插件 FacebookContentProvider 未找到运行时异常
- groovy - 如何将类似行的参数结构传递给方法?
- java - 使用 SpringBoot 处理 REST 中的自定义验证和异常
- google-cloud-dataproc - 从 Yarn UI 终止 Dataproc 作业不再有效 - 仅从 Dataproc UI