Testing components

Topic 1 of 2 in Testing8 min readIntermediateFree course

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

Terminal
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
JavaScript
// 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'],
  },
});
JavaScript
// 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
JSON
// 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

JSX
// 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, todos state 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

Query priority in Testing Library: getByRole with a name such as ‘button’, { name: ‘Save’ } matches how users find things; getByLabelText(‘Email’) for form fields; getByText(‘No courses yet’) for non-interactive text; getByTestId(‘chart-canvas’) is a last resort because users can’t see test ids. Example: await user.click(screen.getByRole(‘button’, { name: /save/i })).

Prefer queries that reflect how users — including screen-reader users — find things:

JSX
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
JSX
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:

JSX
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 key

Call 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:

JSX
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:

JSX
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:

JSX
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:

JSX
// 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.

Exercise

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.

JavaScript
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
});

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 getByRole with an accessible name, then getByLabelText and getByText; getByTestId is a last resort.
  • Simulate real interactions with userEvent.setup() and await each action.
  • getBy throws if missing, queryBy returns null (for asserting absence), findBy waits for async content.