input type=“password” の getByRole 失敗と input の暗黙のロール
に公開背景
testing-library でテストを書く際にパスワード入力用の input を特定しようと以下のように記載しました。
screen.getByRole(‘textbox’, {name: “パスワード”})
しかし、Unable to find an accessible element with the role "textbox" and name “パスワード”
というエラーメッセージが表示され要素が特定できませんでした。
原因
type=“password”
にした input 要素は暗黙の役割を持たず、textbox ではないため getByRole
で特定できません。
なので testing-library だけの問題ではなく、 playwright などでもロールに基づいて要素を特定する場合に同じ問題が発生します。
解決策
getByLabelText
を使うことで要素の特定ができます。(playwright ならgetByLabel
)
screen.getByLabelText(‘パスワード’)
input 要素の暗黙のロール一覧
他にも input=“number”
などでも textbox
ロールではなく spinbutton
ロールになるなどタイプによって暗黙のロールが異なるため、mdn を参考に暗黙のロールをまとめました。
type | 暗黙のロール |
---|---|
button | button |
checkbox | checkbox |
color | なし |
date | なし |
datetime-local | なし |
email(list 属性あり) | textbox |
email(list 属性なし) | combobox |
file | なし |
hidden | なし |
image | button |
month | なし |
number | spinbutton |
password | なし |
radio | radio |
range | slider |
reset | button |
search(list 属性がない場合) | searchbox |
search (list 属性がある場合) | combobox |
submit | button |
tel (list 属性がない場合) | textbox |
tel (list 属性がある場合) | combobox |
text | textbox |
time | なし |
url (list 属性がない場合) | textbox |
url (list 属性がない場合) | combobox |
week | なし |