| | |

Vitest 40 ๐Ÿงช Cheatsheet

โฑ๏ธ Estimated read: 14 min | |

Install and bootstrap

npm i -D vitest                 # core only
npm i -D vitest @vitest/coverage-v8        # v8 coverage provider
npm i -D vitest @vitest/coverage-istanbul  # istanbul provider
npm i -D vitest jsdom                      # jsdom environment
npm i -D vitest happy-dom                  # faster DOM environment
npm i -D vitest @vitest/browser playwright  # browser mode
npm i -D vitest @vitest/ui                 # optional browser UI
npx vitest init browser         # scaffold browser-mode setup
FilePurpose
vite.config.tsConfig lives in the test key
vitest.config.tsSame, wins over vite.config.ts
vitest.setup.tssetupFiles entry, runs per environment
test.globalSetupRuns once per whole run, in a separate scope
tsconfig.jsonAdd "types": ["vitest/globals"] only if globals: true

Minimal configuration

// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    globals: true,                    // test/expect/vi as globals, no imports
    environment: "node",              // node | jsdom | happy-dom | edge-runtime
    include: ["src/**/*.{test,spec}.ts"],   // default glob covers .test/.spec
    exclude: ["**/node_modules/**", "**/dist/**"],  // default exclusions
    setupFiles: ["./vitest.setup.ts"],   // per-environment setup, runs per file
    globalSetup: ["./vitest.global.ts"], // once per run, separate context
    testTimeout: 5000,               // per-test budget in ms
    hookTimeout: 10000,              // per-hook budget in ms
    slowTestThreshold: 300,          // mark slow above this many ms
    retry: 0,                        // rerun count for failures
    bail: 0,                         // stop after N failing files (0 = never)
  },
});

CLI commands

CommandEffect
vitestWatch mode in a TTY, run mode otherwise
vitest runOne-shot run, the CI form
vitest watchWatch mode, explicit
vitest devWatch mode, alias of watch
vitest benchRun bench files only
vitest listPrint test names, do not execute
vitest related <files>Run files that import the given files
vitest merge-reports <dir>Combine blob fragments into one report
vitest init <template>Scaffold browser, coverage, or workspace setup

CLI flags

FlagEffect
--run / --no-watchForce a single run
--changed [ref]Only files affected since the git ref
--shard=1/4Run shard 1 of 4, split by test file
--reporter=defaultReporter name, repeatable
--outputFile.junit=./j.xmlPer-reporter destination
--coverageEnable coverage
--pool=forksforks | threads | vmThreads | vmForks
--maxWorkers=4Worker ceiling
--minWorkers=1Workers kept warm
--isolate=falseShare the environment per worker
--fileParallelism=falseFiles run one at a time
--tags-filter=@smokeTag selection, ! negates
--project=webRestrict to a named project
--testTimeout=10000Per-test budget
--retry=2Rerun failures twice
--bail=1Abort after the first failing file
--passWithNoTestsDo not fail on an empty run
--allowOnlyPermit .only even when CI is set
--no-cacheDisable read and write of the transform cache
--silentSuppress console output from tests
--typecheckEnable typechecking
--update / -uRewrite snapshots
--config <path>Alternate config file
--dir <path>Base directory for discovery
--sequence.shuffleRandomize test order

Test API

FormBehavior
test(name, fn)Sequential test, the default
test(name, options, fn)Options object in the middle
test.onlyRun only this test
test.skipSkip this test
test.todoPlaceholder, reported as todo
test.failsPass only if the body throws
test.concurrentRun alongside sibling tests via Promise.all
test.skipIf(cond)Conditional skip, condition evaluated at collection
test.runIf(cond)Conditional run
test.each(table)Table-driven, rows spread as arguments
test.for(table)Table-driven, row passed as one value, $ interpolation
test.extend(fixtures)Define a fixture-carrying test
test.scoped(options)Apply skip/only defaults to the suite
bench(name, fn)Benchmark entry, vitest bench
import { test, expect } from "vitest";

