← Back to React, page 7

react-0129 · Medium mid

What is the testing philosophy behind React Testing Library, in what order should you choose queries, and what should (and should not) you mock?

Test the component the way a user experiences it, not its internals. Choose queries in this order: getByRole (with name), getByLabelText, getByPlaceholderText, getByText, getByDisplayValue, getByAltText, getByTitle, and getByTestId only as a last resort. Mock only what you do not own or cannot run in a test: the network, timers, browser APIs and callback props. Do not mock your own child components or hooks, and do not assert on state or implementation details.

Full answer

The guiding principle of Testing Library is: "the more your tests resemble the way your software is used, the more confidence they can give you". A user finds a button by what it says and what role it has, not by a CSS class or a component name. Tests written this way survive refactors and also act as a basic accessibility check.

Query priority, from the documentation:

  1. Accessible to everyone: getByRole (with the name option), getByLabelText, getByPlaceholderText, getByText, getByDisplayValue.
  2. Semantic: getByAltText, getByTitle.
  3. Last resort: getByTestId, because users cannot see test ids.

Variants: getBy throws if not found (use it when the element must exist), queryBy returns null (use it to assert absence), and findBy waits for an element to appear (use it after async work). The All versions return arrays. within(element) scopes a query. screen.logTestingPlaygroundURL() and getByRole error messages suggest better queries.

Interactions use @testing-library/user-event, which simulates real sequences (focus, key down, input, key up) and is more realistic than fireEvent.

What to mock:

  • The network (with Mock Service Worker, or a stubbed fetch in small tests), because tests must not depend on a server.
  • Time (fake timers) for debounce, polling and animations.
  • Browser APIs that jsdom lacks (matchMedia, IntersectionObserver).
  • Callback props, with vi.fn() or jest.fn(), to assert how the component reports events.

What not to mock: your own child components (a test of a page should render its real children), your own custom hooks, and React itself. Mocking internals makes tests pass while the real integration is broken. Do not test state values, instance methods or the number of renders.

Prefer a few integration tests of whole features over many shallow ones, and keep end-to-end tests for critical flows.

The example runs a test file that uses accessible queries and a callback mock.

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

function Newsletter({ onSubscribe }) {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    if (!email.includes('@')) {
      setError('Enter a valid email');
      return;
    }
    setError('');
    onSubscribe(email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <h2>Newsletter</h2>
      <label>
        Email address
        <input value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
      {error && <p role="alert">{error}</p>}
      <ul aria-label="Topics">
        <li>React</li>
        <li>TypeScript</li>
      </ul>
      <button type="submit">Subscribe</button>
    </form>
  );
}

afterEach(cleanup);

describe('Newsletter', () => {
  it('finds elements the way a user would', () => {
    render(<Newsletter onSubscribe={vi.fn()} />);
    expect(screen.getByRole('heading', { name: 'Newsletter' })).toBeInTheDocument();
    expect(screen.getByLabelText('Email address')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Subscribe' })).toBeEnabled();
    expect(within(screen.getByRole('list', { name: 'Topics' })).getAllByRole('listitem')).toHaveLength(2);
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
  });

  it('shows an error for an invalid email and does not call the callback', async () => {
    const user = userEvent.setup();
    const onSubscribe = vi.fn();
    render(<Newsletter onSubscribe={onSubscribe} />);
    await user.type(screen.getByLabelText('Email address'), 'asha');
    await user.click(screen.getByRole('button', { name: 'Subscribe' }));
    expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email');
    expect(onSubscribe).not.toHaveBeenCalled();
  });

  it('reports a valid email through the callback prop', async () => {
    const user = userEvent.setup();
    const onSubscribe = vi.fn();
    render(<Newsletter onSubscribe={onSubscribe} />);
    await user.type(screen.getByLabelText('Email address'), 'asha@example.com');
    await user.click(screen.getByRole('button', { name: 'Subscribe' }));
    expect(onSubscribe).toHaveBeenCalledWith('asha@example.com');
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
  });
});

Only the callback prop is mocked, and the real component runs. The file ran under Vitest with jsdom, and these tests passed on two consecutive runs: Newsletter > finds elements the way a user would Newsletter > shows an error for an invalid email and does not call the callback Newsletter > reports a valid email through the callback prop

Key points

  • Test behaviour from the user's point of view, not implementation details.
  • Query order: role, label, placeholder, text, display value, alt text, title, and test id last.
  • Use getBy for present, queryBy for absent and findBy for async elements. Prefer user-event.
  • Mock the network, time, missing browser APIs and callback props.
  • Do not mock your own components or hooks, and do not assert on state or render counts.

Common mistakes

  • Using getByTestId when a role or label query exists.
  • Mocking child components or custom hooks in a test of a parent.
  • Asserting on state, props or the number of renders.
  • Using getBy to check that something is absent.
  • Using fireEvent for typing instead of user-event.

Follow-ups

  • Why does getByRole make a test double as an accessibility check?
  • How would you test a component that depends on a context provider?
  • When is a snapshot test appropriate?

Tips

  • Quote the guiding principle in your own words.
  • Know the query order and the three query variants.
  • Say you mock the boundary, not your own code.