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/core-config.md


name: vitest-configuration description: Configure Vitest with vite.config.ts or vitest.config.ts

Configuration

Vitest reads configuration from vitest.config.ts or vite.config.ts. It shares the same config format as Vite.

Basic Setup

// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    // test options
  },
})

Using with Existing Vite Config

Add Vitest types reference and use the test property:

// vite.config.ts
/// <reference types="vitest/config" />
import { defineConfig } from 'vite'

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
  },
})

Merging Configs

If you have separate config files, use mergeConfig:

// vitest.config.ts
import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config'

export default mergeConfig(viteConfig, defineConfig({
  test: {
    environment: 'jsdom',
  },
}))

Common Options

defineConfig({
  test: {
    // Enable global APIs (describe, it, expect) without imports
    globals: true,
    
    // Test environment: 'node', 'jsdom', 'happy-dom'
    environment: 'node',
    
    // Setup files to run before each test file
    setupFiles: ['./tests/setup.ts'],
    
    // Include patterns for test files
    include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
    
    // Exclude patterns
    exclude: ['**/node_modules/**', '**/dist/**'],
    
    // Limit test discovery to a directory (faster than broad excludes)
    dir: './src',

    // Test timeout in ms
    testTimeout: 5000,
    
    // Hook timeout in ms
    hookTimeout: 10000,
    
    // Coverage configuration (v4+: define `include`, no more `all`)
    coverage: {
      provider: 'v8', // or 'istanbul'
      reporter: ['text', 'html'],
      include: ['src/**/*.ts'],
    },
    
    // Run each file in an isolated module graph (threads/forks pools only)
    isolate: true,
    
    // Pool: 'forks' (default), 'threads', 'vmForks', 'vmThreads'
    pool: 'forks',
    
    // v4+: pool options are top-level (poolOptions was removed)
    maxWorkers: 4,
    fileParallelism: true,
    
    // Clear mock call history before each test (v5: defaults to true)
    clearMocks: true,
    
    // Restore spies created with vi.spyOn between tests
    restoreMocks: true,
    
    // Retry failed tests
    retry: 0,
    
    // Stop after first failure
    bail: 0,

    // v5: repeat every test N times regardless of result (flaky-hunting)
    repeats: 0,
  },
})

v5 Performance Config

defineConfig({
  test: {
    // Persist transformed modules on disk, reused across reruns AND separate
    // processes (stable in v5; was experimental.fsModuleCache). Cache lives in
    // node_modules by default; clear with `vitest --clearCache`. Not for browser.
    fsModuleCache: true,

    // Inline projects that don't change the Vite config reuse the declaring
    // config's Vite server (default true) — shared files transformed once.
    // Set false if a plugin must be re-instantiated per project.
    sharedViteServer: true,

    // Inject CJS globals (module/exports/require/__filename/__dirname) into
    // every module (default true). Set false for stricter ESM-like scope.
    injectCjsGlobals: false,

    // Detect async resources leaking past a test file (slow; debugging only)
    detectAsyncLeaks: false,
  },
})

v4/v5 Config Changes

  • v5 requires Vite >= 6.4.0 and Node >= 22.12.0. vite is now a required peer dependency (Yarn users must yarn add -D vite).

  • clearMocks defaults to true in v5 — vi.clearAllMocks() runs before every test (history cleared, implementations kept). Set clearMocks: false for the old behavior.

  • Inline projects inherit the root config by default (extends defaults to true) — including Vite plugins/resolve.alias. Set extends: false to opt out. See advanced-projects.

  • testNamePattern (-t) matches the >-joined full name ('math > adds'), not the space-joined Jest form.

  • vi.mock/vi.unmock/vi.hoisted must be at the top level — nested calls now throw (they were only warned before).

  • Pool default is forks (child processes), not threads.

  • poolOptions removed — maxThreads/maxForks are now top-level maxWorkers; singleThread/singleFork become maxWorkers: 1, isolate: false; VM memoryLimit is vmMemoryLimit. minWorkers was removed.

  • workspace removed — use projects. vitest.workspace.ts no longer supported.

  • coverage.all and coverage.extensions removed — by default only covered files are reported; set coverage.include explicitly.

  • Simplified exclude — only node_modules/.git excluded by default. Use test.dir to scope discovery, or spread configDefaults.exclude.

  • Config not looked up from parent dirs — pass --config explicitly when running from a subdirectory.

  • .vitest artifact dir — blob reports (.vitest/blob/), attachments (.vitest/attachments/), and the html/json/junit reporters now all live under a single .vitest/ directory; add one entry to .gitignore.

  • test.sequential/describe.sequential/sequential removed — use { concurrent: false }.

  • deps.optimizer.web renamed to deps.optimizer.client; deps.inline/deps.external moved under server.deps.

v5.1 Additions

  • cache (default true) stores per-file results (failed/duration/last run) used to run failed and slow files first and by --last-failed; cache.dir is a no-op — use cacheDir.

  • experimental.recordDependencies + experimental.vcsProvider: 'mtime' back --since-last-run (see features-filtering). vcsProvider also accepts 'git' or a custom VCSProvider, whose findChangedFiles now receives resolver.getDependencies().

  • ui: { enabled, theme: 'auto' | 'light' | 'dark' } — ui: true is shorthand for { enabled: true }; theme also applies to the Browser Mode UI.

  • fakeTimers.fakeNodeBuiltins fakes node:timers and node:timers/promises.

  • coverage.ignoreNode(node, type) (v8) skips generated code by AST node; return true, or 'ignore-this-and-nested-nodes'.

  • In multi-project runs process.cwd() stays where Vitest started, regardless of project root; use pool: 'forks' plus a project setupFiles calling process.chdir() if tests need it.

  • In Browser Mode each browser instance counts as a worker for maxWorkers.

Conditional Configuration

Use mode or process.env.VITEST for test-specific config:

export default defineConfig(({ mode }) => ({
  plugins: mode === 'test' ? [] : [myPlugin()],
  test: {
    // test options
  },
}))

Projects (Monorepos)

Run different configurations in the same Vitest process:

defineConfig({
  test: {
    projects: [
      'packages/*',
      {
        test: {
          name: 'unit',
          include: ['tests/unit/**/*.test.ts'],
          environment: 'node',
        },
      },
      {
        test: {
          name: 'integration',
          include: ['tests/integration/**/*.test.ts'],
          environment: 'jsdom',
        },
      },
    ],
  },
})

Key Points

  • Vitest uses Vite's transformation pipeline - same resolve.alias, plugins work

  • vitest.config.ts takes priority over vite.config.ts

  • Use --config flag to specify a custom config path (required from subdirectories in v5)

  • process.env.VITEST is set to true when running tests

  • Test config uses test property, rest is Vite config

  • v5 requires Vite >= 6.4.0 and Node >= 22.12.0; vite is a required peer dependency

<!-- Source references: - https://vitest.dev/guide/#configuring-vitest - https://vitest.dev/config/ -->

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