Skip to the content

Lesson 184 of 296

React Testing Library

What you will learn

  • Why we test, and what kinds of tests exist
  • Vitest: the test runner
  • React Testing Library and its main idea
  • Queries and their priority
  • Simulating users with user-event
  • Waiting for asynchronous UI
  • A full component test
On this page

Why test?

A test is code that checks your code does what it should. Tests let you change code with confidence: if you break something, a test fails before your users notice. In interviews, writing a test for your own solution shows maturity, and many take-home tasks are judged partly on tests.

Kind of testChecksSpeedTools
UnitOne function or small component on its ownVery fastVitest, Jest
IntegrationSeveral parts working together (a form with validation and a mocked API)FastVitest + React Testing Library + MSW
End-to-end (E2E)The whole app in a real browser, like a userSlowPlaywright, Cypress

The testing pyramid (Lesson 271): many unit tests, a good number of integration tests, a few E2E tests for the most important journeys. Many front-end teams follow the "testing trophy" idea instead, where integration tests get the most attention, because they give the most confidence per test.

Vitest

Vitest is a fast test runner built on Vite. It has the same API as Jest (the older, very common runner), so knowing one means knowing both.

TSX
import { describe, it, expect } from "vitest";

function formatPrice(pence: number): string {
  return `£${(pence / 100).toFixed(2)}`;
}

describe("formatPrice", () => {
  it("formats pence as pounds", () => {
    expect(formatPrice(1999)).toBe("£19.99");
  });

  it("handles zero", () => {
    expect(formatPrice(0)).toBe("£0.00");
  });
});
  • describe groups related tests; it (or test) is one test case.
  • expect(value).toBe(expected) is an assertion. Others: toEqual (deep equality for objects and arrays), toThrow, toHaveBeenCalledWith, toContain.
  • Each test follows Arrange, Act, Assert: set up, do the thing, check the result.

To test React components, configure Vitest with a DOM environment (jsdom, a simulated browser in Node.js):

TypeScript
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    setupFiles: ["./vitest.setup.ts"]
  }
});

The setup file adds extra matchers: import "@testing-library/jest-dom/vitest";. Vitest also has a browser mode that runs component tests in a real browser through Playwright, which became stable in Vitest 4.

React Testing Library: the main idea

React Testing Library (RTL) renders components and lets you interact with them the way a user does: find things by what users see (text, labels, roles), click and type, then check what appears on screen.

Its guiding principle: the more your tests resemble the way your software is used, the more confidence they give you. So you do not test implementation details: state variable names, which hooks a component uses, or internal methods. If you refactor a component without changing its behaviour, good tests should still pass.

Queries: how to find elements

screen represents the whole rendered page. Query priority (use the first one that works):

PriorityQueryFinds by
1getByRole("button", { name: "Save" })Accessible role and name, as screen readers see it
2getByLabelText("Email")The label of a form field
3getByPlaceholderText(...)Placeholder (weaker: placeholders are not labels)
4getByText("Welcome back")Visible text
5getByDisplayValue(...)Current value of an input
6getByAltText, getByTitleImage alt, title attribute
Last resortgetByTestId("chart")A data-testid attribute

Using getByRole first has a bonus: if your test cannot find a button by its role and name, a screen reader user probably cannot either. Tests encourage accessibility (Lesson 13).

Each query comes in three forms:

FormIf not foundIf many foundUse for
getBy...Throws an errorThrowsSomething that should be there now
queryBy...Returns nullThrowsChecking something is not there
findBy...Rejects after waiting (default 1 second)RejectsSomething that will appear (after a fetch or timer); returns a Promise, so await it

Each also has an ...AllBy... version that returns an array.

user-event: acting like a user

@testing-library/user-event simulates real interactions: a click includes pointer and focus events; typing fires a key event for every character.

TSX
import userEvent from "@testing-library/user-event";

async function example() {
  const user = userEvent.setup();
  await user.click(screen.getByRole("button", { name: "Add" }));
  await user.type(screen.getByLabelText("Name"), "Sam");
  await user.keyboard("{Enter}");
  await user.selectOptions(screen.getByLabelText("Plan"), "pro");
  await user.tab();
}

Prefer user-event over the lower-level fireEvent, which only fires a single event.

