Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

Component Tests That Read Like User Stories

Set up Vitest with jsdom and Testing Library, query a component the way users perceive it, simulate typing with user-event, and cover loading, empty and error states.

Contentsand lesson path

What you will learn

  • Write component tests with Vitest and Testing Library that query by role and label, simulate user events and assert visible behavior rather than implementation details.

Prerequisites: React Components & State

01. The problem

A shop page has a search box. When shoppers type, results appear after a short pause; sometimes the catalogue has nothing that matches, and sometimes the products API is down. These visible states — loading, results, empty, error — are exactly what a component test should prove, because they are what a user experiences.

Here is the component under test: a search box that waits for typing to settle, then reads from the network.

TypeScript · src/product-search.tsx
import { useEffect, useState } from 'react';
import { searchProducts, type Product } from './api';

type State =
  | { status: 'loading' }
  | { status: 'error' }
  | { status: 'success'; products: Product[] };

export function ProductSearch() {
  const [query, setQuery] = useState('');
  const [state, setState] = useState<State>({ status: 'loading' });

  useEffect(() => {
    let active = true;
    const timer = setTimeout(() => {
      setState({ status: 'loading' });
      searchProducts(query)
        .then((products) => {
          if (active) setState({ status: 'success', products });
        })
        .catch(() => {
          if (active) setState({ status: 'error' });
        });
    }, 150);
    return () => {
      active = false;
      clearTimeout(timer);
    };
  }, [query]);

  return (
    <section aria-labelledby="search-heading">
      <h2 id="search-heading">Product search</h2>
      <label htmlFor="search-input">Search products</label>
      <input id="search-input" type="search" value={query}
        onChange={(event) => setQuery(event.target.value)} />
      {state.status === 'loading' && <p role="status">Loading…</p>}
      {state.status === 'error' &&
        <p role="alert">Something went wrong. Please try again.</p>}
      {state.status === 'success' && state.products.length === 0 &&
        <p>No products match &ldquo;{query}&rdquo;.</p>}
      {state.status === 'success' && state.products.length > 0 && (
        <ul>
          {state.products.map((product) => (
            <li key={product.id}>{product.name} — £{product.price.toFixed(2)}</li>
          ))}
        </ul>
      )}
    </section>
  );
}

Notice what the component does not expose: no CSS classes to signal state, no refs to poke, no internal flags worth reading. Everything worth knowing is visible: a role="status" note while loading, a role="alert" on failure, a list of results, or a plain sentence when nothing matches. The tests below use exactly those visible handles.

02. Step 1: run React in jsdom

Vitest runs the tests, jsdom provides a browser-like DOM, and Testing Library renders React and queries it the way a user would. Install them as dev dependencies. The install line pins the versions this lesson was checked with on 26 November 2026: Vitest 5.1.2, jsdom 31.0.1, @testing-library/react 16.3.3 with @testing-library/dom 10.4.2 (a required peer since version 16, so name it explicitly), @testing-library/user-event 14.6.13 and @testing-library/jest-dom 8.0.0 (which supports Vitest 5 only), plus MSW 3.0.8 (Mock Service Worker) for the mock network the tests talk to. React 19.3.1 is already in the project.

Terminal
npm install -D [email protected] [email protected] @testing-library/[email protected] \
  @testing-library/[email protected] @testing-library/[email protected] \
  @testing-library/[email protected] [email protected]
TypeScript · vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'jsdom',
    setupFiles: './src/setup-tests.ts',
  },
});

Two settings matter. environment: 'jsdom' gives every test file a simulated DOM instead of Node's bare globals, and setupFiles points at a file that loads extra matchers and cleans up between tests. @testing-library/jest-dom/vitest adds matchers such as toBeVisible() and toHaveTextContent() to the expect you already use:

TypeScript · src/setup-tests.ts
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';

afterEach(cleanup);

Testing Library can clean up rendered components automatically after each test, but only when Vitest runs with globals enabled. This project imports its test APIs explicitly, so the setup file calls cleanup() itself. It looks optional — right up to the day a query in test two matches a leftover from test one.

The tests use screen, an object whose query methods search the whole rendered body. Every query also exists as a method on the object render() returns, scoped to that render; screen is the convenient form, and its queries fail with a clear message when the component is no longer mounted.

03. Step 2: query the way a user does

All three tests in this lesson run against a mock network. ProductSearch calls searchProducts (the src/api.ts client printed in the lab), which calls fetch, and a Mock Service Worker server answers from a small catalogue that includes "Trail shoes". The next lesson builds that server in src/mocks/ and adds it to src/setup-tests.ts; the passing output at the end of this lesson assumes those files are in place. With only the setup above, the requests have nowhere to go and the tests fail, so read this lesson for the queries and come back to run it after the next one.

The first test states a user story: while results load, shoppers see a note; once results arrive, the note is replaced by a list.