// Sequential default
test("adds", () => {
  expect(1 + 1).toBe(2);            // equality by Object.is
});

// Options object middle argument
test("slow path", { timeout: 15_000, retry: 2 }, async () => {
  await longRunningTask();          // gets 15s and two retries
});

// Table with spread
test.each([1, 2, 3])("is positive: %i", (n) => {
  expect(n).toBeGreaterThan(0);     // one test per row
});

// Table with a single object per row
test.for([{ a: 1, b: 2 }])("sums $a and $b", ({ a, b }) => {
  expect(a + b).toBe(3);            // $a and $b interpolate the names
});

// Conditional
test.skipIf(!process.env.DB)("hits the database", async () => {
  await db.ping();                  // skipped when DB is unset
});

describe and nesting

import { describe, test, expect } from "vitest";

describe("cart", () => {
  test("adds an item", () => { /* ... */ });

  describe("totals", () => {
    test("sums prices", () => { /* ... */ });
  });
});

// Shared tags and repeats
describe.each([["a"], ["b"]])("case %s", (name) => {
  test(`handles ${name}`, () => { /* ... */ });
});
BlockNotes
describe(name, fn)Synchronous body, tests collected eagerly
describe.only / .skipApplies to every test inside
describe.each(table)Repeats the block per row
describe.for(table)Single value per row
describe.concurrentEvery test inside runs concurrently
describe(name, { tags }, fn)Tags applied to every contained test

Assertions

MatcherCompares
toBe(x)Object.is identity
toEqual(x)Deep equality, ignores undefined props
toStrictEqual(x)Deep equality, checks class and sparse arrays
toBeTruthy() / toBeFalsy()Loose boolean
toBeNull() / toBeUndefined() / toBeDefined()Presence
toBeGreaterThan(n) / toBeLessThan(n)Numeric order
toBeCloseTo(n, digits)Floating point
toContain(x)Array or string membership
toContainEqual(obj)Deep membership in an array
toHaveLength(n).length
toHaveProperty("a.b", v)Path lookup
toMatchObject(obj)Partial deep match
toMatch(/re/)String or regex
toThrow() / toThrow(/re/) / toThrow(Error)Throw check
toBeInstanceOf(C)instanceof
toMatchSnapshot()Serialized snapshot
toMatchInlineSnapshot()Snapshot written into the file
toMatchFileSnapshot(path)Snapshot written to a named file
toBeTypeOf("string")typeof
toSatisfy(fn)Custom predicate

Mock and spy matchers

MatcherChecks
toHaveBeenCalled()Any call
toHaveBeenCalledTimes(n)Call count
toHaveBeenCalledWith(...args)Any call matched
toHaveBeenLastCalledWith(...args)Last call matched
toHaveBeenNthCalledWith(n, ...args)Nth call, 1-based
toHaveReturned()Non-throwing return
toHaveReturnedWith(v)A return value matched
toHaveReturnedTimes(n)Non-throwing count
toHaveBeenResolvedWith(v)Resolved value matched
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

FormEffect
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

APIEffect
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

APIEffect
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

APIEffect
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

HookRuns
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

APIBehavior
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
snapshotFormatSerializer config
resolveSnapshotPathCustom storage path
--update / -uRewrite 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
      },
    },
  },
});
ReporterOutput
textTerminal table
text-summaryTwo-line summary
htmlBrowsable report
json / json-summaryMachine readable
lcovlcov.info for external tools
clover / coberturaCI-provider formats

Reporters

ReporterOutput
defaultTree grouped by file with counts and durations
verboseOne line per test
dotMinimal progress dots
jsonFull result tree
junitXML for the CI test-results tab
tap / tap-flatTAP formats
github-actionsInline annotations on the PR diff
blobMergeable fragment for merge-reports
hanging-processSignals 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

