【问题标题】:React testing library: An update inside a test was not wrapped in act(...) & Can't perform a React state update on an unmounted componentReact 测试库:测试中的更新未包含在 act(...) 中,并且无法对未安装的组件执行 React 状态更新
【发布时间】:2021-01-20 14:28:56
【问题描述】:

在我的测试中,组件接收它的 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();
});

【问题讨论】:

    标签: reactjs use-effect react-testing-library


    【解决方案1】:

    试试这个:

    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 waitFor(()=>{ }) 中就可以了,虽然我不明白我的 findByText 等待(findByText 也返回一个承诺)没有不工作
    • @blomster waitFor 方法在内部使用 act 函数。你可以做你所做的,而不是用act函数包装它
    【解决方案2】:

    基本上,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();
    

    【讨论】:

    • 我收到Module '"@testing-library/react"' has no exported member 'wait'.?
    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2021-07-01
    • 2020-11-21
    • 2023-02-11
    • 2021-11-30
    • 2020-09-03
    相关资源
    最近更新 更多