Skip to main content

Overview

This guide walks you through setting up a complete testing environment using Vitest and React Testing Library. Vitest is a blazing-fast unit test framework powered by Vite, providing an excellent developer experience with features like hot module replacement for tests.

Installation

1

Install Testing Dependencies

Install Vitest, React Testing Library, and related packages:
npm install -D vitest @testing-library/react @testing-library/dom
These packages provide:
  • vitest: Fast unit test framework
  • @testing-library/react: React component testing utilities
  • @testing-library/dom: DOM testing utilities
2

Configure Test Scripts

Add test scripts to your package.json:
package.json
{
  "scripts": {
    "test": "vitest",
    "test:ui": "vitest --ui",
    "coverage": "vitest run --coverage"
  }
}
Available commands:
  • npm test: Run tests in watch mode
  • npm run test:ui: Launch the interactive Vitest UI
  • npm run coverage: Generate code coverage reports
3

Configure Vitest (Optional)

Create a vitest.config.ts file for custom configuration:
vitest.config.ts
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react-swc'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    globals: true,
    setupFiles: './src/test/setup.ts',
  },
})
4

Create Test Files

Create test files alongside your source code with the .test.ts or .test.tsx extension:
src/
├── MyAwesomeApp.tsx
├── MyAwesomeApp.test.tsx
└── helpers/
    ├── math.helper.ts
    └── math.helper.test.ts

Dependencies Overview

Your package.json should include these testing dependencies:
package.json
{
  "devDependencies": {
    "@testing-library/dom": "^10.4.1",
    "@testing-library/react": "^16.3.2",
    "vitest": "^4.0.16"
  }
}
Vitest works seamlessly with Vite projects and reuses your existing Vite configuration, making setup minimal.

Running Tests

Once configured, you can run tests using the scripts defined in your package.json:
npm test

Test Modes Explained

  • Watch Mode: Automatically reruns tests when files change, perfect for development
  • UI Mode: Opens a browser-based interface to explore and debug tests interactively
  • Coverage: Generates a detailed code coverage report showing which lines are tested
Use npm run test:ui during development for the best debugging experience. The UI shows test results, console output, and allows you to filter and focus on specific tests.

Next Steps

Now that your testing environment is configured, you can:
  • Write component tests using React Testing Library
  • Create unit tests for helper functions
  • Use snapshot testing to catch unexpected UI changes

Build docs developers (and LLMs) love