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?

React Hook Form + Chakra UI で「Unable to find an element with the text」エラーが出る原因と対処法

Posted at

はじめに

React Hook Form と Chakra UI を使って必須入力フォームを作っていたとき、
UI 上ではちゃんとエラーメッセージが表示されるのに、Jest のテストでは取れないという問題にハマりました。
この記事では、その原因と解決方法を共有します。

問題

React Hook Form + Chakra UI で必須項目をテストしていたとき、
本番ではちゃんとエラーメッセージが表示されるのに、Jest のテストでは失敗しました。

Unable to find an element with the text: IDは必須です

UI 上では確かに表示されているのに、テストでは見つからない状態でした。
原因は、React Hook Form のバリデーションエラーは即時には DOM に反映されないためでした。
そのため getByText で要素を探すと、まだ DOM に存在せずテストが失敗してしまいました。

解決方法

Testing Library の findByText を使って、要素が出てくるまで待つようにしました。

これだと失敗する

expect(screen.getByText("IDは必須です")).toBeInTheDocument();

非同期対応で成功

expect(await screen.findByText("IDは必須です")).toBeInTheDocument();

これで「テストでは取れないけど UI では見える」という食い違いが解消しました。

まとめ

  • UI と Jest の挙動がズレたときは「非同期かどうか」を疑う
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?