【问题标题】:Jest - Warning: You called act(async () => ...) without await开玩笑 - 警告:您在没有等待的情况下调用了 act(async () => ...)
【发布时间】:2026-01-08 10:50:02
【问题描述】:

我有一个测试,我试图测试组件的默认渲染与存储中的某些东西(在本例中为 0)时的渲染相比。组件在两种情况下都应该呈现相同的内容。为了测试这一点,我需要渲染组件两次。

import { render, waitFor } from "@testing-library/react-native";
import * as React from "react";
import { View } from "react-native";

it("Shouldn't break when rendering twice...", async () => {
    const firstRender = await waitFor(() => render(<View />));
    const defaultJson = JSON.stringify(firstRender.toJSON()); 
    firstRender.unmount();
  
    putTheThingInAsyncStorage();
    
    const secondRender = await waitFor(() => render(<View />));
    const newJson = JSON.stringify(secondRender.toJSON()); 
    expect(newJson).toBe(defaultJson);
  
    // In this particular test case, they should be the same.
    expect(newJson).toBe(defaultJson);

    removeTheThingFromAsyncStorage();
});

这个测试有效,但控制台给了我这个烦人的警告:Warning: You called act(async () =&gt; ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () =&gt; ...);

因此,我已将 await waitFor(...); 添加到渲染调用中,但我仍然收到警告。在这一点上,警告是对我说谎,因为事实上我使用的是 await 关键字,所以我不确定问题是什么。

我做错了什么?

【问题讨论】:

    标签: react-native jestjs


    【解决方案1】:

    我仍然感到困惑的是,我收到了我收到的具体警告,但以下是似乎对我有用的方法:

    import { render, waitFor } from "@testing-library/react-native";
    import * as React from "react";
    import { View } from "react-native";
    
    it("Shouldn't break when rendering twice...", async () => {
      // DO NOT use await or put render() in a waitFor
      const firstRender = render(<View/>);
      const defaultJson = JSON.stringify(firstRender.toJSON());
      act(() => {
        // Unmount should be wrapped in an act, but don't use await
        firstRender.unmount();
      });
    
      putTheThingInAsyncStorage();
    
      // DO NOT use await or put render() in a waitFor
      const secondRender = render(<View/>);
      // I did need to use await and waitFor for this toJSON()
      await waitFor(() => secondRender.toJSON());
      const newJson = JSON.stringify(secondRender.toJSON());
    
      expect(newJson).toBe(defaultJson);
    
      removeTheThingFromAsyncStorage();
    });
    

    【讨论】:

      最近更新 更多