4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React testing libraryでgetByRoleのnameオプションがうまく動かない

Last updated at Posted at 2022-08-25

React testing libraryのgetByRoleで同じロール[textbox]が複数存在したので、
nameで絞ろうとしたときうまく取れなかった時の話。

hoge.test.js
test('renders react component', () => {
  render(<TestText value={"hoge"} name="fuga"/>);
  const divElement = screen.getByRole('textbox',{name: /fuga/i });
  expect(divElement).toBeInTheDocument();
});
.html
<input
  name="fuga"
  value="hoge"
/>

以下のエラーになってしまう。
nameがhtmlにあるのにヒットしない??

  ● renders react component
    TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/fuga/i`
    Here are the accessible roles:

結論としてはaria-label属性をinputにつければうまくいった。

<input
  aria-label="fuga"
  value="hoge"
/>

公式ドキュメントに書いてました。
https://testing-library.com/docs/queries/byrole/
image.png

さらにnameについて詳しく書いてます。
https://developer.paciellogroup.com/blog/2017/04/what-is-an-accessible-name/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?