Skip to main content

Web frameworks · Intermediate · 22 min

Test React components with Vitest, Testing Library and MSW

By Padding · Updated 18 Nov 2026
Node.js 26 (node:26 image) · React 19.3 · Vitest 5.1.1 · MSW 3.0.7

You will have a Vitest suite for a React search component that types into it like a user, answers its API calls with MSW handlers, covers the loading, empty and error states, and still passes after you rewrite the component's internals.

On this page

A component test is worth keeping when it fails because the user's experience broke, and only then. Tests that reach into state variables or replace fetch with a hand-written fake break every time you tidy the code, so people stop trusting them. This tutorial builds the other kind.

You build a small React search box for a community library. It calls /api/books?q=... and shows results, a "no match" message, a progress message or an error. You test it with Vitest 5 in a jsdom DOM, Testing Library to find elements the way a person does, user-event to type and press keys, and Mock Service Worker (MSW) 3 to answer the HTTP requests. The component's code never knows it is being tested. At the end you rewrite the component from useState to useReducer, and the tests pass without a single change.

It assumes you know Vitest and Testing Library queries from testing UI code with Vitest and Testing Library, so this page covers what React and a network add, not the basics again.

Step 1 · Create the project and install the test tools

Create a React and TypeScript project with Vite's template, then add the test packages at exact versions:

Bash
cd ~
npm create vite@9 book-search-demo -- --template react-ts --no-interactive
cd book-search-demo
npm install
npm install --save-dev --save-exact vitest@5.1.1 jsdom@31.0.1 @testing-library/react@16.3.3 @testing-library/dom@10.4.2 @testing-library/user-event@14.6.13 @testing-library/jest-dom@8.0.0 msw@3.0.7

What each one does:

  • vitest runs the tests. It reads your Vite config, so the React plugin and TypeScript work in tests the same way they do in the app.
  • jsdom gives Node.js a document and window, so React can render without a browser.
  • @testing-library/react renders components into that document. It needs @testing-library/dom, which holds the queries, installed next to it.
  • @testing-library/user-event sends the full chain of keyboard and pointer events a real person would cause.
  • @testing-library/jest-dom adds matchers such as toBeDisabled() and toHaveTextContent(). Version 8 is the line made for Vitest 5.
  • msw intercepts outgoing requests at the network layer and answers them from handlers you write.

Check it worked

Bash
npm ls vitest msw @testing-library/react @testing-library/user-event

The tree shows vitest@5.1.1, msw@3.0.7, @testing-library/react@16.3.3 and @testing-library/user-event@14.6.13. Because of --save-exact, package.json lists the same numbers with no ^, so everyone on the project installs the same versions.

Step 2 · Describe the API with MSW handlers

Before writing the component, decide what the API returns. An MSW handler is a function that receives a standard Request and returns a Response. Put the handlers and a fixed list of books in src/test/handlers.ts:

Bash
mkdir -p src/test
cat > src/test/handlers.ts <<'TS'
import { http, HttpResponse } from 'msw'

export const API_BASE = 'https://api.library.test'

export const books = [
  { id: 1, title: 'Things Fall Apart', author: 'Chinua Achebe' },
  { id: 2, title: 'Half of a Yellow Sun', author: 'Chimamanda Ngozi Adichie' },
  { id: 3, title: 'Petals of Blood', author: 'Ngũgĩ wa Thiong’o' },
  { id: 4, title: 'So Long a Letter', author: 'Mariama Bâ' },
  { id: 5, title: 'Purple Hibiscus', author: 'Chimamanda Ngozi Adichie' },
]

export const handlers = [
  http.get(`${API_BASE}/api/books`, ({ request }) => {
    const q = (new URL(request.url).searchParams.get('q') ?? '').toLowerCase()
    const matches = books.filter((book) =>
      `${book.title} ${book.author}`.toLowerCase().includes(q),
    )
    return HttpResponse.json(matches)
  }),
]
TS
cat > src/test/server.ts <<'TS'
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
TS

The handler reads the q parameter and filters the list, so a search for "adichie" returns two books and a search for nonsense returns an empty array. That is closer to the real API than a fixed response, and it means the tests check that the component sends the search term at all.

