Sub topic 4
Choosing between getBy, queryBy, and findBy
This chapter assumes you can write a basic React Testing Library test with render and screen, and that jest-dom matchers are already set up. It also assumes you know async/await.
Three prefixes, three behaviors
Every query in Testing Library starts with a prefix. The prefix decides what happens when the element is missing, and whether the query waits.
| Variant | No match | One match | More than one match | Waits? |
|---|---|---|---|---|
| `getBy` | Throws an error | Returns the element | Throws an error | No |
| `queryBy` | Returns `null` | Returns the element | Throws an error | No |
| `findBy` | Rejects after the timeout | Resolves with the element | Rejects | Yes |
The timeout for findBy is 1000 ms by default. Each prefix also has an All form (getAllBy, queryAllBy, findAllBy). The All forms return an array. queryAllBy returns an empty array when nothing matches.
When to use each one
Use getBy when the element must be in the document right now. If it isn't, the thrown error prints the current DOM, which helps you debug. This is your default choice.
Use queryBy only to assert that something is absent. getBy would throw before your assertion could run, but queryBy returns null, and not.toBeInTheDocument() accepts null.
Use findBy when the element appears later, for example after a promise resolves or a timer fires. It polls the DOM and resolves as soon as the element shows up. You must await it.
Worked example
The component below shows a status message after an async save finishes.
// SaveButton.jsx
import { useState } from 'react';
export function SaveButton({ save }) {
const [status, setStatus] = useState('idle');
async function handleClick() {
setStatus('saving');
await save();
setStatus('saved');
}
return (
<div>
<button onClick={handleClick}>Save</button>
{status === 'saving' && <p>Saving...</p>}
{status === 'saved' && <p role="status">Saved</p>}
</div>
);
}
// SaveButton.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SaveButton } from './SaveButton';
test('shows a status after saving', async () => {
const user = userEvent.setup();
const save = jest.fn().mockResolvedValue();
render(<SaveButton save={save} />);
// Absent at first: queryBy returns null instead of throwing.
expect(screen.queryByRole('status')).not.toBeInTheDocument();
// Present now: getBy.
await user.click(screen.getByRole('button', { name: 'Save' }));
// Appears after the promise resolves: findBy waits for it.
expect(await screen.findByRole('status')).toHaveTextContent('Saved');
expect(screen.queryByText('Saving...')).not.toBeInTheDocument();
});Each prefix appears where its behavior fits. In Vitest, replace jest.fn() with vi.fn().
Common errors
- Using
getByto assert absence. The query throws "Unable to find an element" beforeexpectruns. UsequeryBy. - Forgetting
awaitonfindBy. The query returns a promise, so the assertion checks the promise object instead of the element. The test can fail with a confusing message, or finish before the check happens. - Using
findByfor something already on screen. It works, but it hides the fact that the element is not async. PrefergetByso the test says what it means. - Using
queryByfor presence. Anullresult makesexpect(...).toBeInTheDocument()fail, but with a less helpful message thangetBywould give. - Getting "multiple elements" errors.
getBy,queryBy, andfindByfail when more than one element matches. Narrow the query with anameoption or switch to anAllvariant.
Exercise
A test must confirm that an error message with the text "Name is required" is not rendered before the user submits a form. Which query variant should you use, and why does getByText not work here?
Show answer
Use queryByText('Name is required') with expect(...).not.toBeInTheDocument(). getByText throws when no element matches, so the test would fail with an error before the assertion could run. queryByText returns null instead, which the assertion accepts.
Exercise
A component fetches data on mount and then renders a heading "Report". Which variant finds the heading, and what must the test do with it?
Show answer
Use findByRole('heading', { name: 'Report' }) and await it. findBy retries until the heading appears or the timeout (1000 ms by default) passes. Without await, the test would not wait for the data.