Sub topic 5
Querying by role, label, and text before test IDs
This chapter assumes you can write React function components, run Jest or Vitest tests, and read basic HTML (roles, labels, form elements). It also assumes you know the getBy, queryBy, and findBy variants from the previous chapter.
Why query priority matters
React Testing Library offers several ways to find an element. They are not equal. The library's guidance is to prefer queries that match how a user or assistive technology perceives the page. A test that finds a button by its accessible name breaks when the user-visible behavior breaks. A test that finds it by a CSS class breaks when someone renames the class.
The recommended order, from most to least preferred:
| Priority | Query | Finds elements by |
|---|---|---|
| 1 | `ByRole` | ARIA role and accessible name |
| 2 | `ByLabelText` | Text of an associated `<label>` |
| 3 | `ByPlaceholderText` | Placeholder (weak substitute for a label) |
| 4 | `ByText` | Visible text content |
| 5 | `ByDisplayValue` | Current value of a form control |
| 6 | `ByAltText`, `ByTitle` | `alt` or `title` attributes |
| 7 | `ByTestId` | A `data-testid` attribute |
ByRole first
getByRole matches the role an element exposes to the accessibility tree. A <button> has the role button, an <h1> to <h6> has heading, and an <input type="checkbox"> has checkbox. Use the name option to pick one element among several with the same role.
import { render, screen } from '@testing-library/react';
function Toolbar() {
return (
<div>
<h1>Settings</h1>
<button>Save</button>
<button>Cancel</button>
</div>
);
}
test('finds elements by role and accessible name', () => {
render(<Toolbar />);
expect(screen.getByRole('heading', { name: 'Settings' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});Without name, getByRole('button') would throw here because two buttons match. The name option also doubles as an accessibility check: if the query fails, a screen reader user probably cannot identify the element either.
The name option accepts a string, a regular expression, or a function. Use a regular expression such as /save/i when the exact text may change.
ByLabelText for form fields
For inputs, getByLabelText mirrors what a user does: they read the label and then use the field.
import { render, screen } from '@testing-library/react';
test('finds an input through its label', () => {
render(
<form>
<label htmlFor="email">Email</label>
<input id="email" type="email" />
</form>
);
expect(screen.getByLabelText('Email')).toBeInTheDocument();
});This query also works with aria-label and aria-labelledby. If it fails on a real component, the label is probably not linked to the input, which is a real accessibility bug. Fix the markup rather than switching queries.
ByText for non-interactive content
Use getByText for content that has no role or label, such as paragraphs and status messages.
import { render, screen } from '@testing-library/react';
test('finds a paragraph by its text', () => {
render(<p>Your changes were saved.</p>);
expect(screen.getByText('Your changes were saved.')).toBeInTheDocument();
expect(screen.getByText(/changes were saved/i)).toBeInTheDocument();
});A string argument matches the whole text, ignoring surrounding whitespace and case differences only if you use a regular expression with the i flag. Do not use ByText for buttons or links when ByRole works, because it ignores the element's role.
ByTestId as a last resort
getByTestId finds elements by the data-testid attribute. Users never see that attribute, so a test that depends on it does not prove the element is visible or accessible. Reach for it only when nothing else works, for example with a canvas or an element whose text changes on every render.
import { render, screen } from '@testing-library/react';
test('finds a chart container by test id', () => {
render(<div data-testid="revenue-chart" />);
expect(screen.getByTestId('revenue-chart')).toBeInTheDocument();
});Common mistakes
- Using
getByText('Save')for a button, which also matches a paragraph that says "Save". UsegetByRole('button', { name: 'Save' }). - Forgetting
namewhen several elements share a role. - Adding
data-testideverywhere by habit. - Using
getByPlaceholderTextinstead of fixing a missing label.
Exercise
A form has two inputs labeled "First name" and "Last name", plus a submit button labeled "Register". Which queries would you use to find the "Last name" input and the submit button, and why not use test IDs?
Show answer
Use screen.getByLabelText('Last name') for the input and screen.getByRole('button', { name: 'Register' }) for the button. Both match what a user perceives and also confirm the label link and the button's accessible name work. A test ID would pass even if the label were missing or the button were hidden from assistive technology.
Exercise
screen.getByRole('button') throws an error saying it found multiple elements. What is the smallest change that fixes it while keeping the query user-facing?
Show answer
Add the name option, for example screen.getByRole('button', { name: 'Save' }), so the query matches only the button with that accessible name.