blo*_*ter 7 reactjs react-testing-library use-effect
在我的测试中,组件接收其 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();
});
Run Code Online (Sandbox Code Playgroud)
Tag*_*ari 13
尝试这个:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14917 次 |
| 最近记录: |