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 Testing Library のユーザー操作(fireEvent / userEvent)についてまとめてみた

Posted at

はじめに

React Testing Library を使ってテストを書いているときに、「要素をどう探せばいいのか?」で少し迷ったので、よく使う方法をまとめます。

fireEvent

fireEvent.click(button);
fireEvent.change(input, { target: { value: "abc" } });

DOM イベントを直接発火させる方法。
動作はシンプルですが、実際のユーザー操作とは少し違う挙動になることもあります。

  • 最低限のイベント発火だけ確認したいときに便利。

userEvent

await userEvent.type(input, "Hello");
await userEvent.click(button);

実際のユーザー操作に近いシミュレーション。
キーボード入力やマウスクリックを「人が操作する感じ」で再現できます。

  • 可能なら こちらを優先して使うのがおすすめ。

まとめ

fireEvent
→ シンプルにイベントを直接発火させたいとき

userEvent
→ 実際のユーザー操作に近い挙動をテストしたいとき

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?