jest-dom matchers

Readable assertions about the DOM:

MatcherChecks
toBeInTheDocument()The element exists on the page
toHaveTextContent("3 items")Its text
toBeVisible()Not hidden
toBeDisabled() / toBeEnabled()Disabled state
toHaveValue("Sam")An input's value
toBeChecked()A checkbox state
toHaveAttribute("aria-expanded", "true")An attribute
toHaveFocus()It has keyboard focus

A full example

The component: a counter with a limit.

TSX
import { useState } from "react";

export function QuantityPicker({ max = 5, onChange }: { max?: number; onChange?: (qty: number) => void }) {
  const [qty, setQty] = useState(1);
  function update(next: number) {
    setQty(next);
    onChange?.(next);
  }
  return (
    <div>
      <button type="button" aria-label="Decrease quantity" disabled={qty <= 1} onClick={() => update(qty - 1)}>
        -
      </button>
      <output aria-live="polite" aria-label="Quantity">{qty}</output>
      <button type="button" aria-label="Increase quantity" disabled={qty >= max} onClick={() => update(qty + 1)}>
        +
      </button>
      {qty >= max && <p role="status">Maximum {max} per order</p>}
    </div>
  );
}

The test:

TSX
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe("QuantityPicker", () => {
  it("starts at 1 with decrease disabled", () => {
    render(<QuantityPicker />);
    expect(screen.getByLabelText("Quantity")).toHaveTextContent("1");
    expect(screen.getByRole("button", { name: "Decrease quantity" })).toBeDisabled();
  });

  it("increases up to the maximum and shows a message", async () => {
    const user = userEvent.setup();
    const onChange = vi.fn();
    render(<QuantityPicker max={3} onChange={onChange} />);

    const increase = screen.getByRole("button", { name: "Increase quantity" });
    await user.click(increase);
    await user.click(increase);

    expect(screen.getByLabelText("Quantity")).toHaveTextContent("3");
    expect(increase).toBeDisabled();
    expect(screen.getByText("Maximum 3 per order")).toBeInTheDocument();
    expect(onChange).toHaveBeenLastCalledWith(3);
    expect(onChange).toHaveBeenCalledTimes(2);
  });

  it("does not show the limit message before the maximum", () => {
    render(<QuantityPicker max={3} />);
    expect(screen.queryByText(/Maximum/)).not.toBeInTheDocument();
  });
});

Points to notice:

  • vi.fn() creates a mock function (a fake that records how it was called), used to check the onChange callback.
  • The test never looks at qty or useState; it checks what the user sees.
  • queryBy... with .not.toBeInTheDocument() checks absence.
  • A trap found while testing this example: <output> has the implicit role status, so getByRole("status") would match two elements (the output and the message) and throw "Found multiple elements". That is why the test finds the message by its text. Knowing the implicit roles of HTML elements (Lesson 13) helps you write correct queries.
  • RTL automatically cleans up the rendered component after each test (when the test runner exposes afterEach globally, or when you call cleanup yourself).

What to test in a component

  • It renders the right content for given props.
  • User interactions produce the right results (and callbacks are called with the right values).
  • Loading, error, empty and success states (Lesson 161).
  • Accessibility basics: labels exist, focus moves correctly, errors are announced.
  • Not: styling details, internal state, the exact number of renders, or third-party library internals.

How to say it in an interview

"I use Vitest with React Testing Library and jsdom. RTL's principle is to test behaviour the way a user experiences it, not implementation details, so I query by role and label first, which also checks accessibility, use getBy for things that should exist, queryBy to assert absence and await findBy for things that appear later. I simulate interactions with user-event and assert with jest-dom matchers like toBeDisabled and toHaveTextContent, and I use vi.fn to check callbacks. I cover loading, error, empty and success states rather than internal state."

Key words

WordMeaning
Test runnerThe tool that finds and runs tests (Vitest, Jest)
AssertionA check that a value is what you expect
jsdomA simulated browser DOM running in Node.js
React Testing LibraryA library for testing components through what users see and do
QueryA way to find elements (getBy, queryBy, findBy)
user-eventA library that simulates realistic user interactions
Mock functionA fake function that records its calls (vi.fn())
Implementation detailInternal code that users cannot see

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.