Skip to content

Lesson 10 — Vitest and React Testing Library

Objective

Test domain transitions and user-visible workflows at useful boundaries.

Prerequisites

Lesson 9 — Effects, cancellation, and event reasoning. You should be able to handle async side effects and cleanup.

Mental Model

Tests should increase confidence in observable behavior. Roles and names approximate user interaction and resist harmless refactors better than class selectors or component internals.

Concept

Use pure unit tests for reducers and integration-style component tests for workflows. Query the DOM the way a user would: by role, label, and text. Mock at the network or repository boundary, not React internals. Tests that assert behavior, not implementation, survive refactors.

Example

it('filters topics by search term', async () => {
  render(<TopicList topics={topics} />);
  const search = screen.getByRole('searchbox');
  await userEvent.type(search, 'react');
  expect(screen.getByRole('listitem')).toHaveTextContent('React basics');
});

Real-World Usage

CI checks, pre-commit quality gates, and refactoring safety for forms, tables, and async flows.

Common Mistakes

  • Testing implementation details such as useState calls or CSS classes.
  • Mocking all of React instead of the repository/network boundary.
  • Using getBy for async content and timing tests with arbitrary waitFor calls.

Mini Lab

Task

Test reducer immutability, topic filtering/status, form validation/submission, and route navigation. Use userEvent, provider wrappers, and async queries where behavior is asynchronous.

Constraints

  • Run npm test.
  • Intentionally break each behavior and ensure the relevant test fails for a useful reason.

Expected Result

Each behavior has a test that fails with a diagnostic message when the implementation is intentionally broken. Tests run in CI and pass on the reference implementation.

Hints

Use pure unit tests for reducers and integration-style component tests for workflows. Mock at the network/repository boundary, not React internals.

Knowledge Check

  • What should not be mocked?
  • getBy, findBy, or queryBy?
  • How do you test accessibility without claiming full compliance?

Challenge

A test suite is fast but breaks on every component rename. What would you change in the query strategy and in the test review process?

Summary

Test observable behavior with user-centric queries. Mock at the boundary, unit test pure logic, and avoid coupling tests to implementation.

What Comes Next

Lesson 11 — Rendering performance and profiling