Sub topic 5
Querying by role, label, and text before test IDs
This chapter assumes you can already render a component and call screen.getByX, queryByX, and findByX. It also assumes you know basic HTML semantics: which elements are buttons, links, headings, and form controls, and how a <label> connects to an input. If the query variants are unfamiliar, review them first. This chapter is about which query to choose, not which variant.
Why the order of queries matters
Testing Library has many queries, and most of them can find the same element. The documentation ranks them. The ranking is a decision tool, not a style preference. A query near the top finds an element the way a person or assistive technology (a screen reader, for example) finds it. A query near the bottom finds it through something the user never sees.
Choosing a high-priority query gives you two benefits:
- The test fails when the interface breaks for users. If you query a button by its role and name, the test fails when the button becomes an unlabeled
div. A test ID query would keep passing while a screen reader user could no longer find the control. - The test survives refactors. Changing a
divto asection, or renaming a CSS class, does not change what a user can do, so the test should not change either.
The priority order
| Rank | Query | Finds elements by | Typical use |
|---|---|---|---|
| 1 | `ByRole` | ARIA role plus accessible name | Buttons, links, headings, checkboxes, lists, almost anything interactive |
| 2 | `ByLabelText` | Text of an associated label | Form fields |
| 3 | `ByPlaceholderText` | `placeholder` attribute | Fields with no label (a weak fallback) |
| 4 | `ByText` | Text content of the element | Paragraphs, spans, and other non-interactive content |
| 5 | `ByDisplayValue` | Current value of an input, select, or textarea | Checking pre-filled form values |
| 6 | `ByAltText`, `ByTitle` | `alt` or `title` attribute | Images, icons with a title |
| 7 | `ByTestId` | `data-testid` attribute | Last resort, when nothing user-facing works |
The official guidance groups these as "accessible to everyone" (ranks 1 to 5), "semantic" (rank 6), and "test IDs" (rank 7).
ByRole: the default choice
Every HTML element has an implicit role. <button> is button, <a href> is link, <h1> to <h6> are heading, <input type="checkbox"> is checkbox, <nav> is navigation, and <ul> is list. getByRole matches the role, and its name option matches the element's accessible name, which is the text a screen reader announces.
// Settings.jsx
export function Settings() {
return (
<main>
<h1>Settings</h1>
<nav aria-label="Primary">
<a href="/home">Home</a>
</nav>
<label>
<input type="checkbox" defaultChecked /> Email alerts
</label>
<button>Save</button>
<button>Cancel</button>
</main>
);
}
// Settings.test.jsx
import { render, screen } from '@testing-library/react';
import { Settings } from './Settings';
test('exposes its controls by role and name', () => {
render(<Settings />);
expect(screen.getByRole('heading', { name: 'Settings', level: 1 })).toBeInTheDocument();
expect(screen.getByRole('navigation', { name: 'Primary' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Home' })).toHaveAttribute('href', '/home');
expect(screen.getByRole('checkbox', { name: 'Email alerts', checked: true })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
});Points worth knowing about ByRole:
- The name comes from several sources. The accessible name can come from an element's text, a wrapping or associated
<label>,aria-label, oraria-labelledby. In the test above, the checkbox is named "Email alerts" by its wrapping label. - String names match the whole name.
{ name: 'Save' }does not match "Save draft". Use a regular expression such as/save/ifor partial or case-insensitive matches. Use a string when the exact wording matters. - State filters exist. The options
checked,pressed,selected,expanded, andlevelnarrow the match by state, as the checkbox and heading above show. - Inaccessible elements are skipped. By default,
ByRoleignores elements hidden withdisplay: none,hidden, oraria-hidden="true". This is correct behavior, because a user cannot reach them. Pass{ hidden: true }only when you intentionally want hidden elements. - A missing role is a finding.
<div onClick={...}>Save</div>has no button role, sogetByRole('button')fails. The failure points to a real accessibility defect. Fix the markup rather than switching to a test ID. Likewise, an<a>withouthrefis not a link.
Tests become more precise when you use getAllByRole for repeated elements and choose by name, not by index.
ByLabelText: form fields
For inputs, selects, and textareas, getByLabelText mirrors how a user finds a field: by reading its label. It works with <label for> (htmlFor in JSX), wrapping labels, aria-label, and aria-labelledby.
import { render, screen } from '@testing-library/react';
test('finds fields by their labels', () => {
render(
<form>
<label htmlFor="email">Email</label>
<input id="email" />
<label>
Password
<input type="password" />
</label>
</form>
);
expect(screen.getByLabelText('Email')).toBeInTheDocument();
expect(screen.getByLabelText('Password')).toBeInTheDocument();
});The most common error here is a label that is not connected to its input. If the htmlFor value does not match any id, the query throws an error saying it found a label with that text but no form control associated with it. That error is useful. A user with a screen reader would hear an unnamed field, so fix the component.
For form fields, getByRole('textbox', { name: 'Email' }) and getByLabelText('Email') both work. Prefer ByRole when it supports the control, and use ByLabelText when the role is awkward, such as a password input, which has no role in the ARIA mapping that Testing Library uses.
ByText: visible content
Use getByText for content that has no role of its own, such as a paragraph, a status message, or a list entry. Do not use it for buttons and links, which ByRole finds better.
How matching works:
- A string must match the element's own text exactly, after trimming and collapsing whitespace. Matching is case-sensitive.
- A regular expression matches any part of the text, so
/count/iis the usual way to loosen a match. - Matching uses the text of the element's own text nodes. In
<p>Hello, <strong>Ada</strong></p>, the paragraph's own text is "Hello, ", sogetByText('Hello, Ada')fails. Query the part you can match, then assert on the whole withtoHaveTextContent:
import { render, screen } from '@testing-library/react';
test('greets the user across nested elements', () => {
render(<p>Hello, <strong>Ada</strong></p>);
expect(screen.getByText(/hello/i)).toHaveTextContent('Hello, Ada');
});script and style elements are ignored by default. If one text appears in several places, narrow the match with the selector option or scope it with within.
Scoping with within
When the same label or text appears many times, narrow the search to one region instead of reaching for test IDs. within returns queries bound to one element.
// TodoList.jsx
export function TodoList({ items }) {
return (
<ul aria-label="Todos">
{items.map((item) => (
<li key={item}>
<span>{item}</span>
<button>Delete</button>
</li>
))}
</ul>
);
}
// TodoList.test.jsx
import { render, screen, within } from '@testing-library/react';
import { TodoList } from './TodoList';
test('each row has its own delete button', () => {
render(<TodoList items={['Write tests', 'Ship it']} />);
const list = screen.getByRole('list', { name: 'Todos' });
const rows = within(list).getAllByRole('listitem');
expect(rows).toHaveLength(2);
expect(within(rows[1]).getByText('Ship it')).toBeInTheDocument();
expect(within(rows[1]).getByRole('button', { name: 'Delete' })).toBeEnabled();
});When a test ID is the right tool
getByTestId matches the data-testid attribute. It is a valid escape hatch when no user-facing query can identify the element. Examples include a canvas or chart container whose content a library draws, or a wrapper that carries no text, role, or label.
// Chart.jsx
export function Chart() {
return <div data-testid="revenue-chart" />;
}
// Chart.test.jsx
import { render, screen } from '@testing-library/react';
import { Chart } from './Chart';
test('mounts the chart container', () => {
render(<Chart />);
expect(screen.getByTestId('revenue-chart')).toBeInTheDocument();
});The cost is that test IDs verify nothing about what the user perceives. They also add attributes to production markup. To use a different attribute name, such as data-test, call configure({ testIdAttribute: 'data-test' }) from @testing-library/react once in your setup file.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `getByRole` cannot find a clickable `div` | A `div` has no button role | Use `<button>` |
| Name option fails on partial text | A string name matches the full name | Use a regular expression |
| `getByLabelText` reports a label without a control | `htmlFor` and `id` do not match | Connect the label to the input |
| `getByText` fails on text split by tags | Matching uses the element's own text nodes | Query a part, then use `toHaveTextContent` |
| "Found multiple elements" | The query matches several elements | Add a name, use `within`, or use `getAllBy` |
| Element exists but `ByRole` misses it | It is hidden from accessibility | Check `aria-hidden` and CSS, or pass `hidden: true` deliberately |
Exercise
A component renders <div className="btn" onClick={save}>Save</div>. A test uses screen.getByRole('button', { name: 'Save' }) and fails with an error that no button was found. What should you change, and why is getByTestId the wrong fix?
Show answer
Change the markup to <button onClick={save}>Save</button>. A div has no button role, so keyboard and screen reader users cannot reach it as a button, and the failing query exposes that problem. Adding data-testid would make the test pass but hide the accessibility defect.
Exercise
Given <label htmlFor="user-name">Name</label><input id="username" />, which query finds the input, and what happens with getByLabelText('Name')? How do you fix it?
Show answer
getByLabelText('Name') throws an error saying it found a label with that text but no form control associated with it, because htmlFor="user-name" does not match id="username". Fix the component so the two values match (for example both username). Then getByLabelText('Name') or getByRole('textbox', { name: 'Name' }) finds the input.