setupServer from msw/node is the Node.js side of MSW. In a browser, MSW uses a service worker instead; the same handlers array works in both, which is the subject of mocking an API in front-end development with MSW.

The .test domain is reserved, so api.library.test is never assigned to a public host. If a handler is missing, the request cannot quietly reach the internet.

Check it worked

Bash
ls src/test

You see handlers.ts and server.ts.

Step 3 · Configure Vitest for React

Replace vite.config.ts so it also holds the test settings. Importing defineConfig from vitest/config instead of vite adds the types for the test block:

Bash
cat > vite.config.ts <<'TS'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    setupFiles: ['./src/test/setup.ts'],
  },
})
TS
cat > src/test/setup.ts <<'TS'
import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterAll, afterEach, beforeAll } from 'vitest'
import { server } from './server'

beforeAll(() => server.listen({ onUnhandledFrame: 'error' }))
afterEach(() => {
  cleanup()
  server.resetHandlers()
})
afterAll(() => server.close())
TS
npm pkg set scripts.test=vitest

The setup file runs before every test file:

  • The jest-dom import registers its matchers with Vitest's expect.
  • server.listen starts intercepting requests. onUnhandledFrame: 'error' makes any request without a handler fail loudly, so a typo in a URL shows up as a failing test, not a mystery. MSW 3 renamed this option; in MSW 2 it was onUnhandledRequest, and older guides still show that name.
  • cleanup() removes what each test rendered. Testing Library only does this by itself when your test runner exposes a global afterEach, and Vitest does not unless you turn on globals, so call it yourself.
  • server.resetHandlers() drops any handler a single test added, so one test's error response never leaks into the next.

Check it worked

Bash
npx vitest run --passWithNoTests

Vitest starts, prints RUN v5.1.1 and the project folder, then reports that it found no test files and exits with code 0. If it complains about the config, check that the import in vite.config.ts says vitest/config.

Step 4 · Build the search component

The component needs to know where the API lives. In the app that is your own site, and in tests it is the fake api.library.test address. A small context provider carries that base URL, which also gives you a real provider to wrap in the next step.

Bash
cat > src/api.tsx <<'TSX'
import { createContext, useContext, type ReactNode } from 'react'

const ApiContext = createContext('')

type ApiProviderProps = { baseUrl: string; children: ReactNode }

export function ApiProvider({ baseUrl, children }: ApiProviderProps) {
  return <ApiContext.Provider value={baseUrl}>{children}</ApiContext.Provider>
}

export function useApiBase() {
  return useContext(ApiContext) || window.location.origin
}
TSX
cat > src/BookSearch.tsx <<'TSX'
import { useState, type FormEvent } from 'react'
import { useApiBase } from './api'

type Book = { id: number; title: string; author: string }
type Status = 'idle' | 'loading' | 'done' | 'error'

