4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jestを実行すると`An update to Page inside a test was not wrapped in act(...).`のWarningが出た

Posted at

はじめに

Jestでテスト実行したところ、An update to Page inside a test was not wrapped in act(...).のWarningが出ました。
原因は書いてある通り、Reactのステート更新時にはactでラップをする必要があるようです。

    An update to Page 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://react.dev/link/wrap-tests-with-act

actとは

公式ドキュメントには下記の説明がありました。

actは、アサーションを行う前に保留中の React の更新を適用するために用いるテストヘルパです。

超ざっくりですが、actでラップした処理が実DOMに反映されるまでは、次の処理の実行を待ってくれるといった認識です。

actは以下のような場合に使用します。

・Reactの状態更新(useStateやuseReducer)が発生する操作をテストする時
・コンポーネントの初期レンダリング時(特に非同期処理がある場合)
・useEffectの実行時
・イベントハンドラの実行時
・APIコールなどの非同期処理

注意点としては下記です。

・公式ではactawaitおよびasync関数と一緒に使用することを推奨している
・ステートが非同期で更新されるケースはactでは対応できない
・React Testing Library を使えばactは不要

おわりに

普段はReact Testing Libraryを使っていたので、今回このようなWarningに初めて遭遇しました。いちいちactを使っているとコードの記述量が増えてしまった印象があるので、React Testing Libraryのありがたみに気づきました。

参考

actの挙動について図とともに詳しく解説されています。

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?