Skip to main content
skill CX Codex

vitest · itechmeat — Claude Code skill: what it does, how to install

Helps an agent write and configure Vitest tests with mocks, snapshots, coverage, and browser mode. Useful for Vite and TypeScript projects.

MIT 202 installs ★ 23 updated 2026-10-24

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add itechmeat/llm-code --skill vitest -a claude-code
Open on GitHub

What vitest does

This skill gives the agent focused Vitest guidance: test and assertion APIs, hooks, vi.fn and vi.mock, fake timers, snapshots, CLI usage, and vitest.config.ts. It also covers coverage reports, UI mode, concurrent execution, and tests that run in a real browser.

The included patterns use *.test.*, *.spec.*, and __tests__ files, with commands such as vitest, vitest run, vitest run --coverage, and vitest --browser.enabled. Ask the agent to create tests, adjust configuration, or map familiar Jest-style calls to Vitest. Vitest v5 requires Node.js >=22 together with Vite >=6.4; a project below those versions will fail to run.

What it helps with

  • write unit tests for functions and classes
  • mock an API and control fake timers
  • add snapshots for generated output
  • configure code coverage reports
  • run tests in a real browser

Example prompts for the agent

  • Set up Vitest in this Vite project and create vitest.config.ts.
  • Write tests for src/api.ts with a mocked external API and call assertions.
  • Add a coverage script using vitest run --coverage.

How to install vitest

1Skills CLI (Vercel)

npx skills add itechmeat/llm-code --skill vitest -a claude-code

2Manually: put the files in place

~/.claude/skills/vitest/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/vitest/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about vitest

How do I install vitest in Claude Code?

Run npx skills add itechmeat/llm-code --skill vitest -a claude-code, then check ~/.claude/skills/vitest/SKILL.md.

What does vitest do?

The skill helps the agent write and configure Vitest tests, including assertions, mocks, snapshots, coverage, CLI commands, and browser mode.

What does Vitest v5 require?

It requires Node.js >=22 and Vite >=6.4. By default, test files use .test. or .spec. in their names, and __tests__ directories are supported.

Source text

SKILL.md · MIT
---
name: vitest
description: "Vitest testing framework: Vite-powered tests, Jest-compatible API, mocking, snapshots, coverage, browser mode, and TypeScript support. Use when writing or configuring tests with Vitest, setting up mocking/snapshots, configuring coverage, or running browser-mode tests. Keywords: Vitest, testing, Vite, Jest, mocking, coverage."
metadata:
  version: "5.0.5"
  release_date: "2026-10-15"
---

# Vitest

Next generation testing framework powered by Vite.

## Quick Navigation

- [Test API](references/api.md) - test, describe, hooks
- [Expect API](references/expect.md) - matchers and assertions
- [Mocking](references/mocking.md) - vi.fn, vi.mock, fake timers
- [Configuration](references/config.md) - vitest.config.ts options
- [CLI](references/cli.md) - command line reference
- [Browser Mode](references/browser.md) - real browser testing

## When to Use

- Testing Vite-based applications (shared config)
- Need Jest-compatible API with native ESM support
- Component testing in real browser
- Fast watch mode with HMR
- TypeScript testing without extra config
- Parallel test execution

## Installation

Install: `npm install -D vitest`. Requires Node.js >=22 and Vite >=6.4 in v5.

## Release Highlights (5.0.0)

- **Requirements:** Node.js >=22 and Vite >=6.4 are required. `@vitest/runner` is inlined (the package is no longer published) and `expect` is inlined, so old entry points were removed.
- **Mock/timer behavior:** mocks are cleared by default before each test, and `Temporal` can now be mocked (with or without fake timers).
- **Replaced APIs:** `sequential` test/suite options are removed in favor of `concurrent`; the `webdriverio` browser provider is removed; `toHaveTextContent` is strict with `toMatchTextContent` as the alternative; `expect.poll` fails when the function does not resolve in time.
- **New defaults/outputs:** `attachmentsDir` defaults to `.vitest/attachments/` (was `.vitest-attachments/`), and blob/json/junit/html reporter outputs default to `.vitest`; a `createReport` API and `.vitest` report directory convention are introduced.
- **Projects:** inline projects extend the root config by default, nested projects are supported, distinct projects share one Vite server, and the config file is no longer looked up from ancestor directories (parent dirs no longer apply).
- **Browser:** locator objects replace locator strings, `locators.exact` is on by default, and a `screenshotDirectory` config controls `toMatchScreenshot` output.
- **Misc:** benchmark public API was rewritten with a pluggable provider API; `-p` is a shorthand for `--project`; `-t` uses `>` as separator; coverage `thresholds.perFile` accepts an object and TypeScript build mode / `vitest list` static parsing are supported.

## Patch Notes (5.0.1 -> 5.0.5)

