Picking a query function by priority

With the eight ways to query for elements with React Testing Library, it can be hard to pick the most suitable one.

It is often easy to default to something like screen.getByText() - but there are often more suitable selectors.

In this lesson we will cover how to pick the most suitable one.

Why?

The main reason is to make your tests work in the same way as real users do. For example, real users look at form input label text first (not placeholder values or data-testid attributes). So for that example, our test should ideally do the same thing - get a field by its associated label text.

This means if you do this:

<label>Email</label>
<input name="email" />

Your test will fail, until you link the label to the input (with a htmlFor in your JSX, or wrapping the input in the label like this:

<label htmlFor="email">Email</label>
<input id="email" name="email" />

Loading full lesson content & code...

Ready to try running tests for this lesson?