Testing components
Overview
Tests let you change code with confidence: refactor a component, upgrade a library or add a feature, and know within seconds whether anything broke. For React, the standard toolkit is Vitest (a fast test runner that shares Vite’s configuration) and React Testing Library (utilities for rendering components and interacting with them like a user would).
Setup
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom// vite.config.js
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom', // a simulated browser DOM
setupFiles: ['./vitest.setup.js'],
},
});// vitest.setup.js
import '@testing-library/jest-dom/vitest'; // adds matchers like toBeInTheDocument
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => cleanup()); // unmount components between tests// package.json
"scripts": {
"test": "vitest"
}npm test runs in watch mode, re-running affected tests as you save. Name test files *.test.jsx next to the code they test.
Your first test
// Counter.test.jsx
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 when clicked', async () => {
const user = userEvent.setup();
render(<Counter />);
const button = screen.getByRole('button', { name: /clicked 0 times/i });
await user.click(button);
expect(button).toHaveTextContent('Clicked 1 times');
});The pattern is always arrange → act → assert: render the component, interact with it, check what’s on screen.
Test behaviour, not implementation
Testing Library’s guiding principle: the more your tests resemble the way your software is used, the more confidence they give you. So test what a user can see and do:
- ✓ “after clicking Add, the new item appears in the list”
- ✗ “after clicking Add,
todosstate has length 1” - ✗ “the component calls
setTodos”
Tests written against behaviour survive refactoring — switch useState to useReducer or Zustand and they still pass. Tests written against internals break every time you change how something works, even if what it does is the same.
Finding elements
Prefer queries that reflect how users — including screen-reader users — find things:
screen.getByRole('button', { name: 'Enrol' });
screen.getByRole('heading', { name: 'React', level: 1 });
screen.getByRole('link', { name: /view course/i });
screen.getByRole('checkbox', { name: 'Free only' });
screen.getByRole('textbox', { name: 'Email' });
screen.getByLabelText('Password');
screen.getByText('No courses match your search');A pleasant side effect: if you can’t find an element by role and name, it’s probably not accessible — your tests nudge you towards better HTML. screen.debug() prints the current DOM, and screen.logTestingPlaygroundURL() suggests the best query for any element.
getBy, queryBy, findBy
| Variant | When nothing matches | Use for |
|---|---|---|
getBy… |
throws | elements that should be there now |
queryBy… |
returns null |
asserting something is not there |
findBy… |
waits (up to 1 s), then throws | elements that appear asynchronously |
getAllBy… / queryAllBy… / findAllBy… |
— | multiple matches |
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(await screen.findByText('Saved!')).toBeInTheDocument();Simulating user interaction
user-event simulates complete interactions — a click includes pointer and focus events; typing fires keydown, input and keyup for every character:
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'Add' }));
await user.type(screen.getByLabelText('Course title'), 'React hooks');
await user.clear(screen.getByLabelText('Course title'));
await user.selectOptions(screen.getByLabelText('Level'), 'advanced');
await user.keyboard('{Enter}');
await user.tab(); // move focus like the Tab keyCall userEvent.setup() at the start of each test and await every action. (fireEvent from Testing Library dispatches single DOM events; it’s lower-level and occasionally useful, but user-event is closer to reality.)
jest-dom matchers
@testing-library/jest-dom adds readable assertions about the DOM:
expect(element).toBeInTheDocument();
expect(button).toBeDisabled();
expect(input).toHaveValue('asha@example.com');
expect(checkbox).toBeChecked();
expect(element).toHaveTextContent(/3 items/);
expect(element).toHaveClass('active');
expect(element).toBeVisible();
expect(input).toHaveAccessibleDescription('Enter a valid email');
expect(input).toHaveFocus();Testing props and callbacks
Pass mock functions to check that a component calls its callbacks correctly:
import { vi } from 'vitest';
test('calls onSelect with the course id', async () => {
const user = userEvent.setup();
const onSelect = vi.fn();
render(<CourseCard course={{ id: 7, title: 'React' }} onSelect={onSelect} />);
await user.click(screen.getByRole('button', { name: 'View course' }));
expect(onSelect).toHaveBeenCalledWith(7);
});Re-render with new props using the rerender function returned by render:
const { rerender } = render(<Badge count={1} />);
rerender(<Badge count={5} />);
expect(screen.getByText('5')).toBeInTheDocument();Components that need providers
Components that use context, routers or query clients need those providers in tests. Write a small helper:
// test-utils.jsx
import { render } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
export function renderWithProviders(ui) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={queryClient}>
<CartProvider>{ui}</CartProvider>
</QueryClientProvider>
);
}For routing, render your routes with createMemoryRouter(routes, { initialEntries: ['/courses/react'] }) and <RouterProvider> to start on any URL.
What to test
Focus on what matters most to users and what’s most likely to break:
- the main paths: adding to the cart, submitting a form, filtering a list,
- edge cases: empty lists, validation errors, very long text,
- bug fixes — write a test that reproduces the bug before fixing it.
Don’t test React itself (that useState works), or third-party libraries, or every visual detail. For full user journeys across many pages, add a few end-to-end tests with Playwright, which drives a real browser against your running app.
A good test reads like a user story: “when I type a title and click Add, the course appears in the list.” If yours reads like a description of your code, it’s probably testing implementation details.
Test the to-do list
Write tests for the TodoList from *Updating objects and arrays* (an input labelled “New todo”, an “Add” button, a checkbox per todo labelled with its text, a “Delete” button per todo and a “Clear completed” button). Cover: adding two todos clears the input and shows both; empty input adds nothing; ticking a todo then clicking “Clear completed” removes only that one; deleting removes the right item. Use getByRole/getByLabelText and userEvent.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, test } from 'vitest';
import { TodoList } from './TodoList.jsx';
describe('TodoList', () => {
// your tests here
});import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, test } from 'vitest';
import { TodoList } from './TodoList.jsx';
async function addTodo(user, text) {
await user.type(screen.getByRole('textbox', { name: 'New todo' }), text);
await user.click(screen.getByRole('button', { name: 'Add' }));
}
describe('TodoList', () => {
test('adds todos and clears the input', async () => {
const user = userEvent.setup();
render(<TodoList />);
await addTodo(user, 'Read the docs');
await addTodo(user, 'Do the exercise');
expect(screen.getAllByRole('listitem')).toHaveLength(2);
expect(screen.getByRole('textbox', { name: 'New todo' })).toHaveValue('');
});
test('ignores empty input', async () => {
const user = userEvent.setup();
render(<TodoList />);
await user.click(screen.getByRole('button', { name: 'Add' }));
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
});
test('clears only completed todos', async () => {
const user = userEvent.setup();
render(<TodoList />);
await addTodo(user, 'Done one');
await addTodo(user, 'Still to do');
await user.click(screen.getByRole('checkbox', { name: 'Done one' }));
await user.click(screen.getByRole('button', { name: 'Clear completed' }));
expect(screen.queryByText('Done one')).not.toBeInTheDocument();
expect(screen.getByText('Still to do')).toBeInTheDocument();
});
test('deletes the right todo', async () => {
const user = userEvent.setup();
render(<TodoList />);
await addTodo(user, 'First');
await addTodo(user, 'Second');
const [firstDelete] = screen.getAllByRole('button', { name: 'Delete' });
await user.click(firstDelete);
expect(screen.queryByText('First')).not.toBeInTheDocument();
expect(screen.getByText('Second')).toBeInTheDocument();
});
});Summary
- Vitest runs tests; React Testing Library renders components into a simulated DOM (jsdom) and queries it.
- Test behaviour the user sees, not implementation details like state or component internals.
- Prefer
getByRolewith an accessible name, thengetByLabelTextandgetByText;getByTestIdis a last resort. - Simulate real interactions with
userEvent.setup()and await each action. getBythrows if missing,queryByreturns null (for asserting absence),findBywaits for async content.