はじめに
React Testing Library を使ったテストにおいてクリック操作などのユーザー操作を実施する際には、testing-library/user-event を使います。例えばクリック操作なら user.click()
のような感じ。その際、コンポーネントの状態更新の同期をとるため、戻り値の Promise を await
することが必要です。これをしないと、When testing, code that causes React state updates should be wrapped into act(...):
という warning が出ます。
しかし、これをしているにも関わらず Warning が解消されないことが多々あり、非同期関数内で状態を更新している際はだめなのかと思い長い間あきらめていたのですが、最近あらためて調べてみた結果、原因がわかったので、本記事はその記録となります。
原因
複数のバージョンの @testing-library/dom
がインストールされていることが原因とのこと。User event は @testing-library/dom
に wrapper 関数を登録するのですが、複数のバージョンの @testing-library/dom
がインストールされていると、それが適切に機能しないのが原因だそうです。実際に、npm ls @testing-library/dom
を実行してみたところ、8.20.0 と 9.2.0 の2つインストールされていることが確認できました。
├─┬ @storybook/testing-library@0.1.0
│ ├── @testing-library/dom@8.20.0
│ └─┬ @testing-library/user-event@13.5.0
│ └── @testing-library/dom@8.20.0 deduped
├─┬ @testing-library/react@14.0.0
│ └── @testing-library/dom@9.2.0
├─┬ @testing-library/user-event@14.4.3
│ └── @testing-library/dom@8.20.0 deduped
├─┬ eslint-plugin-jest-dom@4.0.3
│ └── @testing-library/dom@8.20.0 deduped
└─┬ react-select-event@5.5.1
└── @testing-library/dom@8.20.0 deduped
修正
@testing-library/dom に依存しているライブラリを再インストール。
├─┬ @testing-library/react@14.0.0
│ └── @testing-library/dom@9.3.3
├─┬ @testing-library/user-event@14.5.1
│ └── @testing-library/dom@9.3.3 deduped
├─┬ eslint-plugin-jest-dom@5.1.0
│ └── @testing-library/dom@9.3.3 deduped
└─┬ react-select-event@5.5.1
└── @testing-library/dom@9.3.3 deduped
これにて act warning は全て解消。