首页 > 解决方案 > 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();
});

标签: reactjsuse-effectreact-testing-library

解决方案


试试这个:

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();
  });
});

推荐阅读