OptionDefaultCost Driver
pool: "forks"Yes~100โ€“200ms per worker
pool: "threads"No~10โ€“30ms per worker
pool: "vmThreads"NoHighest, per-file context
pool: "vmForks"NoFork + per-file context
isolate: trueYesSetup per file
isolate: falseNoOne setup per worker
maxWorkersavailableParallelism()Workers created
minWorkers0Workers kept warm
fileParallelismtrueFiles overlap per worker
maxConcurrency5Concurrent 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

environmentProvides
nodePlain Node globals, default
jsdomFull DOM implementation, slower
happy-domFaster DOM, fewer edge cases
edge-runtimeEdge 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 APIEffect
pagePlaywright page for DOM queries
userEventReal 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
});

Configuration reference

KeyDefault
include`[“**/*.{test,spec}.?(c
excludenode_modules, dist, .idea, .git
environment"node"
globalsfalse
testTimeout5000
hookTimeout10000
slowTestThreshold300
retry0
bail0
maxWorkersavailableParallelism()
minWorkers0
pool"forks"
isolatetrue
fileParallelismtrue
sequence.hooks"stack"
sequence.shufflefalse
snapshotFormat{ escapeString: false, printBasicPrototype: false }
coverage.provider"v8"
reporters["default"]
allowOnly!process.env.CI
passWithNoTestsfalse
strictTagstrue

Common gotchas

GotchaCauseFix
vi.mock does nothingCalled after the importHoist or use vi.doMock
toHaveBeenCalled failsSpy created after the call siteSpy in beforeEach
Mock not resetclearAllMocks keeps implementationsresetAllMocks
Fake timers hangMicrotasks not drainedadvanceTimersByTimeAsync
Snapshot diff noiseUnstable object keysSort or use a serializer
Test passes alone, fails in suiteisolate: false state leakIsolate that project
Native module errorspool: "threads"Switch to forks
CI slower than localCold transform cacheCache node_modules/.vite
Empty shard fails--changed shrank the listLower the shard count
Reporter file overwrittenTwo file reporters, one pathUse outputFile map
.only fails in CIallowOnly is false when CI setRemove the .only
ESM import errorsCJS package under ssrserver.deps.inline

Version notes worth knowing

ChangeSince
pool default moved to forksv1
poolOptions removed, use maxWorkersv4
maxWorkers / minWorkers addedv3
basic reporter removed, use defaultv4
coverage.all removed, use includev4
coverage.ignoreEmptyLines removedv4
AST-aware coverage remapping always onv4
vitest.workspace.ts replaced by test.projectsv3.2
test.for / describe.for addedv2
onTestFinished / onTestFailed addedv1
test.concurrent bounded by maxConcurrencyv3
strictTags guardv3

One file to copy

// vitest.config.ts โ€” a complete, current configuration
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    globals: true,                              // no imports for test/expect/vi
    environment: "node",                        // override per project for DOM
    include: ["src/**/*.{test,spec}.ts"],       // discovery pattern
    exclude: ["**/node_modules/**", "**/dist/**"],
    setupFiles: ["./vitest.setup.ts"],          // per-file setup

    pool: "forks",                              // full process isolation
    maxWorkers: 4,                              // at or below the runner's cores
    minWorkers: 2,                              // keep two warm
    isolate: true,                              // fresh module registry per file

    testTimeout: 5000,                          // per-test budget
    hookTimeout: 10000,                         // per-hook budget
    retry: process.env.CI ? 2 : 0,              // retries only in CI
    bail: process.env.CI ? 1 : 0,               // stop early in CI

    reporters: ["default", "junit"],            // terminal plus xml
    outputFile: { junit: "./reports/junit.xml" },

    coverage: {
      provider: "v8",                           // native V8 counters
      include: ["src/**/*.ts"],                 // measured whether tested or not
      exclude: ["src/**/*.test.ts", "**/*.d.ts"],
      reporter: ["text", "html", "lcov"],
      thresholds: { lines: 80, branches: 75, functions: 80, statements: 80 },
    },

    tags: [{ name: "@slow", timeout: 60_000 }], // tag-level overrides
    strictTags: true,                           // reject undeclared tags
  },
});

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!