export function BookSearch() {
  const apiBase = useApiBase()
  const [query, setQuery] = useState('')
  const [searched, setSearched] = useState('')
  const [status, setStatus] = useState<Status>('idle')
  const [books, setBooks] = useState<Book[]>([])

  async function search(event: FormEvent) {
    event.preventDefault()
    const term = query.trim()
    if (term === '') return
    setStatus('loading')
    setSearched(term)
    try {
      const url = new URL('/api/books', apiBase)
      url.searchParams.set('q', term)
      const response = await fetch(url)
      if (!response.ok) throw new Error(`HTTP ${response.status}`)
      setBooks(await response.json())
      setStatus('done')
    } catch {
      setStatus('error')
    }
  }

  let message = ''
  if (status === 'loading') message = 'Searching…'
  if (status === 'done' && books.length === 0) message = `No books match "${searched}".`

  return (
    <section>
      <h2>Find a book</h2>
      <form role="search" onSubmit={search}>
        <label htmlFor="book-query">Title or author</label>
        <input
          id="book-query"
          type="search"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
        <button type="submit" disabled={status === 'loading'}>
          Search
        </button>
      </form>
      <p role="status">{message}</p>
      {status === 'error' && (
        <p role="alert">Could not load books. Check your connection and try again.</p>
      )}
      {status === 'done' && books.length > 0 && (
        <ul aria-label="Results">
          {books.map((book) => (
            <li key={book.id}>
              {book.title} by {book.author}
            </li>
          ))}
        </ul>
      )}
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { ApiProvider } from './api'
import { BookSearch } from './BookSearch'

export default function App() {
  return (
    <ApiProvider baseUrl={import.meta.env.VITE_API_URL ?? ''}>
      <main>
        <h1>Community library</h1>
        <BookSearch />
      </main>
    </ApiProvider>
  )
}
TSX

Three details matter for testing:

  • The input has a real <label>, so its accessible name is "Title or author". Tests find it by that name, the same name a screen reader speaks.
  • The status paragraph is always in the page with role="status", and only its text changes. Screen readers announce changes to a live region that already exists more reliably than one that appears, and tests can find it by role.
  • URLSearchParams (through url.searchParams.set) encodes the term, so a search for "Ngũgĩ" or "Bâ" reaches the server intact. If your readers search in Yoruba, Swahili or French, an encoding bug here is a bug they hit daily, and you test for it below.

In the app, VITE_API_URL is unset, so the component calls /api/books on its own site. Set VITE_API_URL in a .env file when the API lives elsewhere; it holds an address, never a secret, because Vite copies VITE_ values into the browser bundle.

Check it worked

Bash
npx tsc -b

The type check prints nothing when it passes. It also covers the files in src/test/, so a wrong MSW option name (such as the old onUnhandledRequest) shows up here as an error.

Step 5 · Wrap providers in a custom render

Every test of BookSearch needs the ApiProvider around it, and later components may need a router or a query client too. Put that in one helper, so each test renders a single line and the provider list lives in one place:

Bash
cat > src/test/render.tsx <<'TSX'
import type { ReactElement, ReactNode } from 'react'
import { render, type RenderOptions } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ApiProvider } from '../api'
import { API_BASE } from './handlers'

function Providers({ children }: { children: ReactNode }) {
  return <ApiProvider baseUrl={API_BASE}>{children}</ApiProvider>
}

export function renderWithProviders(
  ui: ReactElement,
  options?: Omit<RenderOptions, 'wrapper'>,
) {
  return {
    user: userEvent.setup(),
    ...render(ui, { wrapper: Providers, ...options }),
  }
}
TSX

wrapper tells Testing Library to render your component inside Providers. The helper also calls userEvent.setup() before rendering and returns the user object with everything render returns, so a test gets both from one call. When you add a provider to the app, add it to Providers too, and every test picks it up.

Check it worked

Bash
npx tsc -b

It passes silently. If TypeScript reports that RenderOptions must be imported with import type, keep the type keyword inside the braces as written; the Vite template turns on verbatimModuleSyntax, which requires it.

Step 6 · Write the first test

The first test does what a library visitor does: types a name, presses the button, and reads the results.

Bash
cat > src/BookSearch.test.tsx <<'TSX'
import { screen, within } from '@testing-library/react'
import { delay, http, HttpResponse } from 'msw'
import { describe, expect, test } from 'vitest'
import { BookSearch } from './BookSearch'
import { API_BASE } from './test/handlers'
import { renderWithProviders } from './test/render'
import { server } from './test/server'

describe('BookSearch', () => {
  test('lists the books that match a search', async () => {
    const { user } = renderWithProviders(<BookSearch />)

    await user.type(screen.getByRole('searchbox', { name: 'Title or author' }), 'adichie')
    await user.click(screen.getByRole('button', { name: 'Search' }))

    const results = await screen.findByRole('list', { name: 'Results' })
    const items = within(results).getAllByRole('listitem')
    expect(items).toHaveLength(2)
    expect(items[0]).toHaveTextContent('Half of a Yellow Sun by Chimamanda Ngozi Adichie')
  })
})
TSX
npx vitest run

Read it line by line:

  • getByRole('searchbox', { name: 'Title or author' }) finds an <input type="search"> by its label. If someone deletes the label, this fails, and it should, because people using a screen reader would lose it too.
  • await user.type(...) and await user.click(...) are asynchronous in user-event 14. Always await them.
  • findByRole waits and retries, by default for up to one second, until the list appears. The response comes back asynchronously, so a getBy query here would run too early and fail. Use findBy for anything that appears after a network call, getBy for what is there now, and queryBy only to check that something is absent.
  • within(results) limits the next query to the results list.

The imports for delay, http, HttpResponse, API_BASE and server are for the next step. Vitest does not type-check, so they cause no error yet.

During development, run the suite in watch mode instead. It reruns the affected tests every time you save, and you press q to quit:

Bash
npm test

Check it worked

The output lists src/BookSearch.test.tsx with a tick and ends with Tests 1 passed (1). Change 'adichie' to 'achebe' and run npx vitest run again: the test fails, showing that one list item was found where two were expected, and printing the rendered HTML. Change it back before you continue.

Step 7 · Test the loading, empty and error states

The default handler covers the happy path. For the other states, override it inside a single test with server.use. The override only lasts until resetHandlers runs after that test. Append four tests to the file:

Bash
cat >> src/BookSearch.test.tsx <<'TSX'

describe('BookSearch while waiting', () => {
  test('shows progress and blocks a second search until the answer arrives', async () => {
    server.use(
      http.get(`${API_BASE}/api/books`, async () => {
        await delay(200)
        return HttpResponse.json([{ id: 9, title: 'So Long a Letter', author: 'Mariama Bâ' }])
      }),
    )
    const { user } = renderWithProviders(<BookSearch />)

    await user.type(screen.getByRole('searchbox', { name: 'Title or author' }), 'bâ{Enter}')

    expect(screen.getByRole('status')).toHaveTextContent('Searching')
    expect(screen.getByRole('button', { name: 'Search' })).toBeDisabled()
    expect(await screen.findByText('So Long a Letter by Mariama Bâ')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Search' })).toBeEnabled()
  })
})

describe('BookSearch when there is nothing to show', () => {
  test('says so when no book matches', async () => {
    const { user } = renderWithProviders(<BookSearch />)

    await user.type(screen.getByRole('searchbox', { name: 'Title or author' }), 'ngũgĩ{Enter}')
    expect(await screen.findByText('Petals of Blood by Ngũgĩ wa Thiong’o')).toBeInTheDocument()

    await user.clear(screen.getByRole('searchbox', { name: 'Title or author' }))
    await user.type(screen.getByRole('searchbox', { name: 'Title or author' }), 'zzz{Enter}')
    expect(await screen.findByText('No books match "zzz".')).toBeInTheDocument()
    expect(screen.queryByRole('list', { name: 'Results' })).not.toBeInTheDocument()
  })

  test('shows an error when the server fails', async () => {
    server.use(
      http.get(`${API_BASE}/api/books`, () => new HttpResponse(null, { status: 500 })),
    )
    const { user } = renderWithProviders(<BookSearch />)

    await user.type(screen.getByRole('searchbox', { name: 'Title or author' }), 'achebe{Enter}')

    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load books')
  })

  test('shows an error when the connection drops', async () => {
    server.use(http.get(`${API_BASE}/api/books`, () => HttpResponse.error()))
    const { user } = renderWithProviders(<BookSearch />)

    await user.type(screen.getByRole('searchbox', { name: 'Title or author' }), 'achebe{Enter}')

    expect(await screen.findByRole('alert')).toHaveTextContent('Check your connection')
  })
})
TSX
npx vitest run --reporter=verbose

What each override shows:

  • delay(200) holds the response long enough to see the in-between state. Right after Enter, the status reads "Searching…" and the button is disabled, so an impatient double tap cannot send two requests. Typing {Enter} inside user.type submits the form from the keyboard, which also checks that keyboard users can search.
  • The empty-state test uses the default handler. Searching for "ngũgĩ" proves that non-ASCII text survives the trip through the URL, and "zzz" proves the empty message replaces the old list.
  • new HttpResponse(null, { status: 500 }) is a server error. fetch resolves, response.ok is false, and the component shows the alert.
  • HttpResponse.error() is a network failure: fetch itself rejects, as it does when a phone drops off mobile data halfway through a request. On slow or prepaid connections this path runs often, so it deserves its own test.

None of these tests mock fetch. If you later swap fetch for another HTTP client, the handlers still answer it, because MSW works below the client. A test built on vi.spyOn(globalThis, 'fetch') would need rewriting, and could pass even when the URL is wrong. The suite also never touches the real network, so it runs offline and costs no data.

Check it worked

The verbose reporter prints five ticked tests grouped under BookSearch, BookSearch while waiting and BookSearch when there is nothing to show, and the summary reads Tests 5 passed (5). To confirm the error tests have teeth, change the alert text in src/BookSearch.tsx to "Something went wrong", rerun, and watch both error tests fail. Undo the change before the last step.

Step 8 · Refactor the component and rerun the tests

The real test of these tests is a refactor. Rewrite BookSearch so the four useState calls become one useReducer with a state type that cannot hold impossible combinations, and move the request into its own function. The rendered output stays the same:

Bash
cat > src/BookSearch.tsx <<'TSX'
import { useReducer, useState, type FormEvent } from 'react'
import { useApiBase } from './api'

type Book = { id: number; title: string; author: string }

type State =
  | { kind: 'idle' }
  | { kind: 'loading'; term: string }
  | { kind: 'done'; term: string; books: Book[] }
  | { kind: 'error'; term: string }

type Action =
  | { type: 'start'; term: string }
  | { type: 'success'; books: Book[] }
  | { type: 'failure' }

function reducer(state: State, action: Action): State {
  const term = state.kind === 'idle' ? '' : state.term
  switch (action.type) {
    case 'start':
      return { kind: 'loading', term: action.term }
    case 'success':
      return { kind: 'done', term, books: action.books }
    case 'failure':
      return { kind: 'error', term }
  }
}

async function fetchBooks(apiBase: string, term: string): Promise<Book[]> {
  const url = new URL('/api/books', apiBase)
  url.searchParams.set('q', term)
  const response = await fetch(url)
  if (!response.ok) throw new Error(`HTTP ${response.status}`)
  return response.json()
}

export function BookSearch() {
  const apiBase = useApiBase()
  const [query, setQuery] = useState('')
  const [state, dispatch] = useReducer(reducer, { kind: 'idle' })

  async function search(event: FormEvent) {
    event.preventDefault()
    const term = query.trim()
    if (term === '') return
    dispatch({ type: 'start', term })
    try {
      dispatch({ type: 'success', books: await fetchBooks(apiBase, term) })
    } catch {
      dispatch({ type: 'failure' })
    }
  }

  const books = state.kind === 'done' ? state.books : []
  let message = ''
  if (state.kind === 'loading') message = 'Searching…'
  if (state.kind === 'done' && books.length === 0) message = `No books match "${state.term}".`

  return (
    <section>
      <h2>Find a book</h2>
      <form role="search" onSubmit={search}>
        <label htmlFor="book-query">Title or author</label>
        <input
          id="book-query"
          type="search"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
        <button type="submit" disabled={state.kind === 'loading'}>
          Search
        </button>
      </form>
      <p role="status">{message}</p>
      {state.kind === 'error' && (
        <p role="alert">Could not load books. Check your connection and try again.</p>
      )}
      {books.length > 0 && (
        <ul aria-label="Results">
          {books.map((book) => (
            <li key={book.id}>
              {book.title} by {book.author}
            </li>
          ))}
        </ul>
      )}
    </section>
  )
}
TSX
npx vitest run
npx tsc -b

The state names, the number of hooks and where the request lives have all changed. Nothing a user sees has, and the tests only look at what a user sees: roles, names and text. That is why they pass. Had the tests asserted on setStatus calls or on a mocked fetch being called with certain arguments, this refactor would have broken them for no reason.

Check it worked

Vitest reports Tests 5 passed (5) with no edits to src/BookSearch.test.tsx, and npx tsc -b prints nothing. When you have finished, remove the demo project:

Bash
cd ~
rm -rf ~/book-search-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.