Generated banner for Vitest
Generated logo for Vitest

Vitest

Anthony FuCommunityCreated by Anthony Fu

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

Vitest fast unit testing framework powered by Vite with Jest-compatible API. Use when writing tests, mocking, configuring coverage, or working with test filtering and fixtures.
— the description by Anthony Fu

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Vitest is a testing framework built for the Vite ecosystem. It provides a Jest-compatible API and supports ESM, TypeScript, and JSX by default. It shares configuration, transformers, and plugins with Vite applications, allowing for integrated testing workflows. The framework includes features for mocking, snapshot testing, code coverage, and multi-threaded test execution.

What it does

  • Provides a Jest-compatible API for writing and running unit tests
  • Supports native ESM, TypeScript, and JSX without additional configuration
  • Enables mocking of functions, modules, timers, and dates
  • Offers built-in code coverage reporting using V8 or Istanbul
  • Supports multi-project workspaces and varied test environments like Node, jsdom, and happy-dom
  • Includes utilities for snapshot testing, test filtering, and benchmarking

When to use it

  • When you need a testing framework that integrates directly with your Vite configuration
  • When migrating existing test suites that rely on Jest-compatible APIs
  • When you require specific test environments like jsdom or happy-dom for DOM-related testing
  • When managing complex test setups across monorepos or multiple projects

Advantages

  • Shares configuration and plugins with Vite projects
  • Supports parallel test execution via multi-threaded workers
  • Provides flexible test environment configuration per file or project
  • Includes built-in support for snapshot testing and mocking utilities

Usage examples

“How do I configure Vitest to use the jsdom environment for my tests?”
The agent provides the vitest.config.ts configuration snippet using the environment: 'jsdom' property and explains how to install the necessary jsdom package.
“Can I run different test configurations in the same Vitest process?”
The agent explains how to use the projects field in the vitest.config.ts file to define multiple test suites with different environments or include patterns.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/antfu/vitest/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip vitest.zip -d .agents/skills

Documentation by Anthony Fu

Vitest is a next-generation testing framework powered by Vite. It provides a Jest-compatible API with native ESM, TypeScript, and JSX support out of the box. Vitest shares the same config, transformers, resolvers, and plugins with your Vite app.

Key Features:

  • Vite-native: Uses Vite's transformation pipeline for fast HMR-like test updates

  • Jest-compatible: Drop-in replacement for most Jest test suites

  • Smart watch mode: Only reruns affected tests based on module graph

  • Native ESM, TypeScript, JSX support without configuration

  • Multi-threaded workers for parallel test execution

  • Built-in coverage via V8 or Istanbul

  • Snapshot testing, mocking, and spy utilities

The skill is based on Vitest 5.1.0-beta.1, generated at 2026-10-23.

Core

TopicDescriptionReference
ConfigurationVitest and Vite config integration, defineConfig usagecore-config
CLICommand line interface, commands and optionscore-cli
Test APItest/it function, modifiers like skip, only, concurrentcore-test-api
Describe APIdescribe/suite for grouping tests and nested suitescore-describe
Expect APIAssertions with toBe, toEqual, matchers and asymmetric matcherscore-expect
HooksbeforeEach, afterEach, beforeAll, afterAll, aroundEachcore-hooks

Features

TopicDescriptionReference
MockingMock functions, modules, timers, dates with vi utilitiesfeatures-mocking
SnapshotsSnapshot testing with toMatchSnapshot and inline snapshotsfeatures-snapshots
CoverageCode coverage with V8 or Istanbul providersfeatures-coverage
Test ContextTest fixtures, context.expect, test.extend for custom fixturesfeatures-context
ConcurrencyConcurrent tests, parallel execution, shardingfeatures-concurrency
FilteringFilter tests by name, file patterns, tagsfeatures-filtering
Test TagsLabel tests with tags to filter runs and apply shared optionsfeatures-test-tags
ReportersBuilt-in reporters, default selection, CI/output configfeatures-reporters
BenchmarkingWrite benchmarks with the bench fixture (Tinybench)features-benchmarking

Advanced

TopicDescriptionReference
Vi Utilitiesvi helper: mock, spyOn, fake timers, hoisted, waitForadvanced-vi
EnvironmentsTest environments: node, jsdom, happy-dom, customadvanced-environments
Type TestingType-level testing with expectTypeOf and assertTypeadvanced-type-testing
ProjectsMulti-project workspaces, different configs per projectadvanced-projects

Files

references/advanced-vi.md


name: vi-utilities description: vi helper for mocking, timers, utilities

Vi Utilities

The vi helper provides mocking and utility functions.

import { vi } from 'vitest'

Mock Functions

// Create mock
const fn = vi.fn()
const fnWithImpl = vi.fn((x) => x * 2)

// Check if mock
vi.isMockFunction(fn) // true

// Mock methods
fn.mockReturnValue(42)
fn.mockReturnValueOnce(1)
fn.mockResolvedValue(data)
fn.mockRejectedValue(error)
fn.mockImplementation(() => 'result')
fn.mockImplementationOnce(() => 'once')

// Clear/reset
fn.mockClear()    // Clear call history
fn.mockReset()    // Clear history + implementation
fn.mockRestore()  // Restore original (for spies)

Spying

const obj = { method: () => 'original' }

const spy = vi.spyOn(obj, 'method')
obj.method()

expect(spy).toHaveBeenCalled()

// Mock implementation
spy.mockReturnValue('mocked')

// Spy on getter/setter
vi.spyOn(obj, 'prop', 'get').mockReturnValue('value')

