Vitest Cheat Sheet

Quick reference for Vitest test runner. Test syntax, assertions, mocking, snapshots, coverage, and configuration — all in one page.

Setup & CLI Test Structure Assertions (expect) Async Testing Mocking Functions Mocking Modules Snapshots Configuration (vitest.config.ts) Coverage & Reporting

Setup & CLI

npm install -D vitest Install Vitest
npx vitest Run in watch mode
npx vitest run Run once (CI mode)
npx vitest run --reporter=verbose Verbose output
npx vitest run src/utils.test.ts Run specific file
npx vitest -t "should validate" Run tests matching name
npx vitest --coverage Run with coverage report
npx vitest --ui Open browser UI dashboard
npx vitest bench Run benchmarks

Test Structure

import { describe, it, expect, test } from "vitest" Import test functions
test("adds numbers", () => { ... }) Define a test
it("should add", () => { ... }) Alias for test
describe("Math", () => { ... }) Group tests
beforeEach(() => { ... }) Run before each test
afterEach(() => { ... }) Run after each test
beforeAll(() => { ... }) Run once before all
afterAll(() => { ... }) Run once after all
test.skip("...", () => { ... }) Skip test
test.only("...", () => { ... }) Run only this test
test.todo("implement later") Placeholder test
test.each([[1,2,3], [2,3,5]])("add(%i,%i)=%i", (a,b,sum) => { ... }) Parameterized test

Assertions (expect)

expect(value).toBe(42) Strict equality (===)
expect(obj).toEqual({ a: 1 }) Deep equality
expect(value).toBeTruthy() Truthy check
expect(value).toBeFalsy() Falsy check
expect(value).toBeNull() Is null
expect(value).toBeUndefined() Is undefined
expect(value).toBeDefined() Is defined (not undefined)
expect(value).toBeGreaterThan(5) Number comparison
expect(str).toContain("hello") String/array contains
expect(str).toMatch(/pattern/) Regex match
expect(arr).toHaveLength(3) Array/string length
expect(obj).toHaveProperty("key", "value") Object has property
expect(fn).toThrow("error message") Function throws
expect(fn).toThrowError(TypeError) Throws specific error type

Async Testing

test("async", async () => { await expect(fn()).resolves.toBe(42) }) Resolved promise
await expect(fn()).rejects.toThrow("error") Rejected promise
test("callback", (done) => { fetchData(data => { expect(data).toBe("ok"); done() }) }) Callback style (done)
vi.useFakeTimers() Use fake timers
vi.advanceTimersByTime(1000) Advance timers by ms
vi.runAllTimers() Run all pending timers
vi.useRealTimers() Restore real timers

Mocking Functions

const fn = vi.fn() Create mock function
const fn = vi.fn(() => 42) Mock with implementation
fn.mockReturnValue(42) Set return value
fn.mockReturnValueOnce(42) Set return value once
fn.mockResolvedValue(data) Mock async return
fn.mockResolvedValueOnce(data) Mock async return once
fn.mockImplementation((x) => x * 2) Set implementation
expect(fn).toHaveBeenCalled() Was called
expect(fn).toHaveBeenCalledTimes(3) Call count
expect(fn).toHaveBeenCalledWith("arg") Called with args
fn.mockClear() Clear calls & results
fn.mockReset() Clear + remove implementation
fn.mockRestore() Restore original (spied fn)

Mocking Modules

vi.mock("./utils") Auto-mock module
vi.mock("./utils", () => ({ sum: vi.fn(() => 42) })) Mock with factory
vi.mock("axios") Mock npm package
vi.spyOn(object, "method") Spy on object method
vi.stubGlobal("fetch", vi.fn()) Stub global function
vi.unstubAllGlobals() Restore all globals
vi.importActual("./utils") Import real module in mock factory
vi.mocked(fn) Get typed mock (for TypeScript)

Snapshots

expect(component).toMatchSnapshot() Match file snapshot
expect(value).toMatchInlineSnapshot(`"hello"`) Match inline snapshot
npx vitest -u Update all snapshots
expect(obj).toMatchObject({ key: expect.any(String) }) Partial match with matchers
expect.stringContaining("hello") Asymmetric matcher: contains string
expect.arrayContaining([1, 2]) Asymmetric matcher: contains items
expect.objectContaining({ key: "value" }) Asymmetric matcher: contains properties

Configuration (vitest.config.ts)

import { defineConfig } from "vitest/config" Import config helper
test: { globals: true } Auto-import describe/it/expect
test: { environment: "jsdom" } Use jsdom for DOM testing
test: { environment: "happy-dom" } Use happy-dom (faster)
test: { include: ["src/**/*.{test,spec}.{js,ts}"] } Test file patterns
test: { coverage: { provider: "v8" } } Coverage with v8
test: { coverage: { provider: "istanbul" } } Coverage with istanbul
test: { setupFiles: ["./src/test-setup.ts"] } Setup files
test: { testTimeout: 10000 } Test timeout (ms)
test: { alias: { "@": "./src" } } Path aliases

Coverage & Reporting

npx vitest --coverage Generate coverage report
coverage: { reporter: ["text", "html", "lcov"] } Coverage output formats
coverage: { thresholds: { lines: 80 } } Enforce minimum coverage
coverage: { include: ["src/**"] } Coverage include paths
coverage: { exclude: ["**/*.test.ts"] } Coverage exclude paths
/* v8 ignore next */ Ignore next line from coverage
/* v8 ignore start */ ... /* v8 ignore stop */ Ignore block from coverage
Step-by-Step Guide

How to Format JSON Online

Read Guide →

More Cheat Sheets