Vitest 安装与配置 #
环境要求 #
在安装 Vitest 之前,请确保你的开发环境满足以下要求:
| 要求 | 版本 | 说明 |
|---|---|---|
| Node.js | >= 18.0 | 推荐 LTS 版本 |
| 包管理器 | npm/pnpm/yarn | 任选其一 |
| Vite | >= 5.0 | 如果使用 Vite 项目 |
检查环境 #
bash
# 检查 Node.js 版本
node -v
# v18.0.0 或更高
# 检查包管理器
npm -v
# 或
pnpm -v
# 或
yarn -v
安装 Vitest #
使用 npm #
bash
# 安装为开发依赖
npm install -D vitest
使用 pnpm #
bash
# 安装为开发依赖
pnpm add -D vitest
使用 yarn #
bash
# 安装为开发依赖
yarn add -D vitest
使用 bun #
bash
# 安装为开发依赖
bun add -D vitest
快速开始 #
1. 创建项目结构 #
text
my-project/
├── src/
│ └── sum.ts
├── test/
│ └── sum.test.ts
├── package.json
└── vite.config.ts
2. 编写源代码 #
typescript
// src/sum.ts
export function sum(a: number, b: number): number {
return a + b
}
3. 编写测试 #
typescript
// test/sum.test.ts
import { describe, it, expect } from 'vitest'
import { sum } from '../src/sum'
describe('sum', () => {
it('should add two numbers', () => {
expect(sum(1, 2)).toBe(3)
})
it('should handle negative numbers', () => {
expect(sum(-1, -2)).toBe(-3)
})
})
4. 添加脚本命令 #
json
// package.json
{
"scripts": {
"test": "vitest",
"test:run": "vitest run",
"test:ui": "vitest --ui",
"test:coverage": "vitest --coverage"
}
}
5. 运行测试 #
bash
# 运行测试(Watch 模式)
npm test
# 单次运行
npm run test:run
# 带 UI 界面
npm run test:ui
# 生成覆盖率报告
npm run test:coverage
配置文件 #
vite.config.ts #
Vitest 会自动读取 vite.config.ts 配置文件:
typescript
// vite.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
// Vitest 配置
},
})
vitest.config.ts #
也可以使用独立的配置文件:
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
// Vitest 配置
},
})
配置优先级 #
text
1. vitest.config.ts(优先级最高)
2. vite.config.ts
3. package.json 中的 vitest 字段
常用配置项 #
测试环境配置 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
// 测试环境
environment: 'node', // 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime'
// 全局变量
globals: true,
// 测试文件匹配模式
include: ['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
// 排除文件
exclude: ['node_modules', 'dist', '.idea', '.git', '.cache'],
// 测试超时时间(毫秒)
testTimeout: 10000,
// 钩子超时时间(毫秒)
hookTimeout: 10000,
},
})
路径别名配置 #
typescript
// vite.config.ts
import { defineConfig } from 'vitest/config'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils'),
},
},
test: {
// Vitest 自动继承上面的 alias 配置
},
})
测试环境选择 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
// Node.js 环境(默认)
environment: 'node',
// 浏览器环境(需要安装 jsdom)
// environment: 'jsdom',
// 更快的浏览器环境(需要安装 happy-dom)
// environment: 'happy-dom',
},
})
安装测试环境依赖 #
bash
# jsdom
npm install -D jsdom
# happy-dom(更快)
npm install -D happy-dom
不同项目类型配置 #
Vite + Vue 项目 #
bash
# 安装依赖
npm install -D vitest @vue/test-utils jsdom
typescript
// vite.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
globals: true,
},
})
Vite + React 项目 #
bash
# 安装依赖
npm install -D vitest @testing-library/react jsdom
typescript
// vite.config.ts
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './test/setup.ts',
},
})
typescript
// test/setup.ts
import '@testing-library/jest-dom'
Vite + Svelte 项目 #
bash
# 安装依赖
npm install -D vitest @testing-library/svelte jsdom
typescript
// vite.config.ts
import { defineConfig } from 'vitest/config'
import { svelte } from '@sveltejs/vite-plugin-svelte'
export default defineConfig({
plugins: [svelte()],
test: {
environment: 'jsdom',
globals: true,
},
})
非 Vite 项目 #
Vitest 也可以在非 Vite 项目中使用:
bash
# 安装 Vitest
npm install -D vitest
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
globals: true,
environment: 'node',
},
})
全局变量配置 #
启用全局变量 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
globals: true,
},
})
启用后,可以直接使用全局变量,无需导入:
typescript
// 无需导入
// import { describe, it, expect } from 'vitest'
describe('my suite', () => {
it('my test', () => {
expect(1 + 1).toBe(2)
})
})
TypeScript 类型支持 #
json
// tsconfig.json
{
"compilerOptions": {
"types": ["vitest/globals"]
}
}
Setup 文件配置 #
配置 Setup 文件 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
setupFiles: ['./test/setup.ts'],
},
})
Setup 文件示例 #
typescript
// test/setup.ts
import { beforeAll, afterAll, beforeEach, afterEach } from 'vitest'
// 全局 setup
beforeAll(() => {
console.log('Tests starting...')
})
// 全局 teardown
afterAll(() => {
console.log('Tests finished.')
})
// 每个 test 前执行
beforeEach(() => {
// 重置测试状态
})
// 每个 test 后执行
afterEach(() => {
// 清理测试数据
})
扩展断言匹配器 #
typescript
// test/setup.ts
import { expect } from 'vitest'
// 自定义匹配器
expect.extend({
toBeWithinRange(received: number, floor: number, ceiling: number) {
const pass = received >= floor && received <= ceiling
return {
pass,
message: () =>
`expected ${received} ${pass ? 'not to' : 'to'} be within range ${floor} - ${ceiling}`,
}
},
})
// 使用
// expect(100).toBeWithinRange(90, 110)
覆盖率配置 #
安装覆盖率提供者 #
bash
# v8 提供者(推荐)
npm install -D @vitest/coverage-v8
# 或 istanbul 提供者
npm install -D @vitest/coverage-istanbul
配置覆盖率 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
coverage: {
provider: 'v8', // 或 'istanbul'
reporter: ['text', 'json', 'html'],
reportsDirectory: './coverage',
include: ['src/**/*.ts'],
exclude: [
'node_modules/',
'test/',
'**/*.d.ts',
'**/*.config.*',
],
all: true,
lines: 80,
functions: 80,
branches: 80,
statements: 80,
},
},
})
命令行选项 #
常用命令 #
bash
# 启动 Watch 模式
vitest
# 单次运行所有测试
vitest run
# 运行特定文件
vitest run test/sum.test.ts
# 运行匹配模式的测试
vitest run -t "sum"
# 启动 UI 界面
vitest --ui
# 生成覆盖率
vitest --coverage
# 只运行变更的测试
vitest --changed
# 并行运行
vitest --threads
# 串行运行
vitest --no-threads
命令行参数 #
| 参数 | 说明 |
|---|---|
--watch |
启动 Watch 模式 |
--run |
单次运行 |
--ui |
启动 UI 界面 |
--coverage |
生成覆盖率报告 |
--reporter |
指定报告器 |
--threads |
启用多线程 |
--no-threads |
禁用多线程 |
--bail |
遇到失败时停止 |
--changed |
只运行变更的测试 |
--passWithNoTests |
无测试时也通过 |
配置示例 #
完整配置示例 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
// 测试环境
environment: 'jsdom',
// 全局变量
globals: true,
// Setup 文件
setupFiles: ['./test/setup.ts'],
// 测试文件匹配
include: ['test/**/*.test.ts', 'src/**/*.spec.ts'],
exclude: ['node_modules', 'dist'],
// 超时设置
testTimeout: 10000,
hookTimeout: 10000,
// 并行设置
threads: true,
maxThreads: 4,
minThreads: 1,
// 覆盖率
coverage: {
provider: 'v8',
reporter: ['text', 'html'],
include: ['src/**/*.ts'],
exclude: ['src/**/*.d.ts'],
},
// 报告器
reporters: ['default', 'html'],
// 钩子
onConsoleLog: (log) => {
// 过滤控制台输出
return !log.includes('ignore this')
},
},
})
多环境配置 #
typescript
// vitest.config.ts
import { defineConfig } from 'vitest'
export default defineConfig({
test: {
// 默认配置
environment: 'node',
include: ['test/**/*.test.ts'],
// 工作区配置
workspace: [
{
// Node.js 测试
test: {
name: 'node',
environment: 'node',
include: ['test/node/**/*.test.ts'],
},
},
{
// 浏览器测试
test: {
name: 'browser',
environment: 'jsdom',
include: ['test/browser/**/*.test.ts'],
},
},
],
},
})
IDE 集成 #
VS Code 插件 #
安装 Vitest 插件获得更好的开发体验:
- 打开 VS Code 扩展面板
- 搜索 “Vitest”
- 安装官方 Vitest 插件
VS Code settings.json #
json
// .vscode/settings.json
{
"vitest.enable": true,
"vitest.commandLine": "npm test --",
"vitest.debuggerPort": 9229
}
WebStorm / IntelliJ IDEA #
WebStorm 内置支持 Vitest:
- 打开设置 -> Languages & Frameworks -> JavaScript -> Testing
- 选择 Vitest
- 配置测试运行器
故障排除 #
常见问题 #
1. 找不到模块 #
typescript
// 确保路径别名正确配置
// vite.config.ts
import { defineConfig } from 'vitest/config'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
})
2. TypeScript 类型错误 #
json
// tsconfig.json
{
"compilerOptions": {
"types": ["vitest/globals"],
"moduleResolution": "bundler"
}
}
3. 测试超时 #
typescript
// 增加超时时间
// vitest.config.ts
export default defineConfig({
test: {
testTimeout: 30000,
},
})
// 或在单个测试中设置
it('long running test', () => {
// ...
}, 30000)
4. 内存不足 #
bash
# 增加 Node.js 内存限制
NODE_OPTIONS="--max-old-space-size=4096" vitest
下一步 #
现在你已经完成了 Vitest 的安装和配置,接下来学习 编写测试 开始编写你的第一个测试!
最后更新:2026-03-28