Testing with Vitest
Vitest is a TypeScript-first test runner with Jest-compatible API and Vite-fast execution. The default choice in 2026 for new projects.
Install
SHELL
pnpm add -D vitest # package.json scripts "test": "vitest", "test:ui": "vitest --ui", "test:run":"vitest run", "coverage":"vitest run --coverage"
Your first test
src/math.test.ts
import { describe, test, expect } from 'vitest';
import { add } from './math';
describe('add', () => {
test('adds two numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('handles negatives', () => {
expect(add(-1, 1)).toBe(0);
});
});
Run
SHELL
npm test # interactive watch npm test -- src/math # filter to one folder/file npm test -- -t "adds" # filter to a test name
Snapshot tests
TS
test('render', () => {
expect(render(user)).toMatchSnapshot();
expect(component).toMatchInlineSnapshot(`"<h1>Hi</h1>"`);
});
Mocking
TS
import { vi, test, expect } from 'vitest';
import * as api from './api';
test('shows error on failure', async () => {
vi.spyOn(api, 'fetchUser').mockRejectedValue(new Error('500'));
// ... assertions ...
vi.restoreAllMocks();
});
Coverage
SHELL
pnpm add -D @vitest/coverage-v8 vitest run --coverage
Type-aware tests
Vitest's expectTypeOf tests TypeScript types themselves:
TS
import { expectTypeOf } from 'vitest';
expectTypeOf(add).toBeFunction();
expectTypeOf<ReturnType<typeof add>>().toEqualTypeOf<number>();
Tip: Most Jest tests run in Vitest unchanged. If you're migrating: install vitest, update the script, fix the handful of API differences (mostly mocking).
Example
Example
// pnpm add -D vitest
// add to package.json: "test": "vitest"
//
// import { test, expect } from 'vitest';
// test('adds', () => expect(2 + 2).toBe(4));
console.log('Vitest is Jest-compatible but Vite-fast');
Try it Yourself »
Exercise
The Vite-fast test runner.
npm install -D
Six letters.
Discussion
Loading…