1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Warning: An update to ○○ inside a test was not wrapped in act(...) がでる。

Last updated at Posted at 2022-05-22

React18でReact Tesing Libraryを使っていたら、

      Warning: An update to App inside a test was not wrapped in act(...).
      
      When testing, code that causes React state updates should be wrapped into act(...):
      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */
      
      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
          at App

という警告がでる。

言われた通りにact()でstateを更新した部分を囲んでみる。

import { act } from "react-dom/test-utils";

const Sample = () => {
  const [user, setUser] = useState(null);

  const getUser = async () => {
    return { id: "1", name: "Robin" };
  };

  useEffect(() => {
    const loadUser = async () => {
      const user = await getUser();
      act(()=>setUser(user));
    };
    loadUser();
  }, []);

return <></>
}

するとエラーが変わった。

Warning: The current testing environment is not configured to support act(...)

React18ではこのような警告がでで、テスト前に
globalThis.IS_REACT_ACT_ENVIRONMENT = false
と書くと無視できるらしい。

設定ファイルがわからなかったのでテストに直接書き込んでみる。

describe("sample", () => {
  // warning 回避
  beforeEach(() => {
    globalThis.IS_REACT_ACT_ENVIRONMENT = false;
  });

  test("async await", async () => {
    // 非同期で最後に存在する場合は findBy を使います。
    render(<Sample />);
    expect(screen.queryByText(/Signed in as/)).toBeNull();

    screen.debug();
    expect(await screen.findByText(/Signed in as/)).toBeInTheDocument();

    screen.debug();
  });
});

Warningが消えて解決した。

そのうちこれを書かなくてもいいようにアップデートされるらしい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?