Sub topic 6
Debugging when a query cannot find an element
This chapter assumes you can write a basic React Testing Library test with render, screen, and the getBy, queryBy, and findBy variants. It also assumes you know the query priority order (role, label, text, test ID). Here you will learn to read a failing query's output, inspect the DOM the test sees, and match the failure to its usual cause.
Why queries fail
A query fails when the DOM your test sees does not match what you pictured. The component is almost never "broken" in a mysterious way. The usual causes are:
- The element is not rendered yet (timing).
- The element is rendered but hidden from the accessibility tree.
- The accessible name or text differs from what you wrote.
- The text is split across several elements.
- A label is not connected to its control.
- More than one element matches.
- The component rendered something other than what you assumed, such as an error state or a different branch of a conditional.
Debugging means finding out which of these applies. Do not change the query at random until it passes.
Read the error message first
Every getBy and findBy failure prints a message with the query, and usually a snapshot of the DOM. For ByRole queries it also lists the roles that do exist. Take this component:
import { render, screen } from '@testing-library/react';
function Toolbar() {
return (
<div>
<button>Save draft</button>
<button aria-label="Close dialog">×</button>
</div>
);
}
test('finds the close button', () => {
render(<Toolbar />);
screen.getByRole('button', { name: 'Close' });
});The test fails with output similar to this (shortened here):
TestingLibraryElementError: Unable to find an accessible element with the role "button" and name "Close"
Here are the accessible roles:
button:
Name "Save draft":
<button />
Name "Close dialog":
<button
aria-label="Close dialog"
/>The message shows that the button exists and that its accessible name is Close dialog. A string name must match the whole name, case-sensitive. The fix is { name: 'Close dialog' }, or a regular expression such as { name: /close/i }.
Reading the roles list this way solves most ByRole failures without any other tool.
Print the DOM with screen.debug
When the error message is not enough, print the DOM. screen.debug() writes the current document.body to the console in a readable, indented form.
import { render, screen } from '@testing-library/react';
function Profile() {
return (
<section>
<h1>
Hello, <strong>Ada</strong>
</h1>
<p>Role: admin</p>
</section>
);
}
test('shows the greeting', () => {
render(<Profile />);
screen.debug(); // whole document body
screen.debug(screen.getByRole('heading')); // one element
screen.debug(screen.getByRole('heading'), 300); // one element, truncated to 300 characters
});Three details matter in practice:
- Call
screen.debug()before the failing query. A failinggetBythrows, so any line after it never runs. - Output is truncated at 7000 characters by default. For large components, pass a limit as the second argument, or set the
DEBUG_PRINT_LIMITenvironment variable, for exampleDEBUG_PRINT_LIMIT=20000 npx jest. prettyDOM(element)returns the same formatted string instead of printing it. Use it when you want to put the markup in your own message.
Inspect roles with logRoles
If ByRole is failing and you do not know which roles your markup produces, print them. logRoles takes a container and lists every role with its elements.
import { render, logRoles } from '@testing-library/react';
function SearchBox() {
return (
<form role="search">
<label htmlFor="q">Search</label>
<input id="q" type="text" />
<button type="submit">Go</button>
</form>
);
}
test('lists the roles in SearchBox', () => {
const { container } = render(<SearchBox />);
logRoles(container);
});The output lists search, textbox, and button, each with its accessible name. This shows, for instance, that an <input type="text"> is a textbox and not an input, and that <div onClick> has no role at all.
Use Testing Playground
screen.logTestingPlaygroundURL() prints a link to Testing Playground, a web page that loads your rendered DOM. You can click an element and the page suggests the best query for it, following the same priority order covered in the previous chapter. It is a good way to learn which queries work on unfamiliar markup. It is a diagnostic aid, not part of the test, so do not leave it in committed code.
Common causes and how to recognize them
| Symptom in the error | Likely cause | Fix |
|---|---|---|
| Role listed, but name differs | Accessible name is not what you wrote | Copy the name from the roles list, or use a regular expression |
| The role is not in the roles list | Element is hidden, or markup has no such role | Check `aria-hidden`, `display: none`, and semantic elements |
| Text visible in debug output, `getByText` fails | Text is split across elements | Query by role with a `name`, or use a function matcher |
| "Found a label ... however no form control was found" | Label is not connected to the input | Add `htmlFor` and `id`, or wrap the input in the label |
| "Found multiple elements" | Query is too broad | Add `name`, scope with `within`, or use `getAllBy` |
| Element absent now, present later | Async rendering | Use `findBy` or `waitFor` |
| Wrong content in debug output | Test setup differs from your assumption | Check props, mocks, and providers |
Hidden elements
ByRole queries ignore elements that are not accessible. That includes elements inside aria-hidden="true", display: none, visibility: hidden, and the hidden attribute.
import { render, screen } from '@testing-library/react';
test('menu button inside an aria-hidden region', () => {
render(
<div aria-hidden="true">
<button>Menu</button>
</div>
);
expect(screen.queryByRole('button', { name: 'Menu' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Menu', hidden: true })).toBeInTheDocument();
});Passing hidden: true is correct when the element is intentionally hidden and you want to check it exists. If a user should be able to reach the element, the better fix is in the component, because the query is telling you something real about accessibility. Modal libraries often set aria-hidden on the rest of the page while a dialog is open, which makes elements behind the dialog unreachable by role. That is expected behavior.
Text split across elements
getByText matches an element by its own text nodes. In the Profile component above, the h1 has the text nodes Hello, and the strong holds Ada, so getByText('Hello, Ada') fails. A role query computes the accessible name from all descendants, so this works:
expect(screen.getByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();By default, text matching also trims leading and trailing whitespace and collapses repeated whitespace, so extra spaces in your JSX are not the cause. Matching is case-sensitive and exact for strings. If the query is close but not exact, try a regular expression such as /hello/i.
Labels that are not connected
getByLabelText needs a real association between label and control. This markup looks right but is not connected:
<label>Email</label>
<input id="email" />The error reads: Found a label with the text of: Email, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly. Fix the component with <label htmlFor="email">. Treat this as a real accessibility bug, not just a test problem.
Multiple matches
A query that matches more than one element fails with Found multiple elements. Narrow the query before reaching for getAllBy:
import { render, screen, within } from '@testing-library/react';
test('deletes from the second row only', () => {
render(
<ul>
<li>
Ada <button>Delete</button>
</li>
<li>
Grace <button>Delete</button>
</li>
</ul>
);
const rows = screen.getAllByRole('listitem');
expect(within(rows[1]).getByRole('button', { name: 'Delete' })).toBeInTheDocument();
});within runs the same queries scoped to one element. It is also the right tool when the same label appears in several regions of the page.
Timing
If the element is missing in the first debug output but your component fetches data or uses a timer, the query ran too early. Switch to await screen.findBy... or wrap the assertion in waitFor. The next chapters cover this in detail. A quick check: call screen.debug() after an await on the expected result, and you will see the later DOM.
Failures that are not query problems
Sometimes the query is correct and the DOM is wrong. Check these before editing the query:
- The component got different props than you assumed. Print them or check your
rendercall. - A mock returned
undefined, so the component rendered its empty or error state. - A required provider (router, theme, store) is missing, so the component rendered nothing or threw. A custom render helper fixes this, as a later chapter shows.
- The test ran an interaction without
await, so the state change had not happened when the query ran.
In each case screen.debug() shows the real DOM, and comparing it with your mental picture points to the cause.
Exercise
This test fails with "Unable to find an accessible element with the role "button" and name "Submit"". The component renders <button aria-label="Submit form">Go</button>. What does the error's roles list show for this button, and what is the smallest fix to the query?
Show answer
The roles list shows a button with the name "Submit form", because aria-label overrides the visible text "Go" in the accessible name. A string name must match the whole name, so the smallest fix is screen.getByRole('button', { name: 'Submit form' }). A regular expression such as { name: /submit/i } also works.
Exercise
A test renders <div aria-hidden="true"><input aria-label="Coupon" /></div>. screen.getByRole('textbox', { name: 'Coupon' }) throws. Give two ways to make the assertion pass and say which one you would prefer if real users need to use the field.
Show answer
You can pass hidden: true to the query, or remove aria-hidden="true" from the component. If real users need the field, fix the component, because aria-hidden removes the input from the accessibility tree and screen reader users cannot reach it. The hidden: true option is only appropriate when the element is meant to be hidden.