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 单测 自动化关联测试你可以直接基于这套底座开始开发业务了

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/9/23 4:54:42
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/23 8:01:55
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/9/23 8:02:11
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/9/23 8:01:38
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/23 8:01:21
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/24 11:09:24

日新闻

周新闻