一、环境准备
Node.js: 版本 ≥ 14.18
包管理工具: npm / yarn / pnpm
项目类型: 支持 Vite、React、Vue、Svelte 等现代前端框架
二、快速接入步骤
- 安装依赖
# 核心包安装
npm install vitest -D
# 可选插件(按需安装)
npm install @testing-library/vue @testing-library/react jsdom happy-dom @vitest/coverage-c8 -D
- 配置文件
创建 vitest.config.ts (与 Vite 配置共享):
- 配置文件
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()], // 沿用 Vite 插件
test: {
globals: true, // 启用全局 API
environment: 'jsdom', // 浏览器环境模拟
coverage: {
provider: 'c8', // 覆盖率工具
reporter: ['text', 'html']
}
}
})
- 配置脚本
在 package.json 中添加:
- 配置脚本
{
"scripts": {
"test": "vitest",
"test:watch": "vitest watch",
"test:coverage": "vitest run --coverage"
}
}
三、编写测试用例
*1. 工具函数测试
创建 src/utils/math.test.ts:
import { describe, expect, it } from 'vitest'
import { sum } from './math'
describe('数学工具函数测试', () => {
it('正确计算两数之和', () => {
expect(sum(1, 2)).toBe(3)
})
it('处理浮点数计算', () => {
expect(sum(0.1, 0.2)).toBeCloseTo(0.3)
})
})
*2. Vue 组件测试
创建 src/components/Button.test.ts:
import { mount } from '@vue/test-utils'
import { describe, expect, it } from 'vitest'
import Button from './Button.vue'
describe('按钮组件', () => {
it('渲染正确文本', () => {
const wrapper = mount(Button, {
props: { label: '提交' }
})
expect(wrapper.text()).toContain('提交')
})
it('触发点击事件', async () => {
const wrapper = mount(Button)
await wrapper.trigger('click')
expect(wrapper.emitted()).toHaveProperty('click')
})
})
*3. 异步逻辑测试
import { describe, expect, it } from 'vitest'
describe('API 请求测试', () => {
it('成功获取用户数据', async () => {
const res = await fetch('/api/user/1')
const data = await res.json()
expect(data).toHaveProperty('id', 1)
})
it('模拟网络错误', async () => {
// 使用 vi.mock 模拟请求
const mockFetch = vi.fn().mockRejectedValue(new Error('Network Error'))
vi.stubGlobal('fetch', mockFetch)
await expect(fetch('/api')).rejects.toThrow('Network Error')
})
})
四、运行测试
*1. 执行所有测试
npm test
*2. 监听模式开发
npm run test:watch
*3. 生成覆盖率报告
npm run test:coverage
# 结果将生成在 /coverage 目录
五、高级配置
*1. 测试环境选择
// vitest.config.ts
test: {
environment: 'happy-dom', // 可选 'jsdom'(默认)/ 'happy-dom'
}
*2. 别名解析
// 自动继承 vite.config.ts 中的别名配置
import { resolve } from 'path'
export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, 'src')
}
}
})
*3. 全局变量注入
test: {
setupFiles: ['./tests/setup.ts'], // 全局测试初始化文件
}