Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Testing and Tooling

Testing a Vite Project with Vitest

Test Vite projects with Vitest: setup, test and expect, mocking functions and modules, jsdom components, coverage, watch mode, and a plain-JavaScript test runner stand-in.

Vite's dev server and build pipeline have a natural testing companion: Vitest. It reads your vite.config.js, so your aliases, plugins and import.meta.env work in tests exactly as in the app, with no second configuration. It is fast because it reuses Vite's transform pipeline and runs tests in parallel worker threads, with a watch mode that re-runs only affected tests using the module graph.

Vitest itself is not available in our runners, so the real test files below are read-only. The runnable blocks build a very small test runner with test and expect, which is a good way to understand what a framework does.

Setup

Terminal
npm install -D vitest
JSON
{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run",
    "coverage": "vitest run --coverage"
  }
}

vitest starts watch mode in a terminal and runs once in CI (when the CI variable is set). Add a test block to the Vite config (use vitest/config for types):

JavaScript
// vite.config.js (real Vitest, read-only)
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'node',          // 'jsdom' or 'happy-dom' for DOM tests
    include: ['src/**/*.test.{js,ts}'],
    globals: false,               // true to use test/expect without importing
    setupFiles: ['./test/setup.js'],
  },
});

Your first test

Say src/math.js has:

JavaScript
export function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
export function average(list) {
  if (list.length === 0) throw new Error('empty list');
  return list.reduce((a, b) => a + b, 0) / list.length;
}

Its test file src/math.test.js:

JavaScript
import { describe, test, expect } from 'vitest';
import { clamp, average } from './math.js';

describe('clamp', () => {
  test('keeps a value inside the range', () => {
    expect(clamp(5, 0, 10)).toBe(5);
  });
  test('limits large and small values', () => {
    expect(clamp(99, 0, 10)).toBe(10);
    expect(clamp(-3, 0, 10)).toBe(0);
  });
});

describe('average', () => {
  test('computes the mean', () => {
    expect(average([2, 4, 6])).toBe(4);
  });
  test('throws on an empty list', () => {
    expect(() => average([])).toThrow('empty list');
  });
});

Terminology: describe groups tests, test (alias it) is one case, expect(value) returns an object of matchers such as toBe (strict equality), toEqual (deep equality), toContain, toThrow, toBeCloseTo for floats and toMatchSnapshot.

A tiny runner to demystify it

A framework collects tests, runs each in a try/catch, and reports. This stand-in does exactly that.

JS Stand-in: a mini test runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last test fails on purpose so you can see the report. A real test runner adds isolation, async support, timeouts, parallelism and nicer diffs, but the core is this loop.

Mocks and spies

Tests of code with side effects need test doubles. Vitest's vi object provides them:

JavaScript
import { vi, test, expect } from 'vitest';

test('calls the callback with the value', () => {
  const callback = vi.fn();
  [1, 2].forEach(callback);
  expect(callback).toHaveBeenCalledTimes(2);
  expect(callback).toHaveBeenNthCalledWith(1, 1, 0, [1, 2]);
});

test('fake timers', () => {
  vi.useFakeTimers();
  const fn = vi.fn();
  setTimeout(fn, 1000);
  vi.advanceTimersByTime(1000);
  expect(fn).toHaveBeenCalled();
  vi.useRealTimers();
});

Mock a whole module with vi.mock (hoisted to the top of the file):

JavaScript
import { vi, test, expect } from 'vitest';
import { getUser } from './api.js';
import { greeting } from './greeting.js';

vi.mock('./api.js', () => ({ getUser: vi.fn(async () => ({ name: 'Ada' })) }));

test('greets the user', async () => {
  expect(await greeting(1)).toBe('Hello, Ada');
  expect(getUser).toHaveBeenCalledWith(1);
});

Prefer mocking at boundaries (network, clock, filesystem) rather than your own pure functions; heavy mocking makes tests pass while the real code is broken.

JS Stand-in: a spy that records calls

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Passing the dependency in as an argument (as here) often removes the need for vi.mock at all.

Testing components

Choose a DOM environment per project or file: jsdom or happy-dom. For React, add Testing Library:

JSX
// Counter.test.jsx (real Vitest + Testing Library, read-only)
// @vitest-environment jsdom
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { test, expect } from 'vitest';
import Counter from './Counter.jsx';

test('increments', async () => {
  render(<Counter />);
  await userEvent.click(screen.getByRole('button', { name: /add/i }));
  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

Query by role and accessible name, as users and assistive technology do. For real-browser tests (layout, real events) Vitest also has a Browser Mode using Playwright, and end-to-end tests belong to Playwright or Cypress.

Coverage and CI

Terminal
npm install -D @vitest/coverage-v8
vitest run --coverage

Coverage shows which lines tests execute, not whether they assert anything meaningful. Use it to find untested branches, not as a target to maximize. In CI run vitest run (no watch), fail on test errors, and keep the config file as the single place for thresholds:

JavaScript
test: { coverage: { provider: 'v8', thresholds: { lines: 80, branches: 70 } } }

Useful CLI habits

  • vitest -t "clamp" runs tests whose names match.
  • test.only and test.skip focus or skip a case (do not commit .only).
  • test.each([...])('adds %i + %i', ...) runs table-driven tests.
  • In-source testing lets tiny functions carry their tests inside if (import.meta.vitest) blocks, stripped from the production build with a define setting.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Vitest work well in a Vite project?

    Vitest reads vite.config.js, so test code is transformed the same way as app code.
  2. 2. Which matcher compares objects deeply?

    toBe uses Object.is (identity for objects); toEqual compares structure.
  3. 3. What is vi.fn() used for?

    vi.fn() returns a spy you can inspect with toHaveBeenCalled and related matchers.
  4. 4. What does high coverage guarantee?

    Coverage measures executed code. Tests still need meaningful assertions.

Summary

  • Vitest shares your Vite config; run vitest in watch mode and vitest run in CI.
  • Use describe, test and expect with matchers such as toBe, toEqual and toThrow.
  • Use vi.fn, fake timers and vi.mock at boundaries; prefer dependency injection.
  • Pick jsdom or happy-dom for component tests and query by role.
  • Coverage guides you to untested code but does not prove correctness.

Next: Tooling: TypeScript, ESLint and Prettier