import { test, expect, vi } from "vitest";
test("records calls", () => {
const fn = vi.fn((x: number) => x * 2); // mock with an implementation
expect(fn(2)).toBe(4); // call it directly
expect(fn).toHaveBeenCalledTimes(1); // one call recorded
expect(fn).toHaveBeenCalledWith(2); // arguments matched
expect(fn).toHaveReturnedWith(4); // return value matched
});
Modifiers and async matchers
Form
Effect
expect(x).not.toBe(y)
Negation
expect.soft(x).toBe(y)
Record failure, keep running the test
expect(x).resolves.toBe(y)
Awaits the promise, asserts the value
expect(x).rejects.toThrow(/re/)
Awaits the promise, asserts the rejection
expect.poll(fn, opts)
Retries fn until the assertion passes
expect.assertions(n)
Assert the test ran exactly n assertions
expect.hasAssertions()
Assert at least one assertion ran
expect.unreachable(msg)
Explicit failure marker
expect.addSnapshotSerializer(p)
Register a serializer
import { test, expect } from "vitest";
test("resolves and rejects", async () => {
await expect(fetchUser(1)).resolves.toMatchObject({ id: 1 }); // awaited value
await expect(fetchUser(0)).rejects.toThrow(/not found/); // rejection
});
test("polls until ready", async () => {
await expect.poll(() => server.requests.length, {
timeout: 2000, // total budget
interval: 50, // gap between attempts
}).toBeGreaterThan(0); // retried until it passes or times out
});
Mocking functions and modules
API
Effect
vi.fn(impl?)
Standalone mock
vi.spyOn(obj, "m")
Wrap a real method, keep the original
vi.mock("./mod", factory?)
Hoisted module replacement
vi.doMock("./mod", factory?)
Non-hoisted, applies to later imports
vi.unmock("./mod")
Undo vi.mock for that path
vi.mocked(fn, { partial: true })
Typed cast, keeps implementation
vi.hoisted(fn)
Run a value factory above the imports
vi.importActual("./mod")
The real module, inside a factory
vi.importMock("./mod")
The fully mocked module
vi.resetModules()
Clear the module registry
vi.clearAllMocks()
Calls and instances only
vi.resetAllMocks()
Calls, instances, and implementations
vi.restoreAllMocks()
Undo every spyOn, back to originals
import { test, expect, vi, beforeEach } from "vitest";
import { sendMail } from "./mail"; // the module under test
import * as api from "./api"; // module to mock
vi.mock("./api", async (importOriginal) => {
const real = await importOriginal<typeof api>(); // keep the real exports
return { ...real, post: vi.fn() }; // replace only post
});
// Order-sensitive constants go in vi.hoisted
const token = vi.hoisted(() => "test-token"); // defined before imports run
beforeEach(() => {
vi.clearAllMocks(); // reset counts, not implementations
});
test("calls the api", async () => {
vi.mocked(api.post).mockResolvedValue({ ok: true }); // typed stub
await sendMail("a@b.c");
expect(api.post).toHaveBeenCalledWith("/mail", expect.objectContaining({ to: "a@b.c" }));
});
Mock instance surface
const fn = vi.fn();
fn.mock.calls // [[arg1, arg2], ...]
fn.mock.results // [{ type: "return", value }, ...]
fn.mock.lastCall // the most recent argument list
fn.mock.instances // `this` for each call
fn.mockImplementation(f) // replace the body
fn.mockImplementationOnce(f) // replace the body for one call
fn.mockReturnValue(v) // constant return
fn.mockReturnValueOnce(v) // constant return for one call
fn.mockResolvedValue(v) // async constant
fn.mockRejectedValue(e) // async rejection
fn.mockName("label") // readable output
fn.mockClear() // clear recorded calls
fn.mockReset() // clear calls and the implementation
fn.mockRestore() // undo spyOn, back to the original method
Timers
API
Effect
vi.useFakeTimers(opts?)
Replace timers, { toFake: [...] } limits which
vi.useRealTimers()
Restore the real ones
vi.advanceTimersByTime(ms)
Move the clock forward
vi.advanceTimersByTimeAsync(ms)
Same, awaiting microtasks
vi.runAllTimers()
Drain the queue
vi.runAllTimersAsync()
Drain, awaiting microtasks
vi.runOnlyPendingTimers()
One generation only
vi.advanceTimersToNextTimer()
Jump to the next scheduled timer
vi.clearAllTimers()
Empty the queue, do not restore
vi.getTimerCount()
Pending timers
vi.setSystemTime(ms)
Pin Date.now()
vi.getRealSystemTime()
The real clock
vi.setSystemTime("2024-01-01")
Date-shaped input accepted
import { test, expect, vi, beforeEach, afterEach } from "vitest";
beforeEach(() => {
vi.useFakeTimers(); // all timers replaced
vi.setSystemTime(new Date("2024-06-01T00:00:00Z")); // pinned clock
});
afterEach(() => {
vi.useRealTimers(); // always restore
});
test("debounces", async () => {
const fn = vi.fn();
const debounced = debounce(fn, 300); // the unit under test
debounced();
expect(fn).not.toHaveBeenCalled(); // still inside the window
await vi.advanceTimersByTimeAsync(300); // drains promises too
expect(fn).toHaveBeenCalledTimes(1); // fired once
});
Environment and global stubbing
API
Effect
vi.stubEnv("KEY", "v")
Set process.env.KEY and import.meta.env.KEY
vi.unstubAllEnvs()
Restore every stubbed key
vi.stubGlobal("fetch", fn)
Replace a global for this file
vi.unstubAllGlobals()
Restore every stubbed global
vi.waitFor(fn, opts)
Retry an async assertion
vi.waitUntil(fn, opts)
Retry until truthy
vi.dynamicImportSettled()
Await pending dynamic imports
import { test, expect, vi, afterEach } from "vitest";
afterEach(() => {
vi.unstubAllEnvs(); // restore env after each test
vi.unstubAllGlobals(); // restore globals after each test
});
test("reads configuration", async () => {
vi.stubEnv("API_URL", "http://test"); // process.env and import.meta.env
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}")));
await loadConfig();
expect(fetch).toHaveBeenCalledWith("http://test"); // stubbed target
});
Lifecycle hooks
Hook
Runs
beforeAll(fn)
Once per suite
afterAll(fn)
Once per suite, after its tests
beforeEach(fn)
Before every test in scope
afterEach(fn)
After every test in scope
onTestFinished(fn)
Inside a test body, after it resolves
onTestFailed(fn)
Inside a test body, only on failure
import { describe, test, beforeAll, afterAll, beforeEach, onTestFinished } from "vitest";
describe("database", () => {
beforeAll(async () => { await db.connect(); }); // once for the suite
afterAll(async () => { await db.close(); }); // once, after all tests
beforeEach(async () => { await db.truncate(); }); // before every test
test("inserts", async () => {
onTestFinished(async () => { await db.rollback(); }); // teardown for this test
await db.insert({ id: 1 });
});
});
Fixtures with test.extend
import { test as base, expect } from "vitest";
// Declare the fixture types
type Fixtures = {
db: Database; // setup-only, no teardown
user: { id: number }; // derived from db
};
export const test = base.extend<Fixtures>({
db: async ({}, use) => { // use() hands the value to the test
const conn = await connect();
await use(conn); // test body runs here
await conn.close(); // teardown after use() returns
},
user: async ({ db }, use) => { // depends on another fixture
const u = await db.createUser();
await use(u);
},
});
test("uses the fixture", async ({ user }) => {
expect(user.id).toBeGreaterThan(0); // fixture injected by name
});
Snapshots
API
Behavior
toMatchSnapshot()
Serialized, stored in __snapshots__
toMatchInlineSnapshot()
Written into the test file
toMatchFileSnapshot(path)
Written to a named file
test("x", { snapshot: false })
Disable snapshots for one test
snapshotFormat
Serializer config
resolveSnapshotPath
Custom storage path
--update / -u
Rewrite all snapshots
import { test, expect } from "vitest";
test("renders a card", () => {
expect(renderCard()).toMatchSnapshot(); // written on first run
expect(renderCard()).toMatchInlineSnapshot(); // written into this file
});
test("writes a fixture", async () => {
await expect(JSON.stringify(config)).toMatchFileSnapshot("./snap/config.json");
});
Coverage
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
coverage: {
provider: "v8", // v8 | istanbul
include: ["src/**/*.{ts,tsx}"], // what to measure, tested or not
exclude: ["src/**/*.test.{ts,tsx}", "**/*.d.ts"],
reporter: ["text", "html", "json", "lcov"], // one or many formats
reportsDirectory: "./coverage", // output root
clean: true, // wipe the directory first
skipFull: false, // hide 100% files from text
thresholds: {
lines: 80, // source-level percentage
branches: 75,
functions: 80,
statements: 80,
autoUpdate: false, // rewrite the numbers instead of failing
},
},
},
});
Reporter
Output
text
Terminal table
text-summary
Two-line summary
html
Browsable report
json / json-summary
Machine readable
lcov
lcov.info for external tools
clover / cobertura
CI-provider formats
Reporters
Reporter
Output
default
Tree grouped by file with counts and durations
verbose
One line per test
dot
Minimal progress dots
json
Full result tree
junit
XML for the CI test-results tab
tap / tap-flat
TAP formats
github-actions
Inline annotations on the PR diff
blob
Mergeable fragment for merge-reports
hanging-process
Signals that block exit
// vitest.config.ts
export default defineConfig({
test: {
reporters: ["default", "junit", "json"], // three formats in one run
outputFile: {
junit: "./reports/junit.xml", // per-reporter destination
json: "./reports/results.json",
},
},
});
CI: sharding, tags, merging
# Split by test file, one job per shard
npx vitest run --shard=1/4 --reporter=blob # writes .vitest-reports
# Combine the fragments in a later job
npx vitest merge-reports --reporter=default --reporter=junit all-blobs
# Select by tag
npx vitest run --tags-filter='@smoke' # inclusion
npx vitest run --tags-filter='!@db' # exclusion
# Only files affected by the diff
git fetch origin main --depth=1
npx vitest run --changed=origin/main
// vitest.config.ts
export default defineConfig({
test: {
tags: [
{ name: "@slow", timeout: 60_000 }, // tag carries a timeout
{ name: "@flaky", retry: 3 }, // tag carries a retry
],
strictTags: true, // undeclared tag = failure
allowOnly: !process.env.CI, // reject .only in CI
passWithNoTests: false, // empty run is a failure
},
});
Performance knobs
Option
Default
Cost Driver
pool: "forks"
Yes
~100โ200ms per worker
pool: "threads"
No
~10โ30ms per worker
pool: "vmThreads"
No
Highest, per-file context
pool: "vmForks"
No
Fork + per-file context
isolate: true
Yes
Setup per file
isolate: false
No
One setup per worker
maxWorkers
availableParallelism()
Workers created
minWorkers
0
Workers kept warm
fileParallelism
true
Files overlap per worker
maxConcurrency
5
Concurrent tests per file
// vitest.config.ts โ the fastest safe combination for a unit package
export default defineConfig({
test: {
pool: "threads", // cheap startup, no native modules here
minWorkers: 2, // keep two warm across runs
isolate: false, // one setup per worker, no shared state
deps: {
optimizer: {
web: { enabled: true }, // pre-bundle once per session
ssr: { enabled: true },
},
},
cache: { dir: "./node_modules/.vite" }, // the directory CI restores
},
});
Projects (the workspace replacement)
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
projects: [
{
test: {
name: "unit", // selected with --project=unit
include: ["packages/unit/**/*.test.ts"],
environment: "node", // no DOM needed
isolate: false,
},
},
{
test: {
name: "web", // selected with --project=web
include: ["packages/web/**/*.test.tsx"],
environment: "jsdom", // DOM required
setupFiles: ["./packages/web/setup.ts"],
},
},
],
},
});
Environments and browser mode
environment
Provides
node
Plain Node globals, default
jsdom
Full DOM implementation, slower
happy-dom
Faster DOM, fewer edge cases
edge-runtime
Edge env, Request/Response
// vitest.config.ts โ browser mode with real DOM and real events
export default defineConfig({
test: {
browser: {
enabled: true, // Playwright drives a real browser
name: "chromium", // chromium | firefox | webkit
headless: true, // no visible window
screenshotFailures: true, // capture on failure
},
},
});
Browser API
Effect
page
Playwright page for DOM queries
userEvent
Real event dispatch, not synthetic
expect.element(locator)
Retrying DOM assertion
toMatchAriaSnapshot()
Accessibility-tree snapshot
toHaveScreenshot()
Visual regression, needs a baseline
Type testing
// vitest.config.ts
export default defineConfig({
test: {
typecheck: {
enabled: true, // runs *.test-d.ts files through tsc
include: ["src/**/*.test-d.ts"],
checker: "tsc", // tsc | vue-tsc
ignoreSourceErrors: false, // fail on errors outside the test file
},
},
});
// src/types.test-d.ts
import { expectTypeOf, test } from "vitest";
test("infers the return type", () => {
expectTypeOf(getUser).returns.toEqualTypeOf<User>(); // exact match
expectTypeOf(getUser).parameter(0).toBeNumber(); // parameter type
expectTypeOf<string>().not.toBeAny(); // any check
});