0
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?

【React】テスト実行時に「Warning: An update to Counter inside a test was not wrapped in act(...)」のワーニングが発生

Posted at

Reactアプリに対してTesting Libraryを使用してテストを行っていた際に以下のようなワーニングが発生しました。

Warning: An update to Counter 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 */

今回はこのワーニングが表示されたときの対処法を簡単にまとめていこうと思います。

すでに先人の方々が多くの記事でまとめられている内容になりますが、自分自身の頭を整理するために記事にしました。最後までお付き合いいただけますと幸いです。

環境

  • Windows11
  • Vite
  • Node.js : ver.20
  • React18

結論

ステート変更後の検証処理をawait waitFor()で囲む

it('should render "Add Modal"', async () => {
  render(
    <ChakraProvider value={defaultSystem}>
      <App />
    </ChakraProvider>
  );

  // モーダルが非表示であるか確認
  expect(screen.queryByText('Cancel')).toBeNull();

  // ボタンの取得
  const button = screen.getByText('新規登録');

  // ボタンクリック
  fireEvent.click(button);

  // モーダルが表示されているか確認
-  expect(screen.getByText('Cancel')).toBeInTheDocument()
+  await waitFor(() => {
+    expect(screen.getByText('Cancel')).toBeInTheDocument()
+  });
});

説明

簡単に3行でまとめると下記のようになります。

  • フックを使用した処理はReactではいい感じに非同期に実行される
  • テスト側はそんなことを気にせずレンダー後に値チェックを実行する
  • Warning「もしかしたら値が更新されてないかもしれないよ!!!」

そのため値チェック時に実行を待機することでWarningが消えたようです。

まだまだ学習中のため認識に誤りがありましたらご指摘いただけると幸いです。

おわりに

なんとなくコピペで解決していたため、記事にしてより理解が深まりました。
こういった記事をこれからも書いていきたいです。

参考

※↓試していないがこのような方法もあるらしい

0
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
0
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?