- `5.0.2` to `5.0.5` are fixes only — the `5.0` API surface is unchanged.
- The root temp directory is removed when the run closes, and `--changed` handles quoted file names.
- `import.meta.hot` stubs expose `data`, `skipIf` sets `skip` and ignores `undefined` options, and the native loader keeps the import frame inside its errors.
- Browser mode: late connections of closed sessions are dropped, global setup runs once with instances, the browser waits up to 30s to close, and synthetic `pagehide` events are ignored.
- Hook cleanups run even when a later hook fails, mocks of finished test files are released, and all running tests are aborted on cancel.
- The reporter reports end reason `failed` when a worker crashes.

## Release Highlights (4.1.0 -> 4.1.6)

- New control-flow hooks: `aroundEach` and `aroundAll`.
- Test metadata expands with tags, `meta`, and improved `test.extend` type inference.
- CLI adds `--detect-async-leaks`, richer `--update` modes, and static collection for `vitest list`.
- Browser mode grows Playwright persistent contexts, `userEvent.wheel`, and stronger trace/artifact handling.
- Mocking/timers add disposable `doMock()`, `mockThrow` / `mockThrowOnce`, and `setTickMode`.
- `4.1.4` adds experimental ARIA snapshots, `filterMeta` for the JSON reporter, and exposes `assertion` as a public experimental field.
- `4.1.5` adds coverage `instrumenter` support and improves reporter/UI behavior around large snapshots and HTML output.
- `4.1.6` tightens browser screenshot path resolution and fixes `sequence.concurrent` handling for concurrent test scheduling.

## Quick Start

```js
// sum.js
export function sum(a, b) {
  return a + b;
}
```

```js
// sum.test.js
import { expect, test } from "vitest";
import { sum } from "./sum.js";

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});
```

```json
// package.json
{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run",
    "coverage": "vitest run --coverage"
  }
}
```

## Configuration

```ts
// vitest.config.ts (recommended)
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    globals: true, // Enable global test APIs
    environment: "jsdom", // Browser-like environment
    include: ["**/*.{test,spec}.{js,ts,jsx,tsx}"],
    coverage: {
      provider: "v8",
      reporter: ["text", "html"],
    },
  },
});
```

Or extend Vite config:

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

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

## Test File Naming

By default, tests must contain `.test.` or `.spec.` in filename:

- `sum.test.js`
- `sum.spec.ts`
- `__tests__/sum.js`

## Key Commands

```bash
# Watch mode (default)
vitest

# Single run
vitest run

# With coverage
vitest run --coverage

# Filter by file/test name
vitest sum
vitest -t "should add"

# UI mode
vitest --ui

# Browser tests
vitest --browser.enabled
```

## Common Patterns

### Basic Test

```ts
import { describe, it, expect, beforeEach } from "vitest";

describe("Calculator", () => {
  let calc: Calculator;

  beforeEach(() => {
    calc = new Calculator();
  });

  it("adds numbers", () => {
    expect(calc.add(1, 2)).toBe(3);
  });

  it("throws on invalid input", () => {
    expect(() => calc.add("a", 1)).toThrow();
  });
});
```

### Mocking

```ts
import { vi, expect, test } from "vitest";
import { fetchUser } from "./api";

vi.mock("./api", () => ({
  fetchUser: vi.fn(),
}));

test("uses mocked API", async () => {
  vi.mocked(fetchUser).mockResolvedValue({ name: "John" });

  const user = await fetchUser(1);

  expect(fetchUser).toHaveBeenCalledWith(1);
  expect(user.name).toBe("John");
});
```

### Snapshot Testing

```ts
import { expect, test } from "vitest";

test("matches snapshot", () => {
  const result = generateConfig();
  expect(result).toMatchSnapshot();
});

// Inline snapshot (auto-updates)
test("inline snapshot", () => {
  expect({ foo: "bar" }).toMatchInlineSnapshot();
});
```

### Async Testing

```ts
import { expect, test } from "vitest";

test("async/await", async () => {
  const result = await fetchData();
  expect(result).toBeDefined();
});

test("resolves", async () => {
  await expect(Promise.resolve("ok")).resolves.toBe("ok");
});

test("rejects", async () => {
  await expect(Promise.reject(new Error())).rejects.toThrow();
});
```

### Fake Timers

```ts
import { vi, expect, test, beforeEach, afterEach } from "vitest";

beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  vi.useRealTimers();
});

test("advances time", () => {
  const callback = vi.fn();
  setTimeout(callback, 1000);

  vi.advanceTimersByTime(1000);

  expect(callback).toHaveBeenCalled();
});
```

## Jest Migration

Most Jest code works with minimal changes:

```diff
- import { jest } from '@jest/globals'
+ import { vi } from 'vitest'

- jest.fn()
+ vi.fn()

- jest.mock('./module')
+ vi.mock('./module')

- jest.useFakeTimers()
+ vi.useFakeTimers()
```

**Key differences:**

