TExcelTAD
Home › Vite › Vite Testing with Vitest

Vite Testing with Vitest

Vitest is a test runner built on top of Vite. It reuses your vite.config — aliases, plugins, TypeScript, JSX, Vue/Svelte support, import.meta.env — so tests understand your code exactly like the dev server does. No separate Babel or Jest transform setup.

Install and add a script

bash · try it yourself
npm install -D vitest
added 34 packages, and audited 47 packages in 6s

found 0 vulnerabilities
json
{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run",
    "coverage": "vitest run --coverage"
  }
}

vitest starts in watch mode locally (re-runs affected tests on save, like HMR for tests) and runs once in CI (when the CI environment variable is set). vitest run always runs once.

Your first test

js
// src/price.js
export function formatPrice(cents, currency = 'USD') {
  if (!Number.isInteger(cents)) throw new TypeError('cents must be an integer');
  return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}
js
// src/price.test.js
import { describe, it, expect } from 'vitest';
import { formatPrice } from './price.js';

describe('formatPrice', () => {
  it('formats cents as dollars', () => {
    expect(formatPrice(1999)).toBe('$19.99');
  });

  it('supports other currencies', () => {
    expect(formatPrice(500, 'EUR')).toBe('€5.00');
  });

  it('rejects fractions of a cent', () => {
    expect(() => formatPrice(1.5)).toThrow(TypeError);
  });
});
bash · try it yourself
npx vitest run

 RUN  v4.0.8 /home/me/my-app

 ✓ src/price.test.js (3 tests) 4ms

 Test Files  1 passed (1)
      Tests  3 passed (3)
   Start at  10:15:32
   Duration  318ms (transform 24ms, setup 0ms, collect 19ms, tests 4ms, environment 0ms, prepare 72ms)

Test files are found by the pattern **/*.{test,spec}.?(c|m)[jt]s?(x).

How a test runner works

describe, it and expect are not magic. This mini runner, written from scratch, runs the same three tests and reports results — a good mental model for what Vitest does (plus parallelism, watch mode, snapshots, mocking…):

js · try it yourself
const tests = [];
const describe = (name, fn) => { const prev = describe.prefix; describe.prefix = name + ' > '; fn(); describe.prefix = prev; };
describe.prefix = '';
const it = (name, fn) => tests.push({ name: describe.prefix + name, fn });
const expect = (actual) => ({
  toBe(expected) { if (actual !== expected) throw new Error(`expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`); },
  toThrow(Type) {
    try { actual(); } catch (e) { if (e instanceof Type) return; throw new Error('wrong error type'); }
    throw new Error('expected function to throw');
  },
});

function formatPrice(cents, currency = 'USD') {
  if (!Number.isInteger(cents)) throw new TypeError('cents must be an integer');
  return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}

describe('formatPrice', () => {
  it('formats cents as dollars', () => expect(formatPrice(1999)).toBe('$19.99'));
  it('supports other currencies', () => expect(formatPrice(500, 'EUR')).toBe('€5.00'));
  it('rejects fractions of a cent', () => expect(() => formatPrice(1.5)).toThrow(TypeError));
  it('a deliberately wrong test', () => expect(formatPrice(100)).toBe('$1'));
});

let passed = 0;
for (const t of tests) {
  try { t.fn(); passed++; console.log('✓', t.name); }
  catch (e) { console.log('✗', t.name, '—', e.message); }
}
console.log(`Tests  ${passed} passed | ${tests.length - passed} failed (${tests.length})`);
✓ formatPrice > formats cents as dollars
✓ formatPrice > supports other currencies
✓ formatPrice > rejects fractions of a cent
✗ formatPrice > a deliberately wrong test — expected "$1", got "$1.00"
Tests  3 passed | 1 failed (4)

Common matchers

Matcher Checks
toBe(x) Strict equality (Object.is)
toEqual(obj) Deep equality of objects/arrays
toContain(item) Array/string contains
toMatch(/re/) String matches a regex
toThrow(Error) Function throws
toHaveBeenCalledWith(...) A mock was called with arguments
resolves / rejects Promise outcome: await expect(p).resolves.toBe(1)
toMatchSnapshot() Compare with a stored snapshot

Configuration

Vitest reads the test key of your Vite config (or a separate vitest.config.ts):

ts
// vite.config.ts
/// <reference types="vitest/config" />
import { defineConfig } from 'vite';

export default defineConfig({
  test: {
    environment: 'jsdom',  // 'node' (default), 'jsdom' or 'happy-dom' for DOM tests
    globals: false,        // true = describe/it/expect without imports
    setupFiles: ['./src/test-setup.ts'],
    coverage: { provider: 'v8', reporter: ['text', 'html'] },
  },
});

Mocking

js
import { it, expect, vi } from 'vitest';
import { loadCourses } from './api.js';

it('calls the API once', async () => {
  const fetchMock = vi.fn().mockResolvedValue({ json: async () => [{ id: 'vite' }] });
  vi.stubGlobal('fetch', fetchMock);

  const courses = await loadCourses();

  expect(fetchMock).toHaveBeenCalledWith('/api/courses');
  expect(courses).toEqual([{ id: 'vite' }]);
  vi.unstubAllGlobals();
});

A mock function is simply a function that records its calls. A minimal vi.fn():

js · try it yourself
function fn(impl = () => undefined) {
  const mock = (...args) => { mock.calls.push(args); return impl(...args); };
  mock.calls = [];
  return mock;
}

const track = fn((event) => event.length);
track('signup');
track('purchase', { amount: 20 });

console.log('call count:', track.calls.length);
console.log('first call:', track.calls[0]);
console.log('second call:', track.calls[1]);
call count: 2
first call: ["signup"]
second call: ["purchase",{"amount":20}]

Testing components

For DOM components use environment: 'jsdom' plus Testing Library (@testing-library/react, @testing-library/vue, …), or Vitest Browser Mode, which runs tests in a real browser through Playwright.

Tip: Run npx vitest --ui for a browser dashboard of your tests, and vitest run --coverage (with @vitest/coverage-v8) to see which lines are untested.

Test yourself

Why does Vitest need little configuration in a Vite project?

  1. It doesn't support TypeScript
  2. It reuses the Vite config, plugins and transforms
  3. It runs tests in production builds
  4. It only tests HTML

Which matcher compares two objects by their contents?

  1. toBe
  2. toEqual
  3. toContain
  4. toThrow

What does vitest run do differently from vitest?

  1. Runs tests once instead of watching
  2. Runs only failed tests
  3. Skips TypeScript files
  4. Starts the dev server