← Back to React, page 2

react-0036 · Medium mid

How do you test React components? What does React Testing Library encourage, and how do you test user interactions?

Use a test runner such as Vitest or Jest with React Testing Library. Render the component, find elements the way a user would (by role, label or text), simulate actions with user-event and assert on what the user sees. Test behaviour, not implementation details such as internal state or component names. Mock only the boundaries, such as network calls and callback props.

Full answer

A good component test answers one question: does the component behave correctly for the user? So tests avoid reaching into state or calling hooks directly. Instead they render the component into a simulated DOM (jsdom), interact with it, and check the screen.

React Testing Library (RTL) provides render and the screen object with queries. The preferred query order follows accessibility: getByRole with a name, getByLabelText for form fields, getByText for content, and getByTestId only as a last resort. Using roles has a second benefit: tests fail when the markup is not accessible.

For interaction, use @testing-library/user-event. userEvent.setup() returns a user with methods like click and type that fire the same events a browser does, including focus and key presses. They are async, so await them. For elements that appear later, use findBy queries, which wait, or waitFor. Use queryBy when you expect an element not to exist.

Assertions come from the runner and from jest-dom matchers such as toBeInTheDocument and toBeDisabled. A callback prop is checked with a mock function: const onSubmit = vi.fn(), then expect(onSubmit).toHaveBeenCalledWith(...). Network calls are best handled with a mock at the network layer, such as Mock Service Worker, so the component's own fetch code is exercised.

Custom hooks can be tested with renderHook. Pure logic, such as reducers, needs no React at all.

Keep a balance. Most tests are small component and hook tests, a few cover a page with several components, and a handful of end-to-end tests with Playwright or Cypress cover critical flows in a real browser. Snapshot tests of large trees tend to break for no reason and are best used sparingly.

jsx
import { useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/vitest';

function Counter({ initial = 0 }) {
  const [count, setCount] = useState(initial);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Add one</button>
    </div>
  );
}

function EmailForm({ onSubmit }) {
  const [email, setEmail] = useState('');
  const invalid = email.length > 0 && !email.includes('@');

  function handleSubmit(event) {
    event.preventDefault();
    onSubmit({ email });
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <input value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
      {invalid && <p role="alert">Enter a valid email</p>}
      <button type="submit" disabled={invalid || email === ''}>
        Send
      </button>
    </form>
  );
}

afterEach(cleanup);

describe('Counter', () => {
  it('starts at the given value', () => {
    render(<Counter initial={5} />);
    expect(screen.getByText('Count: 5')).toBeInTheDocument();
  });

  it('adds one when the button is clicked', async () => {
    const user = userEvent.setup();
    render(<Counter />);
    await user.click(screen.getByRole('button', { name: 'Add one' }));
    expect(screen.getByText('Count: 1')).toBeInTheDocument();
  });
});

describe('EmailForm', () => {
  it('shows an error and disables Send for a bad email', async () => {
    const user = userEvent.setup();
    render(<EmailForm onSubmit={vi.fn()} />);
    await user.type(screen.getByLabelText('Email'), 'asha');
    expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email');
    expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();
  });

  it('calls onSubmit with the typed email', async () => {
    const user = userEvent.setup();
    const onSubmit = vi.fn();
    render(<EmailForm onSubmit={onSubmit} />);
    await user.type(screen.getByLabelText('Email'), 'asha@example.com');
    await user.click(screen.getByRole('button', { name: 'Send' }));
    expect(onSubmit).toHaveBeenCalledWith({ email: 'asha@example.com' });
  });
});

In a real project the components live in their own files and the tests sit next to them. They are in one file here only so the example is complete. The file ran under Vitest with the jsdom environment, and these tests passed on two consecutive runs: Counter > starts at the given value Counter > adds one when the button is clicked EmailForm > shows an error and disables Send for a bad email EmailForm > calls onSubmit with the typed email

Key points

  • Test what the user sees and does, not internal state.
  • Query by role, label or text. Use test ids only when nothing else works.
  • user-event simulates real interactions and is async, so await it.
  • Use findBy for async appearance and queryBy to assert absence.
  • Mock at the boundary (callbacks, network) and keep a few end-to-end tests for key flows.

Common mistakes

  • Testing implementation details such as state values or internal function names.
  • Querying by test id when a role or label query is available.
  • Forgetting to await user-event calls or findBy queries.
  • Using getBy to assert that something is absent. Use queryBy.
  • Large snapshot tests that fail on harmless markup changes.

Follow-ups

  • How would you test a component that fetches data on mount?
  • How do you test a custom hook, and when is renderHook the wrong tool?
  • Which flows would you cover with end-to-end tests instead of component tests?

Tips

  • Say "test what the user sees". It is the core idea of Testing Library.
  • Know the query priority order and why role queries help accessibility.
  • Mention the testing mix: many small tests, a few page tests, a few end-to-end tests.