React 测试库:测试中的更新未包含在 act(...) 中并且无法对未安装的组件执行 React 状态更新

React testing library: An update inside a test was not wrapped in act(...) & Can't perform a React state update on an unmounted component

在我的测试中,组件接收它的 props 并设置组件。

这会触发一个 useEffect 来发出一个 http 请求(我模拟的)。

返回了获取的 mocked 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();
  });
});

基本上,await wait();

渲染您的组件:

import { wait } from '@testing-library/react';

const { findByText, getByText } = render(
  <BalanceModule {...reportConfig}></BalanceModule>
);
// wait for the async call
await wait();

// assert stuff
// screen.findByText("2021-01-20T01:04:38");
expect(screen.getByText("2021-01-20T01:04:38")).toBeTruthy();