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?

【Jest】【testing-library】inputフォームをfindByRole()で取得しようとしたらUnable to find role="textbox" and name "xxx"エラー

Last updated at Posted at 2026-01-07

はじめに

@testing-library/reactで、inputフォームをfindByRole()で取得しようとしたときに、以下エラーが発生した時の解決方法をまとめました。

Unable to find role="textbox" and name "xxx"エラー

問題

検査対象のinputフォームとtestファイルは次の通りです。findByRole()で指定しているnameプロパティは、inputフォームのname属性と同じなのに、なぜかエラーになります。

検査対象のinputフォーム
<input
  id="study-content"
  name="study-content"
  type="text"
  value={studyTitle}
  onChange={handleChangeText}
/>
inputForm.spec.js
const contentField = await screen.findByRole("textbox", {
  name: /study-content/i,
});
await userEvent.type(contentField, "TEST");
expect(contentField.value).toBe("TEST");

解決方法

inputフォームにaria-label="xxx"を追加してください。

(修正版)検査対象のinputフォーム
<input
  id="study-content"
  name="study-content"
  aria-label="study-content"
  type="text"
  value={studyTitle}
  onChange={handleChangeText}
/>

aria-label属性とは

視覚的に表示されない要素(アイコンボタンなど)をスクリーンリーダーが読み上げる時のテキストを指定する属性です。

なぜaria-label属性を指定するのか

前提として、findByRole()で指定しているnameは、HTMLのname属性とは別物です。
findByRole()で指定しているnameはスクリーンリーダーで読み上げられるテキストを指しています。
(これは他のfindBy~系のメソッドも同様です。)

この「スクリーンリーダーで読み上げられるテキスト」のことをAccessible Nameといいます。
例えば<button>登録ボタン</butotn>というボタンがあった場合、Accessible Nameは「登録ボタン」になります。

inputフォームにAccessible Nameを付与するため、aria-label属性を追加する必要があります。

おわりに

findByRole()のnameプロパティとHTMLのname属性は同じだという思いこみから、調査に少し手間取りました。どなたかのお役に立てば幸いです。

参考

https://www.w3.org/TR/accname-1.2/
https://testing-library.com/docs/queries/byrole/
https://developer.mozilla.org/ja/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-label

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼
https://projisou.jp

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?