Explain it simply
Explain it simply
A component test asks a robot user to use your app and then checks the result. The robot finds the button called "Add", clicks it, and looks for "Count: 1" on the screen. It never looks at your state variable names or CSS class names.
The interesting part: the robot finds elements by role and name, the way a screen reader user does. A button the robot cannot find is also hard to find for people who use screen readers. So while writing tests, you are checking accessibility at the same time.
Problem → Why → Solution
The problem: a test that passes but protects nothing
In the SaveBar below, the Save "button" is actually a div with an onClick. The test finds it by CSS class, clicks it and passes. Yet a keyboard user cannot reach the div with Tab, and a screen reader does not announce it as a button. The test cannot see this bug at all.
Worse, if a designer renames btn-primary to btn-main, the test fails even though nothing about the behaviour changed. It is a test that stays silent when things really break and complains when they do not.
// SaveBar.jsx renders: <div className="btn-primary" onClick={save}>Save</div>
test('saves', () => {
const { container } = render(<SaveBar />);
fireEvent.click(container.querySelector('.btn-primary')); // finds by CSS class
expect(container.querySelector('.toast').textContent).toBe('Saved');
});Why is this test weak?
The test depends on things users never see, such as class names and DOM structure, so every refactor breaks it, while it never checks what users do see: roles, labels and text. Searching with getByRole('button', { name: 'Save' }) would fail right away because a div is not a button, exposing the accessibility bug.
Core concept: query like a user, act like a user
Testing Library's guiding idea is that the more your tests resemble the way your software is used, the more confidence they give you. Vitest runs the tests, and jsdom provides a simulated browser DOM inside Node. React Testing Library's render() mounts the component into that DOM, and the screen object offers queries that search the whole document.
1. Choose queries in priority order
Reach for getByRole first. Then getByLabelText for form fields, followed by getByPlaceholderText, getByText, getByDisplayValue, getByAltText and getByTitle. getByTestId is the last resort.
2. Act like a person with userEvent
Call userEvent.setup(), then await user.click() and await user.type(). They fire the realistic sequence of focus, keydown and input events, which is closer to reality than a single fireEvent.click().
3. Match the query type to your intent
getBy throws when nothing matches. queryBy returns null, so use it to assert that something is absent. findBy returns a promise that waits until the element appears, which suits UI that shows up after a fetch.
How does getByRole know a button's name? It computes the accessible name the way browsers do: from the button's text, from an aria-label, from a <label> linked to an input through htmlFor and id, or from an image's alt text. So when getByRole('textbox', { name: 'Email' }) fails, it usually points at a missing label rather than a broken test. Prefer visible labels, and keep aria-label for places such as icon-only buttons where visible text does not fit.
| Query | When nothing matches | Use it for |
|---|---|---|
| getByRole(...) | Throws an error | Elements that must be there now |
| queryByRole(...) | Returns null | Asserting absence |
| await findByRole(...) | Rejects after a timeout | Elements that appear later |
- Render into jsdom
- Find elements by role and name
- Click or type with userEvent
- Assert on what the screen shows
When the robot cannot find something, the fix is often to make the component accessible, not to change the test.
General pattern
test('describes what the user sees', async () => {
const user = userEvent.setup();
render(<Component {...props} />);
await user.type(screen.getByLabelText('Field label'), 'some text');
await user.click(screen.getByRole('button', { name: /action/i }));
expect(await screen.findByText('Result')).toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});Three stages: arrange (render), act (what the user does) and assert (what the screen shows). Find elements by label, role and name, and wait for async results with findBy.
Testing a Counter through its accessible button
Here is the Counter under test. The button's text "Add" becomes its accessible name. The test lives next to it as Counter.test.jsx and runs with npx vitest.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import Counter from './Counter.jsx';
test('increments from an accessible button', async () => {
const user = userEvent.setup();
render(<Counter />);
await user.click(screen.getByRole('button', { name: /add/i }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});Code breakdown
- A simulated user
const user = userEvent.setup();Each test starts its own user session. Its methods return promises, so they are awaited.
- Mount into jsdom
render(<Counter />);Counter is rendered into jsdom's document.body, and the screen queries search that document.
- Find by role and name
await user.click(screen.getByRole('button', { name: /add/i }));It finds a button whose accessible name matches "add", ignoring case, and clicks it. Turning the button into a div would make this line fail.
- Assert on visible text
expect(screen.getByText('Count: 1')).toBeInTheDocument();It checks the text the user sees, not the state variable. toBeInTheDocument comes from jest-dom, so it must be imported in a setup file.
Vitest reports one passing test (for example "✓ increments from an accessible button" and a summary like "Tests 1 passed (1)"). toBeInTheDocument() only works once the jsdom environment and the jest-dom matchers are set up.Vitest setup: jsdom, jest-dom and cleanup
By default Vitest runs in a Node environment with no document. Add environment: 'jsdom' to the config and install the jsdom package. A setup file runs before the tests and registers the jest-dom matchers. If Vitest's globals option is off, Testing Library cannot clean up the DOM after each test automatically, so calling cleanup() in afterEach yourself is the safe choice.
// vitest.config.js
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: { environment: 'jsdom', setupFiles: './src/setupTests.js' },
});
// src/setupTests.js
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => cleanup());In real projects
In real projects
In practice, component tests run in CI on every pull request. Teams prioritise user flows that matter, such as a login form, a checkout step or a search filter, and do not test visual details like a button's colour. For components that call an API, tools such as MSW (Mock Service Worker) mock the network so the loading, error and success states can all be tested.
On the accessibility side, eslint-plugin-jsx-a11y warns about problems like an input without a label while you type, and axe-based tools audit the rendered DOM automatically. Automated tools only catch part of the problems, though, so they cannot replace actually using the app with nothing but a keyboard.
Common mistakes
Common mistakes
Checking absence with getBy
expect(screen.getByRole('alert')).not.toBeInTheDocument() fails when there is no alert, because getBy throws before expect even runs. Check absence with queryByRole.
Forgetting to await userEvent
Calling user.click(...) without await lets the assertion run before the click finishes, giving a flaky test that passes one run and fails the next. Await every userEvent method and make the test function async.
Adding data-testid whenever a query fails
When getByLabelText('Email') fails, the input usually has no associated label. Adding data-testid to get past it makes the test pass while the bug for screen reader users stays. Fix the <label htmlFor> first.
Testing internal state
Tests that check whether the count state equals 1, or whether a particular child component rendered, break when you merely swap useState for useReducer, even though users notice no difference. Assert only on what appears on screen.
Best practices
Best practices
- Name tests from the user's point of view: "shows an error when the email is invalid"
- Cover one user flow per test and separate arrange, act and assert with blank lines
- Test the loading, error and empty states as carefully as the happy path
- Before a release, use the app once with only Tab, Enter and Space, without a mouse
Mini challenge
Two tests for a LoginForm
Write two tests for the given LoginForm. The first checks that an invalid email shows an alert and onLogin is not called. The second checks that a valid email calls onLogin with the trimmed email and no alert appears.
- Find the input with getByLabelText and the button with getByRole plus its name
- Use userEvent.setup() and await every method
- Create onLogin with vi.fn() and assert whether it was called
- Assert the alert's absence with queryByRole
// LoginForm.jsx (given):
// <form noValidate onSubmit={handleSubmit}>
// <label htmlFor="email">Email</label>
// <input id="email" name="email" type="email" />
// <button type="submit">Sign in</button>
// {error && <p role="alert">{error}</p>} // 'Enter a valid email.'
// </form>
// handleSubmit trims the email; no '@' -> sets error, else calls onLogin(email)
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test, vi } from 'vitest';
import LoginForm from './LoginForm.jsx';
test('shows an alert for an invalid email', async () => {
// TODO: set up user + onLogin mock, render, type 'not-an-email', click Sign in
// TODO: expect the alert text, expect onLogin not to have been called
});
test('calls onLogin with a trimmed email', async () => {
// TODO: type ' mya@example.com ', submit, check the call and no alert
});Expected: npx vitest run reports both tests passing. If you delete the htmlFor that links the label to the input, both tests fail at getByLabelText.
Show hint
Check screen.getByRole('alert') with toHaveTextContent('Enter a valid email.'). For the mock, use expect(onLogin).not.toHaveBeenCalled() and toHaveBeenCalledWith('mya@example.com').
Show solution
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test, vi } from 'vitest';
import LoginForm from './LoginForm.jsx';
test('shows an alert for an invalid email', async () => {
const user = userEvent.setup();
const onLogin = vi.fn();
render(<LoginForm onLogin={onLogin} />);
await user.type(screen.getByLabelText('Email'), 'not-an-email');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email.');
expect(onLogin).not.toHaveBeenCalled();
});
test('calls onLogin with a trimmed email', async () => {
const user = userEvent.setup();
const onLogin = vi.fn().mockResolvedValue(undefined);
render(<LoginForm onLogin={onLogin} />);
await user.type(screen.getByLabelText('Email'), ' mya@example.com ');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(onLogin).toHaveBeenCalledWith('mya@example.com');
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Tests check the roles, labels and text users see, not class names or state
- Query priority: getByRole, then getByLabelText, and so on, with getByTestId last
- getBy throws, queryBy returns null, findBy returns a promise that waits
- Use userEvent.setup() and await every method
- When a query fails, check the component's accessibility first
React Testing Library Introduction — Testing Library