Vitest 单测使用

发布时间:2026/7/23 5:38:52
Vitest 单测使用 在 Vue 3 Vite 生态中Vitest 是绝对的首选因为它与 Vite 共享配置速度极快且 API 与 Jest 高度兼容。下面是 Vitest 的完整接入指南涵盖了从「环境配置」到「实战测试含 Vue 组件测试」的全流程。一、 核心配置步骤1. 安装核心依赖除了测试框架本身还需要安装 Vue 组件测试工具和 JSDOM提供浏览器环境pnpmadd-Dvitest vue/test-utils jsdom2. 配置vite.config.ts在现有的 Vite 配置中追加test字段// vite.config.tsimport{defineConfig}fromviteimportvuefromvitejs/plugin-vueexportdefaultdefineConfig({plugins:[vue()],test:{environment:jsdom,// 模拟浏览器 DOM 环境globals:true,// 全局注入 describe, it, expect 等无需手动 import// 自动清理 mock 状态避免测试用例间相互污染clearMocks:true,},})3. 补充 TS 类型提示在tsconfig.app.json中加入vitest/globals让编辑器认识describe、expect{compilerOptions:{types:[vitest/globals]}}4. 添加测试脚本在package.json中配置运行命令{scripts:{test:vitest,test:run:vitest run}}二、 完整实战示例示例 1测试普通工具函数纯逻辑假设我们有一个简单的格式化函数// src/utils/format.tsexportfunctionformatPrice(price:number):string{return¥${price.toFixed(2)}}对应的测试文件建议放在同级目录或__tests__目录下// src/utils/__tests__/format.test.tsimport{formatPrice}from../formatdescribe(formatPrice,(){it(应该正确格式化价格,(){expect(formatPrice(100)).toBe(¥100.00)expect(formatPrice(9.9)).toBe(¥9.90)})})示例 2测试 Vue 组件结合 vue/test-utils假设我们有一个简单的按钮组件!-- src/components/BaseButton.vue -- script setup langts const emit defineEmits([click]) /script template button classbase-btn clickemit(click) slot / /button /template组件的测试用例// src/components/__tests__/BaseButton.test.tsimport{mount}fromvue/test-utilsimportBaseButtonfrom../BaseButton.vuedescribe(BaseButton,(){it(应该正确渲染插槽内容,(){constwrappermount(BaseButton,{slots:{default:点击我}})expect(wrapper.text()).toContain(点击我)})it(点击时应该触发 click 事件,async(){constwrappermount(BaseButton)awaitwrapper.trigger(click)expect(wrapper.emitted(click)).toHaveLength(1)})})示例 3测试 Pinia Store结合权限路由场景测试我们之前写的usePermissionStore// src/stores/__tests__/permission.test.tsimport{setActivePinia,createPinia}frompiniaimport{usePermissionStore}from../modules/permissiondescribe(Permission Store,(){beforeEach((){setActivePinia(createPinia())})it(admin 角色应该能看到所有路由,(){conststoreusePermissionStore()constroutesstore.generateRoutes([admin])// 验证 admin 能获取到包含 system 的路由expect(routes.some(rr.path/system)).toBe(true)})it(普通用户应该被过滤掉无权限路由,(){conststoreusePermissionStore()constroutesstore.generateRoutes([user])expect(routes.some(rr.path/system)).toBe(false)})})三、 结合 Husky 的自动化流程为了让测试真正发挥“守住代码质量”的作用我们将测试加入 Git 提交拦截中pnpmadd-Dlint-staged修改package.json{lint-staged:{*.{ts,vue}:[vitest related --run,eslint --fix,prettier --write]}} 亮点vitest related是 Vitest 的神级功能它只会运行与你本次修改的文件有关联的测试而不是全量跑测试这样在git commit时速度会非常快。四、 避坑与最佳实践测试文件命名推荐统一使用xxx.test.ts或xxx.spec.tsVitest 默认会匹配这些后缀。异步测试如果测试涉及接口请求或定时器记得使用async/await或者在it回调中返回 Promise。Mock 外部依赖在测试组件时如果组件内部调用了axios或router使用vi.mock()进行模拟避免测试变成真实的网络请求UI 可视化界面开发时可以直接运行pnpm testVitest 会启动一个 HMR 模式的终端修改代码后测试会自动重跑体验极佳。 完整工程化闭环总结Vue 3 Vite 项目已经具备了企业级的完整骨架基础架构Vite Vue 3 TS Pinia Vue Router工程规范ESLint Prettier Husky lint-staged性能与体验Element Plus 按需引入 动态权限路由质量保障Vitest 单测 自动化关联测试你可以直接基于这套底座开始开发业务了