Testing & Code Quality

Vitest Setup & Deployment Guide

Fast, Vite-native test runner with a Jest-compatible API – unit and component tests, coverage and UI, running in CI before every deploy.

Updated Official documentation ↗

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 needVersion / notes
Node.jsCurrent LTS release
A projectWorks best with Vite – see the ReactJS guide

3. Local setup

  1. 1Install Vitest

    Add scripts for watch mode and single runs.

    BASH
    npm install --save-dev vitest
    npm pkg set scripts.test="vitest"
    npm pkg set scripts.test:run="vitest run"
  2. 2Add a DOM environment for component tests

    jsdom simulates the browser; Testing Library renders components the way users see them.

    BASH
    npm install --save-dev jsdom @testing-library/react @testing-library/jest-dom
  3. 3Configure

    Put test options in vite.config (or a separate vitest.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

  1. 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');
      });
    });
  2. 2Component test

    Render, interact like a user, assert what is visible.

    src/Counter.test.jsx
    import { 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');
    });
  3. 3Mock a module

    vi.mock replaces imports; vi.fn creates spies.

    JS
    import { 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');
    });
  4. 4Run

    Watch mode by default; run for one pass.

    BASH
    npm 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
# .env.test
VITE_API_URL=http://localhost:4010

Key dependencies

Package / toolUsed for
vitestRunner, expect, vi mocks, watch
jsdom / happy-domDOM environment
@testing-library/react + jest-domComponent testing and DOM matchers
@vitest/coverage-v8Coverage
@vitest/uiBrowser UI for test results

Folder structure

project structure
src/
├── components/
│   ├── Counter.jsx
│   └── Counter.test.jsx
├── test/setup.js
└── slug.test.js
vite.config.js         # test: { ... }

Essential commands

CommandWhat it does
npx vitestWatch mode
npx vitest runRun once (CI)
npx vitest run --coverageCoverage (install @vitest/coverage-v8)
npx vitest --uiOpen the web UI (install @vitest/ui)
npx vitest related src/file.jsTests 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

RequirementRecommendation
CI runnerGitHub Actions / GitLab CI / Jenkins with the same Node.js version as development
Installnpm ci from the lockfile
GateTest job marked as a required check before merge/deploy
ReportsJUnit XML / HTML / coverage uploaded as artifacts

Deployment steps

  1. 1Enable coverage thresholds

    Install the provider and set limits.

    JS
    npm install --save-dev @vitest/coverage-v8
    
    // vite.config.js → test:
    coverage: {
      provider: 'v8',
      reporter: ['text', 'html', 'lcov'],
      thresholds: { lines: 80, branches: 70 },
    },
  2. 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.yml
    name: 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 --coverage
  3. 3Build after tests

    Add npm run build after the test step so a broken build also fails the pipeline, then deploy the dist/ 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.

terminal$ npx vitest run ✓ src/slug.test.js (1 test) 2ms ✓ src/Counter.test.jsx (1 test) 38ms ✓ src/api.test.js (1 test) 4ms Test Files 3 passed (3) Tests 3 passed (3) Duration 812ms
Figure 1: terminal output of the sample Vitest project (section 4).
1Write tests2vitest (watch)3CI: vitest run--coverage4Build dist/5Deploy if green
Figure 2: production deployment flow (section 6).
src/├── components/│ ├── Counter.jsx│ └── Counter.test.jsx├── test/setup.js└── slug.test.jsvite.config.js # test: { ... }
Figure 3: project folder structure (section 5).

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 run in CI and watch mode locally.
  • Mock network calls (msw or vi.mock).
  • Fail the pipeline on coverage drops.