Vitest: Fast Unit Testing for Modern JS Apps
You've got a Vite app that builds fine, but the Jest setup next to it needs its own Babel config, a ts-jest preset, and a moduleNameMapper entry for every path alias. Then you add an ESM-only package and Jest starts failing with SyntaxError: Cannot use import statement outside a module. You now maintain two build pipelines, and they don't agree with each other.
Vitest fixes that by running your tests through the same Vite pipeline your app already uses. This post covers setup, writing tests, mocking, component tests, coverage, how it compares to Jest, and the places where I'd still stick with Jest.
Because it shares Vite's config and transform pipeline, there's no separate Babel or webpack setup to maintain. Your path aliases, plugins, and define values apply to tests too, so the test environment matches the app much more closely.
How Vitest Works
Jest builds its own module resolution and transform layer (usually Babel). Vitest doesn't. It hands that work to Vite, so ESM, TypeScript, JSX, and CSS imports work out of the box in most projects with no extra config. The API is mostly Jest-compatible, which keeps migrations small.
What you get:
- Instant startup: Vite's native ESM dev server means no bundling step before tests run
- Smart watch mode: Only re-runs tests affected by changed files, using the same module graph as your app
- Jest-compatible API:
describe,it,expect, and most matchers work exactly as they do in Jest - Built-in mocking:
vi.fn(),vi.spyOn(), and module mocking without extra packages - Native TypeScript & JSX: No
ts-jestor Babel plugin juggling required - In-source testing: Colocate tests directly inside implementation files if you prefer
- UI mode: An optional browser-based dashboard for visually inspecting test runs
How Vitest runs a test file through Vite's transform pipeline
Installation and Configuration
If your project already uses Vite, adding Vitest takes one command. If it doesn't, Vitest still works as a standalone runner. It spins up its own minimal Vite instance under the hood.
Install Vitest
Add Vitest as a dev dependency. For component testing, also install a DOM environment and the appropriate testing-library package.
# Core install
npm install -D vitest
# For DOM-based component testing (React example)
npm install -D jsdom @testing-library/react @testing-library/jest-dom
# Run tests
npx vitest
Configure Vitest
If you already have a vite.config.ts, add a test block to it directly. Otherwise create a standalone vitest.config.ts.
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
},
},
});
Add npm scripts
Add a few commands to package.json for local development and CI.
{
"scripts": {
"test": "vitest",
"test:run": "vitest run",
"test:ui": "vitest --ui",
"test:coverage": "vitest run --coverage"
}
}
Setting globals: true lets you use describe, it, and expect without importing them in every file, like classic Jest. If you're on TypeScript, also add "types": ["vitest/globals"] to tsconfig.json, or the editor will flag every describe as undefined even though the tests pass. If you'd rather keep things explicit, leave it false and import from vitest.
Writing Your First Tests
If you've used Jest, Jasmine, or Chai, the assertion API won't surprise you. Test files are typically named *.test.ts or *.spec.ts and live next to the code they test, or inside a dedicated __tests__ folder.
// math.test.ts
import { describe, it, expect } from 'vitest';
import { add, divide } from './math';
describe('add()', () => {
it('adds two positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
it('handles negative numbers', () => {
expect(add(-2, -3)).toBe(-5);
});
});
describe('divide()', () => {
it('throws on division by zero', () => {
expect(() => divide(10, 0)).toThrow('Cannot divide by zero');
});
it('returns a float result', () => {
expect(divide(10, 4)).toBeCloseTo(2.5);
});
});
// user-service.test.ts
import { describe, it, expect } from 'vitest';
import { fetchUser } from './user-service';
describe('fetchUser()', () => {
it('resolves with user data', async () => {
const user = await fetchUser(1);
expect(user).toMatchObject({ id: 1, name: expect.any(String) });
});
it('rejects for an invalid id', async () => {
await expect(fetchUser(-1)).rejects.toThrow('User not found');
});
});
import { beforeEach, afterEach, beforeAll, afterAll, describe, it, expect } from 'vitest';
import { createTestDb, seedDb, clearDb, closeDb } from './test-helpers';
describe('user repository', () => {
beforeAll(async () => {
await createTestDb();
});
beforeEach(async () => {
await seedDb();
});
afterEach(async () => {
await clearDb();
});
afterAll(async () => {
await closeDb();
});
it('finds a seeded user by email', async () => {
// test body uses the freshly seeded database
});
});
Mocking, Spies, and Fake Timers
The vi object plays the role of Jest's global jest object. Mocking, spying, and timer control are all on it, with no extra packages.
import { describe, it, expect, vi } from 'vitest';
import { sendWelcomeEmail } from './email';
import * as mailer from './mailer';
// Mock an entire module
vi.mock('./mailer');
describe('sendWelcomeEmail()', () => {
it('calls the mailer with the right arguments', async () => {
const spy = vi.spyOn(mailer, 'send').mockResolvedValue(true);
await sendWelcomeEmail('alice@example.com');
expect(spy).toHaveBeenCalledWith({
to: 'alice@example.com',
template: 'welcome',
});
expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('fake timers', () => {
it('fires a callback after a delay', () => {
vi.useFakeTimers();
const callback = vi.fn();
setTimeout(callback, 1000);
vi.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledOnce();
vi.useRealTimers();
});
});
Mocks keep their state across tests in the same file unless you clear them. Set clearMocks: true or restoreMocks: true in your Vitest config to reset mock state before each test. Forgetting this is a common cause of tests that pass alone and fail when run together.
One gotcha with vi.mock(): it's hoisted to the top of the file, above your imports. If the factory function references a variable you declared at the top level, Vitest throws an error telling you there are no top-level variables allowed inside the factory. The fix is to declare those values with vi.hoisted(), which is hoisted along with the mock.
Testing UI Components
For React, Vue, or Svelte components, use Testing Library. Your components go through the same Vite transform your app uses, so JSX, TypeScript, and CSS modules work without extra config.
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from './Button';
describe('<Button />', () => {
it('renders the label text', () => {
render(<Button>Save changes</Button>);
expect(screen.getByText('Save changes')).toBeInTheDocument();
});
it('calls onClick when clicked', () => {
const onClick = vi.fn();
render(<Button onClick={onClick}>Save</Button>);
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
expect(onClick).toHaveBeenCalledOnce();
});
it('is disabled while loading', () => {
render(<Button loading>Save</Button>);
expect(screen.getByRole('button')).toBeDisabled();
});
});
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
// Unmount rendered components after each test to avoid leaks
afterEach(() => {
cleanup();
});
If you see Invalid Chai property: toBeInTheDocument, the jest-dom matchers never got registered. Check that setupFiles points at this file and that it imports @testing-library/jest-dom/vitest, not the plain @testing-library/jest-dom entry.
Coverage Reports and Watch Mode
Running vitest with no arguments starts watch mode. It re-runs only the tests affected by your latest change, using the dependency graph Vite already builds for your app. In CI, use vitest run for a single pass that exits. (Vitest does fall back to run mode when it detects CI, but I'd still be explicit.)
# Watch mode (interactive, reruns on change)
npx vitest
# Single run (use this in CI)
npx vitest run
# Generate a coverage report (requires @vitest/coverage-v8)
npx vitest run --coverage
# Open the interactive browser UI
npx vitest --ui
# Run only tests matching a name pattern
npx vitest run -t "user repository"
The V8 coverage provider uses the engine's built-in coverage instead of instrumenting your source, so it's usually quick enough to run on every commit. It's a separate package:
npm install -D @vitest/coverage-v8
Vitest vs Jest: Which Should You Choose?
Jest is still a solid, well-tested choice, especially for older CRA or plain Node.js projects without Vite anywhere in the pipeline. But if the project is already built on Vite (or a Vite-based meta-framework), Vitest removes a whole layer of duplicated tooling.
| Feature | Vitest | Jest |
|---|---|---|
| Config source | Reuses vite.config.ts |
Separate jest.config.js |
| Transform engine | esbuild (via Vite) | Babel / ts-jest |
| Native ESM support | ✅ First-class | ⚠️ Requires flags/config |
| Cold start speed | ✅ Very fast | ⚠️ Slower (bundling overhead) |
| Watch mode re-runs | Module-graph aware | Heuristic file matching |
| API compatibility | Jest-compatible expect/vi |
Native |
| Ecosystem maturity | Growing fast | Extremely mature |
| Browser-mode testing | ✅ Built-in (experimental) | ❌ Not built-in |
Migrating from Jest is often a matter of swapping imports, replacing jest.fn() with vi.fn(), and installing the Vitest packages. Most describe/it/expect test bodies don't change. The parts that take real time are usually jest.mock() calls with factories (Vitest expects the factory to return an object with the module's exports, including default) and any custom Jest transformers you relied on.
When I'd Use Vitest (and When I Wouldn't)
For a new project on Vite, Nuxt, SvelteKit, or Astro, I'd pick Vitest without much thought. One config file, one transform engine, and a watch mode that knows your module graph. That's a real improvement over keeping a Jest config in sync with your bundler.
Where I'd think twice
- Large, stable Jest suites: if thousands of tests pass today and nobody's fighting the config, a migration costs time and buys you mostly speed. Move when the Jest setup actually starts hurting.
- Heavy reliance on Jest-specific tooling: custom transformers, certain snapshot serializers, or plugins with no Vitest equivalent will need rework.
- Next.js projects: Next doesn't build with Vite, so you lose the "same pipeline as the app" benefit. Vitest still works there, but you'll configure aliases and JSX handling yourself, much like with Jest.
- Treating jsdom as a real browser: jsdom doesn't do layout, so anything that depends on sizes, scrolling, or real CSS belongs in Playwright or Vitest's browser mode, not a unit test.
If you do switch, run both runners side by side on a branch for a while and compare results. Tests that pass in Jest and fail in Vitest usually point to leaked mock state or module isolation differences, and they're much easier to find before you delete the old config.