- Use `vi` instead of `jest`
- Globals not enabled by default (add `globals: true`)
- `vi.mock` is hoisted (use `vi.doMock` for non-hoisted)
- No `jest.requireActual` (use `vi.importActual`)

## Environment Selection

```ts
// vitest.config.ts
{
  test: {
    environment: 'jsdom', // or 'happy-dom', 'node', 'edge-runtime'
  }
}

// Per-file (docblock at top)
/** @vitest-environment jsdom */
```

## TypeScript

```json
// tsconfig.json
{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}
```

## References

See `references/` directory for detailed documentation on:

- Test API and hooks
- All expect matchers
- Mocking functions and modules
- Configuration options
- CLI commands
- Browser mode testing

## Links

- [Documentation](https://vitest.dev/)
- [API Reference](https://vitest.dev/api/)
- [GitHub](https://github.com/vitest-dev/vitest)
- [VS Code Extension](https://marketplace.visualstudio.com/items?itemName=vitest.explorer)

© itechmeat · MIT · itechmeat/llm-code

Similar skills

All skills for Testing and QA →

vitest by other authors comes first.

vitest Anthony Fu vitest is a Claude Code skill for writing tests with Vitest. It comes into play for mocking, coverage setup, test filters, and fixtures. CX Codex +1 48,600installs vitest jezweb Detects your project type and generates a Vitest config, test utilities, and a sample test. Triggers when you ask to add tests, set up coverage, or migrate from Jest. CX Codex +1 1,800installs vitest pproenca Equips your coding agent with 44 prioritized rules for writing, debugging, and speeding up Vitest suites. Covers async patterns, mocks, and test isolation. CX Codex +1 7,800installs vitest sentimony Configures, runs, and audits Vitest suites in JavaScript and TypeScript projects. It inspects project settings and sets up runners without manual API lookups. CX Codex +1 4,600installs vitest Claude MPM Team Guides the agent in configuring Vitest, writing unit tests, checking TypeScript types, and creating mocks in Vite projects. CX Codex +1 949installs vitest-midscene-e2e web-infra-dev vitest-midscene-e2e connects Vitest with Midscene to build AI-driven UI tests across Web, Android, and iOS using natural language. It scaffolds projects and runs tests without fragile element selectors. CX Codex +1 2,200installs vitest-testing secondsky vitest-testing — a skill for Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, and OpenCode that loads Vitest knowledge into the agent for unit and integration testing in TypeScript and JavaScript projects. CX Codex +1 1,300installs vitest-skill TestMu AI Generates Vitest unit tests for JavaScript and TypeScript projects. Provides patterns for vi mocking and React component testing. CX Codex +1 506installs vitest-testing-patterns curiositech vitest-testing-patterns provides Vitest and React Testing Library conventions for coding agents. Useful for writing component tests, API route checks, and dependency mocks. CX Codex +1 373installs nodejs-javascript-vitest official github The nodejs-javascript-vitest rule guides GitHub Copilot when generating Node.js JavaScript and Vitest tests. It applies to .js, .mjs, and .cjs files. CX Codex +1 ★ 41,430repo stars vitest-unit-testing-cursorrules-prompt-file PatrickJS vitest-unit-testing-cursorrules-prompt-file is a Cursor rule that configures AI to write Vitest unit tests in TypeScript or JavaScript. It runs on project files, mocks dependencies before imports, and groups tests in describe blocks. CX Codex +1 ★ 41,178repo stars

From the same set16

The whole set →
mantine-dev The mantine-dev skill gives coding agents Mantine context for React components, themes, forms, and hooks. Use it when building a Mantine interface or configuring a project around the library. CX Codex +1 290installs social-writer social-writer is a skill for drafting and adapting posts and threads for X, LinkedIn, Threads, Instagram, and Facebook with platform-specific formats. CX Codex +1 270installs base-ui Provides AI agents with composition rules, accessibility patterns, and component structures for unstyled @base-ui/react primitives. CX Codex +1 238installs refine-dev refine-dev — a skill that gives the agent Refine's data provider, resource and hook model, so React admin panels over REST, GraphQL, Supabase or Strapi get built the intended way. CX Codex +1 210installs changelog Keeps CHANGELOG.md on the Keep a Changelog 1.1.0 spec: six change types, version headers, ISO dates, comparison links at the bottom. CX Codex +1 192installs makefile This skill guides an agent through GNU Make files, targets, recipes, checks, and build tasks. Use it when a project needs repeatable command automation. CX Codex +1 181installs commits This skill guides agents in writing Conventional Commits and marking breaking changes. Use it when commit history feeds changelogs or SemVer. CX Codex +1 178installs skill-master skill-master — a skill that helps you write, validate and benchmark Agent Skills against the agentskills.io spec: folder layout, SKILL.md frontmatter, trigger evals. CX Codex +1 161installs

Project sponsors

Companies that keep this analytics open