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
Install Testing Dependencies
Install Vitest, React Testing Library, and related packages:These packages provide:
vitest: Fast unit test framework@testing-library/react: React component testing utilities@testing-library/dom: DOM testing utilities
Configure Test Scripts
Add test scripts to your Available commands:
package.json:package.json
npm test: Run tests in watch modenpm run test:ui: Launch the interactive Vitest UInpm run coverage: Generate code coverage reports
Configure Vitest (Optional)
Create a
vitest.config.ts file for custom configuration:vitest.config.ts
Dependencies Overview
Yourpackage.json should include these testing dependencies:
package.json
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 yourpackage.json:
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