Sub topic 14
Common pitfalls and best practices
This chapter collects the mistakes that most often make React Testing Library tests brittle, slow, or misleading, and shows the fix for each. It assumes you can already render a component, use screen queries, simulate events with user-event, and write basic async tests with findBy and waitFor. It also assumes you know Jest or Vitest basics such as test, expect, and mock functions.
The guiding rule
A good test fails when the user-visible behavior breaks and passes when you refactor internals. Every pitfall below breaks one half of that rule. Either the test fails on a harmless refactor, or it passes while the feature is broken.
Testing implementation details
Implementation details are things the user cannot see or do: state variable names, CSS class names, component instance methods, the number of renders, or the internal structure of the DOM. Tests that depend on them break when you rename a class or split a component, even though nothing changed for the user.
// Counter.jsx
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p className="counter-value">Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
);
}
// Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Counter } from './Counter';
test('fragile: depends on a class name and DOM position', async () => {
const user = userEvent.setup();
const { container } = render(<Counter />);
await user.click(container.querySelector('div > button'));
expect(container.querySelector('.counter-value').textContent).toBe('Count: 1');
});
test('robust: uses what the user sees', async () => {
const user = userEvent.setup();
render(<Counter />);
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});The first test fails if you rename counter-value or wrap the button in another element. The second keeps passing as long as a button named "Increment" exists and the text updates.
Two related habits cause the same problem:
- Using
container.querySelectorwhen a role, label, or text query would work. Reserve it for rare cases where nothing accessible identifies the element. - Reaching for
getByTestIdfirst. Test IDs are the last resort in the query priority, because users cannot see them and they say nothing about accessibility.
Misusing query variants
The variant you choose changes what the failure means.
| Goal | Use | Why |
|---|---|---|
| Element must be present now | `getBy` | Throws a descriptive error if missing |
| Element must be absent | `queryBy` | Returns `null` instead of throwing |
| Element appears later | `findBy` | Waits and retries until it appears or times out |
| Several matching elements | the `All` forms | Plain variants throw if more than one matches |
The most common mistake is asserting absence with getBy. It throws before your assertion runs, so the failure message is about a missing element instead of your intent.
// Wrong: getBy throws if the element is missing, so this can never pass
expect(screen.getByText('Loading...')).not.toBeInTheDocument();
// Right
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();The reverse mistake is using queryBy for elements that must exist. A null result produces a vague error such as "received value must be an HTMLElement". getBy gives you the DOM dump and a list of available roles.
When an element disappears after an async step, prefer waitForElementToBeRemoved over a waitFor with a queryBy assertion. It also fails clearly if the element was never there to begin with.
Misusing waitFor
waitFor calls your callback repeatedly until it stops throwing or a timeout passes. That behavior leads to several mistakes.
Using waitFor where findBy fits. findBy is getBy wrapped in waitFor. It is shorter and reports better errors.
// Verbose
await waitFor(() => expect(screen.getByText('Hello, Ada')).toBeInTheDocument());
// Preferred
expect(await screen.findByText('Hello, Ada')).toBeInTheDocument();Putting side effects inside the callback. The callback may run many times. A click inside it fires many times.
// Wrong: the click may run on every retry
await waitFor(async () => {
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(screen.getByText('Saved')).toBeInTheDocument();
});
// Right: act once, then wait for the result
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(await screen.findByText('Saved')).toBeInTheDocument();Using an empty or always-passing callback. await waitFor(() => {}) resolves immediately. It does not wait for your component to settle, and it hides a real race. Wait for a specific, visible outcome instead.
Packing many assertions into one callback. Only the first failing assertion appears in the error, and the whole block retries on every failure. Wait for one observable change, then assert the rest normally.
Forgetting to await user-event
In user-event v14, every interaction returns a promise. Without await, the assertion runs before the interaction finishes, and the test either fails randomly or passes for the wrong reason.
// Wrong: the click has not finished when the assertion runs
user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
// Right
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();Also call userEvent.setup() before render, and use the returned user object rather than calling the direct userEvent.click API. Prefer user-event over fireEvent in general. fireEvent.click dispatches one event, while user.click also produces the hover, pointer, and focus events a real click produces. Use fireEvent only for events user-event cannot simulate.
Wrapping things in act by hand
React warns "not wrapped in act(...)" when a state update happens outside a tracked boundary. Testing Library already wraps render, fireEvent, user-event calls, and the async utilities in act. Adding your own act around them is noise.
When you see the warning, the cause is usually one of these:
- The test ended before an async update finished. Await the result with
findByso the test sees the final state. - A promise resolves after the test finishes. Wait for the UI that depends on it.
- You call a hook's updater directly. This is the one place a manual
actbelongs, as in therenderHookexample from the hooks chapter.
Silencing the warning by mocking console.error hides real bugs. Fix the missing wait instead.
Leaking state between tests
Tests that depend on the order they run in are hard to debug. Check these sources of leakage:
- Cleanup. Testing Library unmounts rendered trees after each test automatically, but only if the runner exposes a global
afterEach. Jest does. Vitest does not unless you setglobals: true. Without it, trees pile up indocument.bodyand queries start matching elements from earlier tests. If you keep globals off, register cleanup yourself:
// vitest.setup.js
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';
afterEach(() => {
cleanup();
});- Mocks. Call
jest.clearAllMocks()(orvi.clearAllMocks()) inafterEach, or setclearMocks: truein the config. OtherwisetoHaveBeenCalledTimes(1)fails in a later test because an earlier one called the mock. - Shared module state. Caches, singletons, and
localStoragepersist across tests in one file. Reset them inbeforeEach. - Shared render results. Call
renderinside each test, not at the top of adescribe. Sharing one render across tests couples them.
Over-relying on snapshots and mocks
Large snapshots of rendered output break on every markup change and teach people to approve updates without reading them. Prefer a few targeted assertions about what matters. A small inline snapshot is acceptable for stable, tiny output.
Mocking too much has the opposite cost. If you mock every child component, the test checks that you passed props to a stub, not that the screen works. Mock at the boundary: network requests, timers, and modules that touch the outside world. Keep your own components real.
Choosing queries and assertions deliberately
A few smaller habits pay off:
- Put the accessible name in the query:
getByRole('button', { name: 'Sign in' })also verifies that the button has a usable name. - Use jest-dom matchers such as
toBeDisabled,toHaveValue, andtoHaveTextContentinstead of reading properties by hand. Failure messages are clearer. - Query inside a region with
within(screen.getByRole('list'))when the same text appears in several places. - Prefer
toHaveBeenCalledWithon a mock callback over checking internal state, since the callback is part of the component's public contract. - Keep one behavior per test and give it a name that states the behavior, such as "shows an error when the email is empty".
A quick decision flow
The flow below summarizes how to pick a query and a wait strategy for an element.
Pitfall summary
| Pitfall | Symptom | Fix |
|---|---|---|
| Querying class names or DOM structure | Tests break on refactors | Query by role, label, or text |
| `getBy` for absence | Error about a missing element | Use `queryBy` |
| Side effects in `waitFor` | Duplicate clicks or calls | Act once, then wait |
| Missing `await` on user-event | Flaky or wrong results | Await every `user.*` call |
| Manual `act` around Testing Library calls | Noise, hidden bugs | Remove it and await the UI |
| No cleanup in Vitest | Elements from earlier tests match | Set `globals: true` or call `cleanup` |
| Uncleared mocks | Call counts carry over | Clear mocks after each test |
Exercise
A test clicks a "Delete" button, then runs await waitFor(() => { user.click(screen.getByRole('button', { name: 'Confirm' })); expect(screen.getByText('Deleted')).toBeInTheDocument(); });. Name two problems and rewrite it.
Show answer
The click is inside the waitFor callback, so it can run on every retry, and the click is not awaited, so the assertion can run before it completes. Rewrite: await user.click(screen.getByRole('button', { name: 'Confirm' })); expect(await screen.findByText('Deleted')).toBeInTheDocument();
Exercise
Your Vitest suite passes when each file runs alone, but getByRole('button', { name: 'Save' }) fails with "multiple elements found" when the whole suite runs. What is the most likely cause and the fix?
Show answer
Rendered trees are not being unmounted between tests, because Vitest has no global afterEach unless globals: true is set. Set globals: true in the Vitest config, or call cleanup() from @testing-library/react in an afterEach in your setup file.