1. Introduction & use cases
Vitest is a test runner built on Vite. It reuses your Vite config (aliases, plugins, TypeScript, JSX), so tests work without extra transpiler setup, and it is very fast thanks to Vite’s on-demand transforms and smart watch mode.
Its API (describe, it, expect, vi.fn) is compatible with Jest, which makes migrating easy. Vitest supports ESM and TypeScript natively and also has a browser mode, a web UI and built-in coverage.
Where it is used
- Unit tests in Vite, React, Vue and Svelte projects
- Component tests with Testing Library + jsdom
- Testing TypeScript libraries without build steps
- Fast feedback in watch mode during development
2. Prerequisites
| You need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| A project | Works best with Vite – see the ReactJS guide |
3. Local setup
1Install Vitest
Add scripts for watch mode and single runs.
BASHnpm install --save-dev vitest npm pkg set scripts.test="vitest" npm pkg set scripts.test:run="vitest run"2Add a DOM environment for component tests
jsdom simulates the browser; Testing Library renders components the way users see them.
BASHnpm install --save-dev jsdom @testing-library/react @testing-library/jest-dom3Configure
Put test options in
vite.config(or a separatevitest.config).vite.config.js/// <reference types="vitest/config" /> import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], test: { environment: 'jsdom', globals: true, setupFiles: './src/test/setup.js', }, }); // src/test/setup.js import '@testing-library/jest-dom/vitest';
4. Create & run a project
1Unit test
Same style as Jest.
JS// src/slug.js export const slug = (s) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''); // src/slug.test.js import { describe, it, expect } from 'vitest'; import { slug } from './slug'; describe('slug', () => { it('makes URL-safe slugs', () => { expect(slug('Hello World!')).toBe('hello-world'); }); });2Component test
Render, interact like a user, assert what is visible.
src/Counter.test.jsximport { render, screen, fireEvent } from '@testing-library/react'; import Counter from './Counter'; it('increments when clicked', () => { render(<Counter />); fireEvent.click(screen.getByRole('button', { name: /clicked 0/i })); expect(screen.getByRole('button')).toHaveTextContent('Clicked 1'); });3Mock a module
vi.mockreplaces imports;vi.fncreates spies.JSimport { vi, it, expect } from 'vitest'; vi.mock('./api', () => ({ getUser: vi.fn().mockResolvedValue({ name: 'Asha' }) })); import { getUser } from './api'; it('uses the mocked API', async () => { expect((await getUser(1)).name).toBe('Asha'); });4Run
Watch mode by default;
runfor one pass.BASHnpm test npm run test:run
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Vitest loads .env files like Vite: in tests import.meta.env.MODE is test and .env.test is applied. Only VITE_ variables are exposed to code by default.
# .env.test
VITE_API_URL=http://localhost:4010Key dependencies
| Package / tool | Used for |
|---|---|
vitest | Runner, expect, vi mocks, watch |
jsdom / happy-dom | DOM environment |
@testing-library/react + jest-dom | Component testing and DOM matchers |
@vitest/coverage-v8 | Coverage |
@vitest/ui | Browser UI for test results |
Folder structure
src/
├── components/
│ ├── Counter.jsx
│ └── Counter.test.jsx
├── test/setup.js
└── slug.test.js
vite.config.js # test: { ... }Essential commands
| Command | What it does |
|---|---|
npx vitest | Watch mode |
npx vitest run | Run once (CI) |
npx vitest run --coverage | Coverage (install @vitest/coverage-v8) |
npx vitest --ui | Open the web UI (install @vitest/ui) |
npx vitest related src/file.js | Tests affected by a file |
6. Production deployment
Test frameworks are not deployed to a production server – in production they act as a quality gate: they run automatically in CI on every push and pull request, publish reports, and block the deployment when a test fails.
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| CI runner | GitHub Actions / GitLab CI / Jenkins with the same Node.js version as development |
| Install | npm ci from the lockfile |
| Gate | Test job marked as a required check before merge/deploy |
| Reports | JUnit XML / HTML / coverage uploaded as artifacts |
Deployment steps
1Enable coverage thresholds
Install the provider and set limits.
JSnpm install --save-dev @vitest/coverage-v8 // vite.config.js → test: coverage: { provider: 'v8', reporter: ['text', 'html', 'lcov'], thresholds: { lines: 80, branches: 70 }, },2Run the tests in CI on every push
Tests protect production only if they run automatically. This GitHub Actions workflow installs dependencies and runs the suite on every push and pull request; mark the job as a required check in branch protection so failing code cannot be merged or deployed.
.github/workflows/tests.ymlname: tests on: push: branches: [main] pull_request: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: lts/* cache: npm - run: npm ci - run: npx vitest run --coverage3Build after tests
Add
npm run buildafter the test step so a broken build also fails the pipeline, then deploy thedist/artifact.YAML- run: npm run build
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
document is not defined
Set environment: 'jsdom' (and install jsdom) for DOM tests, or add // @vitest-environment jsdom at the top of the file.
toBeInTheDocument is not a function
Import @testing-library/jest-dom/vitest in the setup file and list it in setupFiles.
describe is not defined
Import from vitest or enable globals: true (and add "types": ["vitest/globals"] for TypeScript).
Mocks leak between tests
Call vi.restoreAllMocks()/vi.clearAllMocks() in afterEach or enable restoreMocks: true.
Coverage command fails
Install the provider package @vitest/coverage-v8 matching your Vitest version.
Best practices
- Keep tests next to the code they test.
- Test what users see (roles, text), not internal state.
- Use
vitest runin CI and watch mode locally. - Mock network calls (msw or vi.mock).
- Fail the pipeline on coverage drops.