vitest
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.
What this skill does
# 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 Vite >=v6.0.0, Node >=v20.0.0.
## 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)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.