Sub topic 4
Choosing between getBy, queryBy, and findBy
Every Testing Library query comes in three variants: getBy, queryBy, and findBy. They find elements the same way, but they differ in what they do when no element matches and in whether they wait. Picking the wrong variant gives you flaky tests, misleading failures, or assertions that can never fail.
This chapter assumes you can write a basic React component and a Jest or Vitest test, and that you know how render and screen work from the previous chapter. It also assumes you are comfortable with promises and async/await.
The three variants at a glance
The prefix tells you the behavior. The suffix (ByRole, ByLabelText, ByText, and so on) tells you how the element is found. The suffix works the same way in all three variants.
| 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 All forms exist for cases where several matches are expected:
| Variant | No match | One or more matches | Waits? |
|---|---|---|---|
| `getAllBy` | Throws an error | Returns an array | No |
| `queryAllBy` | Returns an empty array | Returns an array | No |
| `findAllBy` | Rejects after the timeout | Resolves with an array | Yes |
Note that the singular variants fail on multiple matches. getByRole('button') throws if the page contains two buttons. This is intentional. It forces you to make the query more specific, usually by adding a name option.
getBy: the element must be there now
Use getBy when the element should already be in the document at the moment you query. This is the default choice for most assertions about what is currently on screen.
// Greeting.jsx
export function Greeting({ name }) {
return <h1>Welcome, {name}</h1>;
}
// Greeting.test.jsx
import { render, screen } from '@testing-library/react';
import { Greeting } from './Greeting';
test('shows the name in a heading', () => {
render(<Greeting name="Ada" />);
const heading = screen.getByRole('heading', { name: 'Welcome, Ada' });
expect(heading).toBeInTheDocument();
});The useful property of getBy is its error message. When nothing matches, it throws with a description of what it looked for and prints the current DOM, so a failing test points at the cause. This is why getBy is also fine for presence assertions. Even without an explicit expect, the query itself fails the test if the element is missing. Many people still add toBeInTheDocument() because it states the intent.
queryBy: the element might not be there
queryBy returns null instead of throwing. Its main job is asserting absence, which getBy cannot do because it throws before your assertion runs.
// Banner.jsx
import { useState } from 'react';
export function Banner({ message }) {
const [open, setOpen] = useState(true);
if (!open) return null;
return (
<div role="status">
{message}
<button onClick={() => setOpen(false)}>Dismiss</button>
</div>
);
}
// Banner.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Banner } from './Banner';
test('removes the banner when dismissed', async () => {
const user = userEvent.setup();
render(<Banner message="Saved" />);
expect(screen.getByRole('status')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Dismiss' }));
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});The test uses getBy before the click, to prove the banner exists, and queryBy after it, to prove the banner is gone. If the first assertion used queryBy, a typo in the query would return null and the test would fail with a vague message. If the last assertion used getBy, the test would fail with a thrown error instead of passing.
findBy: the element will appear later
findBy returns a promise. It checks for the element immediately and then keeps checking until it appears or the timeout passes. Use it when the UI changes after something asynchronous, such as a fetch, a timer, or a state update after a promise resolves.
// UserGreeting.jsx
import { useEffect, useState } from 'react';
export function UserGreeting({ loadUser }) {
const [user, setUser] = useState(null);
useEffect(() => {
loadUser().then(setUser);
}, [loadUser]);
if (!user) return <p>Loading...</p>;
return <h1>Hello, {user.name}</h1>;
}
// UserGreeting.test.jsx
import { render, screen } from '@testing-library/react';
import { UserGreeting } from './UserGreeting';
test('shows a loading state, then the user name', async () => {
const loadUser = jest.fn().mockResolvedValue({ name: 'Ada' });
render(<UserGreeting loadUser={loadUser} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
});All three variants appear here, each in the right place. getBy checks the initial synchronous state. findBy waits for the result. queryBy confirms the loading text is gone.
How findBy works
findBy is waitFor wrapped around getBy. It retries the query every 50 ms, and also re-runs it when the DOM changes. It gives up after 1000 ms by default. When it gives up, it rejects with the last error from getBy, so you still get the DOM dump.
You can raise the timeout for a single call:
const heading = await screen.findByRole(
'heading',
{ name: 'Hello, Ada' },
{ timeout: 3000 }
);The query options come second and the wait options come third. A long timeout only costs time when the test would otherwise fail, because a passing findBy returns as soon as the element appears.
Always await findBy
findBy returns a promise. Without await, the assertion receives a promise, not an element. expect(promise).toBeInTheDocument() throws an error about an invalid value. In some setups the test finishes before the promise settles and the failure shows up as an unrelated error in a later test. If a test mixes findBy with other code, check that the await is there first.
Choosing the right variant
Ask two questions. Should the element exist right now? If not, will it exist later?
In short:
- Present now:
getBy. - Absent now:
queryBy, with.not.toBeInTheDocument(). - Present after async work:
await findBy. - Several expected: use the
Allform of the same variant, for examplegetAllByRole('listitem').
Waiting for something to disappear
findBy only waits for presence. To wait for an element to go away, use waitForElementToBeRemoved, which takes a function or an element that is currently in the document.
import { screen, waitForElementToBeRemoved } from '@testing-library/react';
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));The element must be present when you call it. If it is already gone, the call throws. That is why the earlier UserGreeting test asserts getByText('Loading...') first.
Working with the All variants
The All variants are most useful for lists. getAllByRole returns an array you can check by length or by content.
// TodoList.jsx
export function TodoList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
// TodoList.test.jsx
import { render, screen } from '@testing-library/react';
import { TodoList } from './TodoList';
test('renders one list item per todo', () => {
render(<TodoList items={['Write tests', 'Ship']} />);
const items = screen.getAllByRole('listitem');
expect(items).toHaveLength(2);
expect(items[0]).toHaveTextContent('Write tests');
});
test('renders no items for an empty list', () => {
render(<TodoList items={[]} />);
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
});In the second test getAllByRole would throw, so queryAllByRole is the correct choice for asserting an empty result.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `expect(screen.getByText('x')).not.toBeInTheDocument()` | `getBy` throws before `expect` runs | Use `queryBy` |
| `await screen.findByText('x')` to assert absence | Waits the full timeout, then rejects | Use `queryBy`, or `waitForElementToBeRemoved` |
| `getBy` right after an async update | Fails because the element is not rendered yet | Use `await findBy` |
| `findBy` without `await` | Assertion runs on a promise | Add `await` |
| `await waitFor(() => screen.getByText('x'))` | Works, but more code than needed | Use `await screen.findByText('x')` |
| `getByRole('button')` with two buttons | Throws "multiple elements" | Add `{ name: '...' }` or use `getAllByRole` |
Exercise
A component shows a spinner with the text "Loading" while it fetches, then replaces it with a table. You want a test that renders the component, confirms the spinner is shown, waits for the table, and confirms the spinner is gone. Which query variant do you use for each of the three steps, and why?
Show answer
Use getByText('Loading') for the first step, because the spinner is in the DOM synchronously after render and getBy gives a useful error if it is missing. Use await screen.findByRole('table') for the second step, because the table appears after async work and findBy waits for it. Use queryByText('Loading') with .not.toBeInTheDocument() for the third step, because the element should be absent, and queryBy returns null instead of throwing.
Exercise
This test fails with "Unable to find an element with the text: Saved". Explain the bug and fix it.
test('shows a saved message after clicking', async () => {
const user = userEvent.setup();
render(<SaveButton />);
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(screen.getByText('Saved')).toBeInTheDocument();
});
The component calls an async save() function and sets the message after it resolves.
Show answer
getByText checks once, immediately after the click, before the promise from save() has resolved, so the message is not rendered yet. Replace the last line with expect(await screen.findByText('Saved')).toBeInTheDocument();. findBy retries until the message appears or the 1000 ms timeout passes.