Sub topic 14
Common pitfalls and best practices
This chapter assumes you can write a basic test with render, screen, user-event, and jest-dom matchers, and that you know the difference between getBy, queryBy, and findBy. It collects the mistakes that most often make React Testing Library tests brittle or misleading, and shows the fix for each.
Testing implementation details
A test that reads component state, calls internal methods, or checks CSS class names breaks when you refactor, even if the user sees no change. Assert on what the user can see or do instead.
// Brittle: depends on a class name
expect(container.querySelector('.counter-value').textContent).toBe('1');
// Better: depends on what the user sees
expect(screen.getByText('Count: 1')).toBeInTheDocument();If you can rename a variable or switch from useState to useReducer and the test still passes, the test is at the right level.
Reaching for test IDs too early
getByTestId finds elements the user cannot identify, so it proves nothing about accessibility. Prefer getByRole, then getByLabelText, then getByText. Use test IDs only when no accessible query fits.
Misusing waitFor
waitFor retries a callback until it stops throwing. Two habits cause trouble.
- Putting side effects inside it. The callback can run many times, so a click inside
waitFormay fire repeatedly. - Using it where
findByis enough.findByisgetBypluswaitFor, with clearer errors.
// Avoid
await waitFor(() => {
expect(screen.getByText('Saved')).toBeInTheDocument();
});
// Prefer
expect(await screen.findByText('Saved')).toBeInTheDocument();Use waitFor for assertions that are not element lookups, such as expect(handler).toHaveBeenCalled(). Keep one assertion in each callback.
Asserting absence with the wrong query
getBy throws when nothing matches, so it cannot check that an element is missing. Use queryBy with not.toBeInTheDocument(). To wait for an element to disappear, use waitForElementToBeRemoved or waitFor.
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();Skipping await on user-event
Every user-event call returns a promise. Without await, the assertion runs before the interaction finishes, and the test fails or passes by accident. Create the instance with userEvent.setup() before render, and await each call.
Wrapping everything in act
RTL already wraps render, user-event, findBy, and waitFor in act. Adding your own act around them is noise. You need act mostly for direct state updates, as in renderHook tests. An "not wrapped in act" warning usually means an update happened after the test ended. Fix it by awaiting the final UI change, not by silencing the warning.
Shared state between tests
Mocks keep call counts, and rendered output can leak between tests. RTL unmounts rendered components automatically after each test in Jest and in Vitest with globals enabled. Reset mocks yourself with jest.clearAllMocks() in afterEach, or set clearMocks: true in the Jest config. Each test should set up its own data and not rely on the order of tests.
Over-mocking
Mocking child components or your own modules hides integration bugs. Mock at the boundary instead: the network, timers, or browser APIs. Rendering the real child tree gives you tests closer to real use.
Best practices checklist
| Practice | Reason |
|---|---|
| Query by role and accessible name | Matches how users and assistive tools find elements |
| Use `screen` instead of destructured queries | Shorter and always current |
| Use `userEvent`, not `fireEvent` | Fires the full event sequence a browser does |
| Write one behavior per test | Failures point to one cause |
| Use `findBy` for async results | Retries without manual loops |
Choosing the right tool
Exercise
A test clicks a "Save" button and then runs await waitFor(() => { user.click(screen.getByText('Confirm')); });. Name two problems and give a better version.
Show answer
The click is a side effect inside waitFor, so it can run several times, and it is not awaited. Click outside the callback with await user.click(await screen.findByRole('button', { name: 'Confirm' }));. Then assert the result with findBy or a waitFor that holds only an assertion.
Exercise
You want to confirm a "Loading..." message is gone after data arrives. Which query do you use, and why not getByText?
Show answer
Use queryByText('Loading...') with not.toBeInTheDocument(). getByText throws when the element is missing, so the test would fail for the very condition you expect.