2
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 の要素検索(getByText / getByRole / getByLabelText)についてまとめてみた

Posted at

はじめに

React Testing Library を使ってテストを書いているときに、要素を探すのにすこし苦労したので、必要なところだけ整理します。

1. getByText

screen.getByText("Hello");

getByText は、文字に一致する要素を探すときに使います。
その文字が画面に「必ず存在する」と分かっている場合に使うと便利です。
例えば、見出しやボタンに表示されている固定のテキストなど、シンプルに文字で確認したいケースで使います。

2. getByRole

screen.getByRole("button", { name: /送信/i });

getByRole は、要素の「役割」(button, link, heading など)を指定して探す方法です。

3. getByLabelText

screen.getByLabelText("ユーザー名");

getByLabelText は、入力フォームをラベルに基づいて探すときに使います。

まとめ

  • テキストで探す → getByText

  • 役割で探す → getByRole

  • フォームをラベルで探す → getByLabelText

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