petermakowski.io

Quick introduction to Testing Library queries

Testing Library queries can be a little confusing at first. This guide should help you get started writing tests without having to know all intricacies of different queries.

Which query should I use?

It's best to query elements by their semantic role and name[1]. Query by text only if the element you're looking for has no semantic role.

<button>Save</button>
getByText("Save")
getByRole("button", { name: "Save" })

Looking for a single element?

use getByRole

Looking for multiple elements?

use getAllByRole

Testing that something doesn’t exist?

use queryByRole

Testing Library queries in more depth

If you're interested in knowing more about the queries it's useful to know how their names are constructed.

You can divide all queries into 2 main categories:

The categories above can be divided further into 2 subcategories:

Single element queries

getBy, queryBy, findBy
throw an error when more than 1 match is found

Multiple elements queries

getAllBy, queryAllBy, findAllBy
do not throw an error when more than 1 match is found

Finally, the above can be combined with
role, text, labelText, placeholderText to construct an actual query.

Testing user interactions

It's best to use @testing-library/user-event, a companion library that provides advanced simulation of browser interactions.

The 3 user-event methods below are really all you need
(most of the time):


  1. By default, many semantic elements in HTML have a role; for example, <input type="radio"> has the "radio" role. You can check an element's role by opening developer tools and accessibility properties. More on this in Using ARIA: Roles | MDN ↩︎