Testing React Components with Vitest and React Testing Library

By Muhammad Osama Khan, Software Engineer. Testing, Sep 15, 2026, 3 min read.

A working Vitest setup, tests that query the page like a user does, a mocked API call and the habits that keep tests from breaking on every refactor.

Vitest runs on the same config as Vite, so there is almost nothing to set up in a Vite project, and React Testing Library (RTL) pushes you towards tests that check what a user sees instead of how a component is built. Together they make a fast, readable test suite.

Install and configure

terminal

npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event

vite.config.js

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

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',          // a browser-like DOM for the components
    globals: true,                 // describe / it / expect without imports, and RTL cleans up after each test
    setupFiles: './src/test/setup.js',
    css: false
  }
});

src/test/setup.js

import '@testing-library/jest-dom/vitest'; // adds matchers like toBeInTheDocument()

package.json

{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest"
  }
}

A component to test

src/components/TaskForm.jsx

import { useState } from 'react';

export default function TaskForm({ onAdd }) {
  const [title, setTitle] = useState('');

  const submit = (event) => {
    event.preventDefault();
    const value = title.trim();
    if (!value) return;
    onAdd(value);
    setTitle('');
  };

  return (
    <form onSubmit={submit}>
      <label>
        Task title
        <input value={title} onChange={(e) => setTitle(e.target.value)} />
      </label>
      <button type="submit">Add task</button>
    </form>
  );
}

Test it the way a user uses it

src/components/TaskForm.test.jsx

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

describe('TaskForm', () => {
  it('submits the trimmed title and clears the field', async () => {
    const user = userEvent.setup();
    const onAdd = vi.fn();
    render(<TaskForm onAdd={onAdd} />);

    await user.type(screen.getByRole('textbox', { name: /task title/i }), '  Write tests  ');
    await user.click(screen.getByRole('button', { name: /add task/i }));

    expect(onAdd).toHaveBeenCalledWith('Write tests');
    expect(screen.getByRole('textbox', { name: /task title/i })).toHaveValue('');
  });

  it('does not submit an empty title', async () => {
    const user = userEvent.setup();
    const onAdd = vi.fn();
    render(<TaskForm onAdd={onAdd} />);

    await user.click(screen.getByRole('button', { name: /add task/i }));

    expect(onAdd).not.toHaveBeenCalled();
  });
});

Pick queries in this order

  1. getByRole with a name: the closest thing to how assistive technology sees the page, so it also nudges you towards accessible markup.
  2. getByLabelText for form fields, then getByText for plain content.
  3. getByTestId only as a last resort, when nothing visible identifies the element.

Use queryBy... when you expect something not to be there, and findBy... (which waits) for content that appears after an async step.

Mock the network

Unit tests should not call a real API. Replace fetch for the test and let findBy wait for the result.

src/components/TaskList.test.jsx

import { render, screen } from '@testing-library/react';
import { it, expect, vi, afterEach } from 'vitest';
import TaskList from './TaskList';

afterEach(() => vi.restoreAllMocks());

it('shows tasks loaded from the API', async () => {
  vi.spyOn(globalThis, 'fetch').mockResolvedValue({
    ok: true,
    json: async () => [{ id: 1, title: 'Ship it' }]
  });

  render(<TaskList />);

  expect(await screen.findByText('Ship it')).toBeInTheDocument();
});

Habits that keep tests useful

  • Test behaviour (what the user sees and can do), not implementation details such as state variable names. Then a refactor does not break the tests.
  • One reason to fail per test, with a name that reads like a sentence.
  • Use snapshots sparingly: large snapshots get approved without being read.
  • Run npm test in CI before the build, so a failing test stops a bad deploy.

Frequently asked questions

Why use Vitest instead of Jest in a Vite project?

Vitest reuses your Vite configuration, so ESM, JSX and aliases work without extra transform setup, and it starts quickly. Its API is close to Jest, so most tests look the same.

Which React Testing Library query should I use first?

getByRole with a name. It matches how assistive technology sees the page and nudges you towards accessible markup. Then getByLabelText for form fields, getByText for content, and getByTestId only as a last resort.

How do I test async behaviour in React Testing Library?

Use the findBy... queries, which wait for an element to appear, or waitFor for other conditions. Use queryBy... when you expect something not to be in the document.

Should I use snapshot tests for React components?

Sparingly. Large snapshots tend to be approved without being read and break on harmless changes. Prefer assertions about what the user sees and can do.

Keep reading

All articles · Work with me

MO
Muhammad Osama Khan