reactjs - React 测试库:测试中的更新未包含在 act(...) 中,并且无法对未安装的组件执行 React 状态更新
问题描述
在我的测试中,组件接收它的 props 并设置组件。
这会触发 useEffect 来发出 http 请求(我对此进行了模拟)。
返回了获取的模拟 resp 数据,但是 useEffect 中的清理函数已经被调用(因此组件已卸载),所以我得到了所有这些错误。
如何防止组件卸载以便更新状态?我试过行动,没有行动,没有任何事情会导致组件等待获取完成。
我应该说我的警告只是警告,但我不喜欢所有的红色,它表明出了问题。
export const BalanceModule = (props) => {
const [report, setReport] = useState();
useEffect(() => {
fetch('http://.....').then((resp) => {
console.log("data returned!!!")
setReports((report) => {
return {...report, data: resp}
})
})
return () => {
console.log("unmounted!!!")
};
}, [report])
.... trigger update on report here
}
// the test:
test("simplified-version", async () => {
act(() => {
render(
<BalanceModule {...reportConfig}></BalanceModule>
);
});
await screen.findByText("2021-01-20T01:04:38");
expect(screen.getByText("2021-01-20T01:04:38")).toBeTruthy();
});
解决方案
试试这个:
test("simplified-version", async () => {
act(() => {
render(<BalanceModule {...reportConfig}></BalanceModule>);
});
await waitFor(() => {
screen.findByText("2021-01-20T01:04:38");
expect(screen.getByText("2021-01-20T01:04:38")).toBeTruthy();
});
});
推荐阅读
- angular - Angular:如何通过 API 调用使用 JWT 身份验证
- java - 图像背景要删除并设置为透明图像
- java - 匹配输入中两个不同位置的正则表达式
- python - 使用变量作为函数的关键字参数
- node.js - 已解决承诺的打字稿返回类型可能性
- mysql - 错误 1054 (42S22): MySQL 中“字段列表”中的未知列“员工”
- ios - UIImageView的cornerRadius不起作用
- ios - 如何在 swift 4 和 XCODE 9 中为此 KUNDLI 图像设置多个标签
- yaml - YamlDotNet:如何自定义反序列化器以处理具有不同类型值的相同键
- python - 按下特殊字符后 Visual Studio 智能感知提交 - python