Prefer accessible queries with (React) Testing Library

Published on in Accessibility, JavaScript, React and Testing

Accessible queries take into account the semantic meaning of HTML elements. Such queries help you write more accessible apps.

Your app probably has lots of text in various kinds of HTML elements:

  • headings (<h1><h6>),
  • paragraphs (<p>),
  • form labels (<label>)
  • etc.

What is the semantic meaning of each element?

Does your app have, or should it have, meaningful text in elements without a semantic meaning? Apart from plain paragraphs, probably not!

Testing Library's methods getByText(), queryByText() and findByText() search for all elements; they don't care about the elements' semantic meanings. Because most text should be in elements with specific semantic meanings, these methods should be used sparingly.

For example, don't look for a button using the getByText() method because the test could pass even if the button was implemented in a hacky way[1]. Use the getByRole() method instead:

getByRole('button', { name: /submit/i })

This ensures that the button you are looking for is implemented properly and in an accessible way.

So: prefer more specific queries than the basic *ByText() methods. See list of recommended prioritizations of the different queries.


  1. Think of a <div> with a click handler. Don't do it, kids – use a <button>.