# Vitest — Next Generation Testing Framework Powered by Vite > Vitest is a blazing-fast unit testing framework powered by Vite, with native ESM, TypeScript, and JSX support. Jest-compatible API, instant HMR for tests, and in-source testing make it the go-to test runner for Vite projects. ## Install Save in your project root: ## Quick Use ```bash npm i -D vitest ``` ```json // package.json { "scripts": { "test": "vitest" } } ``` ```ts // sum.test.ts import { expect, test } from "vitest"; import { sum } from "./sum"; test("adds 1 + 2 to equal 3", () => { expect(sum(1, 2)).toBe(3); }); ``` Run: ```bash npm test # watch mode npm test -- --run # single run npm test -- --ui # browser UI ``` ## Intro Vitest is a next-generation testing framework powered by Vite. Jest-compatible API with massive performance gains thanks to Vite ESM-native dev server and Rollup bundling. Default choice for Vite projects (Vue, Svelte, Solid, React+Vite). - **Repo**: https://github.com/vitest-dev/vitest - **Stars**: 16K+ - **Language**: TypeScript - **License**: MIT ## What Vitest Does - **Unit tests** — Jest-compatible `describe/test/expect` - **Watch mode** — instant re-run via Vite HMR - **TypeScript** — native, no ts-jest - **ESM** — native ES modules - **Mocks** — `vi.fn()`, `vi.mock()` matching Jest API - **Snapshots** — inline and file-based - **Coverage** — v8 or istanbul providers - **Browser mode** — run tests in real browser via Playwright - **In-source testing** — tests next to code with `if (import.meta.vitest)` ## Architecture Uses the same `vite.config.ts` as the app. Test files transformed by Vite plugins (same as dev). Workers spin up for parallel test execution. Vite dep pre-bundling caches third-party libs for fast startup. ## Self-Hosting Dev tool. Install as devDependency. CI example: ```yaml - run: npm ci - run: npx vitest run --coverage ``` ## Key Features - Jest-compatible API (easy migration) - Native TS/JSX/ESM - Vite HMR-powered watch - UI mode (browser dashboard) - Browser mode (real browser tests) - In-source testing - Workspace support (monorepos) - Benchmark mode (bench/describe) ## Comparison | Runner | Speed | TS | ESM | Vite | |---|---|---|---|---| | Vitest | Fast | Native | Native | Integrated | | Jest | Slow | ts-jest | Experimental | No | | Mocha | Medium | ts-node | Yes | No | | Bun test | Fastest | Native | Native | No | ## 常见问题 FAQ **Q: 从 Jest 迁移难吗?** A: API 几乎一致。大部分项目只需改 import `jest` → `vi`,替换 `jest.config` 为 `vite.config` 的 `test` 字段。 **Q: 不用 Vite 能用 Vitest 吗?** A: 可以。Vitest 只需 vite.config 的配置字段,不需要 Vite 构建应用。但 Vite 项目收益最大。 **Q: 和 Playwright 冲突吗?** A: 不。Vitest 做单元/组件测试,Playwright 做 E2E。可共存。 ## 来源与致谢 Sources - Docs: https://vitest.dev - GitHub: https://github.com/vitest-dev/vitest - License: MIT --- Source: https://tokrepo.com/en/workflows/267275ed-355f-11f1-9bc6-00163e2b0d79 Author: AI Open Source