TypeScript · src/product-search.test.tsx (first test)
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
import { http, HttpResponse } from 'msw/http'; // for the third test
import { server } from './mocks/server'; // built in the next lesson
import { ProductSearch } from './product-search';

describe('ProductSearch', () => {
  it('shows a loading note, then the matching products', async () => {
    const user = userEvent.setup();
    render(<ProductSearch />);

    expect(screen.getByRole('status')).toHaveTextContent(/loading/i);

    await user.type(
      screen.getByRole('searchbox', { name: 'Search products' }),
      'shoes',
    );
    const list = await screen.findByRole('list');
    expect(list).toHaveTextContent('Trail shoes');
    expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
  });
});

getByRole('searchbox', { name: 'Search products' }) finds the input by its role and accessible name — the same semantics that assistive technology announces. Pairing the role query with the accessible name proves the label is connected: a <label htmlFor> association gives the input its accessible name, so a broken label breaks the test. That is deliberate. If users cannot tell what the box is for, the test should fail.

Testing Library queries are strict: if getByRole('status') matched two elements, the test would fail loudly rather than quietly pick one. Silence hides bugs; a thrown error surfaces them.

The loading note exists on the first render, so getByRole finds it immediately. The list does not: it appears only after the network round-trip. For elements that appear later, use a findBy query, which waits and then reports. The third family, queryBy…, returns null instead of throwing and is the right tool for asserting that something is gone.

Role queries do more than find elements — they keep the markup honest as a side effect. A <div> that behaves like a button has no button role, so a role query cannot find it, and the test fails until the markup uses a real <button> or an explicit role. Accessibility and testability reinforce each other here: what the tests can find is what assistive technology can announce. The accessibility skill covers the markup side of that bargain in depth; this lesson covers the test side.

04. Step 3: type like a user, await like a professional

Test two covers the empty state. userEvent.setup() creates an instance that imitates real typing, sending key, input and change events for every character — closer to reality than firing a single change event by hand. The await is not decoration: user-event methods return promises, and the assertions must not run while typing is still in progress.

TypeScript · src/product-search.test.tsx (second test)
  it('says so when nothing matches the query', async () => {
    const user = userEvent.setup();
    render(<ProductSearch />);

    await user.type(
      screen.getByRole('searchbox', { name: 'Search products' }),
      'kettlebells',
    );
    expect(
      await screen.findByText('No products match “kettlebells”.'),
    ).toBeInTheDocument();
    expect(screen.queryByRole('list')).not.toBeInTheDocument();
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
  });

Because the component debounces for 150 ms, only the final query reaches the network — so the assertion can check the exact message for the full query rather than racing partial results. Timing details like this are worth a comment in the test file: the next reader will wonder why the test is allowed to be this precise.

Notice also what you did not have to do. No act() wrappers, no manual flushing of state updates: Testing Library renders inside React's own machinery, and user-event dispatches events through the same path a browser does, so state updates settle before the awaited call returns. The two tools are built to be used together, and the combination removes most of the timing ceremony people associate with testing React.

05. Step 4: cover the failure

The error state completes the set. The server.use(...) line tells the mock network to answer 500 for this one test; the next lesson explains that mechanism in full. What matters here is the assertion: the component shows role="alert" — the same signal assistive technology uses to announce the failure — and the list is gone.

TypeScript · src/product-search.test.tsx (third test)
  it('shows an error message when the request fails', async () => {
    server.use(
      http.get('*/api/products',
        () => new HttpResponse(null, { status: 500 })),
    );

    render(<ProductSearch />);

    expect(await screen.findByRole('alert')).toHaveTextContent(/went wrong/i);
    expect(screen.queryByRole('list')).not.toBeInTheDocument();
  });
Expected output · npx vitest run (path and timings omitted; they vary between runs, and Vitest also lists by name any test slower than 300 ms)
 RUN  v5.1.2

 ✓ src/product-search.test.tsx (3 tests)

 Test Files  1 passed (1)
      Tests  3 passed (3)

06. Four mistakes that account for most broken tests

07. Check your understanding

Practice check · 3 questions

Reading the suite like a user

Three situations from a component suite.

Q1. You type into a combobox and an options list appears a moment later. Which query reads that list?
Q2. A page shows six product cards, each with an 'Add to basket' button. getByRole('button', { name: 'Add to basket' }) throws. What is the right response?
Q3. What does jest-dom's toBeVisible() check that toBeInTheDocument() does not?
Practice only: not graded, not saved, not evidence.

08. Apply it

Pick one component from your app that talks to the network and write the four-state suite for it: loading, success, empty, error. Query only by role, label or visible text, and type with user-event where an input is involved. The search and checkout features named in the practice task for this skill are good candidates — the network side of the suite is the subject of the next lesson.

09. Review prompt

Without looking back: name the three query families and when each fits. Say what an accessible name is and where it comes from in markup. Then list the four mistakes from the warning callout, each with its fix.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check