Module Mocking

// Hoisted to top of file
vi.mock('./module', () => ({
  fn: vi.fn(),
}))

// Partial mock
vi.mock('./module', async (importOriginal) => ({
  ...(await importOriginal()),
  specificFn: vi.fn(),
}))

// Spy mode - keep implementation
vi.mock('./module', { spy: true })

// Import actual module inside mock
const actual = await vi.importActual('./module')

// Import as mock
const mocked = await vi.importMock('./module')

Dynamic Mocking

// Not hoisted - use with dynamic imports
vi.doMock('./config', () => ({ key: 'value' }))
const config = await import('./config')

// Unmock
vi.doUnmock('./config')
vi.unmock('./module') // Hoisted

Conditional Mocking — vi.when (v5)

Argument-specific spy behaviors:

vi.when(spy)
  .calledWith(1).thenReturn('one')
  .calledWith(2).thenReturn('two')

// then* actions: thenReturn / thenThrow / thenResolve / thenReject (+ *Once)
// options: { times }, second arg { onUnmatched: 'throw' | 'passthrough' | fn }

vi.isWhenChain(w)  // type guard for a When chain

See features-mocking for FIFO/LIFO matching and toHaveBeenExhausted.

Assertion Helpers — vi.defineHelper (4.1+)

Wrap reusable assertion functions so failures point at the call site, not inside the helper:

const expectValidUser = vi.defineHelper((user: unknown) => {
  expect(user).toHaveProperty('id')
  expect(user).toHaveProperty('email')
})

test('returns a valid user', async () => {
  expectValidUser(await fetchUser('alice')) // failures reported here
})

Reset Modules

// Clear module cache
vi.resetModules()

// Wait for dynamic imports
await vi.dynamicImportSettled()

Fake Timers

vi.useFakeTimers()

// Choose which timers to fake (toFake and toNotFake are mutually exclusive)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
vi.useFakeTimers({ toNotFake: ['setInterval'] })

// v5: Temporal is faked alongside Date when present on globalThis;
// exclude it with toNotFake: ['Temporal']

setTimeout(() => console.log('done'), 1000)

// Advance time
vi.advanceTimersByTime(1000)
vi.advanceTimersByTimeAsync(1000)  // For async callbacks
vi.advanceTimersToNextTimer()
vi.advanceTimersToNextFrame()      // requestAnimationFrame

// Run all timers
vi.runAllTimers()
vi.runAllTimersAsync()
vi.runOnlyPendingTimers()

// Clear timers
vi.clearAllTimers()

// Check state
vi.getTimerCount()
vi.isFakeTimers()

// Restore
vi.useRealTimers()

Mock Date/Time

vi.setSystemTime(new Date('2024-01-01'))
expect(new Date().getFullYear()).toBe(2024)
// v5: also drives Temporal.Now when Temporal is available

vi.getMockedSystemTime()  // Get mocked date
vi.getRealSystemTime()    // Get real time (ms)

Global/Env Mocking

// Stub global
vi.stubGlobal('fetch', vi.fn())
vi.unstubAllGlobals()

// Stub environment
vi.stubEnv('API_KEY', 'test')
vi.stubEnv('NODE_ENV', 'test')
vi.unstubAllEnvs()

Hoisted Code

Run code before imports:

const mock = vi.hoisted(() => vi.fn())

vi.mock('./module', () => ({
  fn: mock, // Can reference hoisted variable
}))

Waiting Utilities

// Wait for callback to succeed
await vi.waitFor(async () => {
  const el = document.querySelector('.loaded')
  expect(el).toBeTruthy()
}, { timeout: 5000, interval: 100 })

// Wait for truthy value
const element = await vi.waitUntil(
  () => document.querySelector('.loaded'),
  { timeout: 5000 }
)

Mock Object

Mock all methods of an object:

const original = {
  method: () => 'real',
  nested: { fn: () => 'nested' },
}

const mocked = vi.mockObject(original)
mocked.method()  // undefined (mocked)
mocked.method.mockReturnValue('mocked')

// Spy mode
const spied = vi.mockObject(original, { spy: true })
spied.method()  // 'real'
expect(spied.method).toHaveBeenCalled()

Test Configuration

vi.setConfig({
  testTimeout: 10_000,
  hookTimeout: 10_000,
})

vi.resetConfig()

Global Mock Management

vi.clearAllMocks()   // Clear all mock call history
vi.resetAllMocks()   // Reset + clear implementation
vi.restoreAllMocks() // Restore originals (spies)

vi.mocked Type Helper

TypeScript helper for mocked values:

import { myFn } from './module'
vi.mock('./module')

// Type as mock
vi.mocked(myFn).mockReturnValue('typed')

// Deep mocking
vi.mocked(myModule, { deep: true })

// Partial mock typing
vi.mocked(fn, { partial: true }).mockResolvedValue({ ok: true })

Key Points

  • vi.mock is hoisted - use vi.doMock for dynamic mocking

  • vi.hoisted lets you reference variables in mock factories

  • Use vi.spyOn to spy on existing methods (v4: supports constructors)

  • Use vi.when for argument-specific behaviors and vi.defineHelper for assertion helpers

  • Fake timers require explicit setup and teardown

  • vi.waitFor retries until assertion passes

<!-- Source references: - https://vitest.dev/api/vi.html -->

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Anthony Fu
Publisher
Anthony Fu (Community)
Source
antfu/skills · skills/vitest · commit f63e9ec
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Anthony Fu.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download vitest.zip