はじめに
Reactのテストにおいて Testing LibraryのgetByRoleやqueryByRoleを使って要素を取得したい時が多々あるのですが
HTMLタグとroleの紐付けがよく分からなくて絶望していたところ
WAI-ARIAのドキュメント的なのを教えていただいたのでこちらでまとめます。
HTMLタグとRole(役割)の組み合わせ
使用頻度が高そうなものを抜粋して一覧にしました
| HTMLタグ | role |
|---|---|
| a (hrefあり) | link |
| a (hrefなし) | generic |
| body | generic |
| button | button |
| div | generic |
| form | form |
| h1 to h6 | heading |
| html | document |
| img with alt="some text" | img |
| img with alt="" | presentation |
| img alt属性なし | img |
| input type=button | button |
| input type=checkbox | checkbox |
| input type=email | textbox |
| input type=file | 対応なし |
| input type=hidden | 対応なし |
| input type=image | button |
| input type=month | 対応なし |
| input type=number | spinbutton |
| input type=password | 対応なし |
| input type=radio | radio |
| input type=range | slider |
| input type=reset | button |
| input type=search | searchbox |
| input type=submit | button |
| input type=tel | textbox |
| input type=text | textbox |
| input type=time | 対応なし |
| input type=url | textbox |
| input type=week | 対応なし |
| label | 対応なし |
| li | listitem |
| p | paragraph |
| span | generic |
| table | table |
| tbody | rowgroup |
| textarea | textbox |
| tfoot | rowgroup |
| thead | rowgroup |
| time | time |
使い方の例
使い方の例
screen.getByRole('link') //=> aタグのhrefありの要素を取得できる
screen.queryByRole('spinbutton') //=> inputタグのtype=number を指定している要素を取得できる。
該当要素が複数ある場合
たくさんあるボタンの中から「ボタン1」と書かれたものだけを取得したい
screen.getByRole('button',{name:'ボタン1'})//=>ボタン1と書かれたボタンのみを取得できる。
これらを使いこなせば
data-TestIdを付与しなくても要素の取得ができますね。
参考
WAI-ARIAについてのドキュメント