news 2026/9/3 0:27:53

前端——单元测试实践

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
前端——单元测试实践

背景问题:
需要为 Vue3 + Vite 项目编写单元测试。

方案思考:
使用 Vitest 作为测试框架,结合 @vue/test-utils 进行组件测试。

具体实现:
安装测试依赖:

# 安装 Vitest 和 Vue 测试工具npminstall-D vitest @vue/test-utils jsdom happy-dom# 安装断言库(Vitest 默认包含 Chai 断言)npminstall-D @vitest/coverage-v8

Vitest 配置:

// vite.config.jsimport{defineConfig}from'vite'importvuefrom'@vitejs/plugin-vue'exportdefaultdefineConfig({plugins:[vue()],test:{// 启用 Vitest 的 APIglobals:true,// 指定测试环境environment:'jsdom',// 或 'happy-dom'// 包含测试文件的模式include:['tests/**/*.test.{js,ts}'],// 排除文件的模式exclude:['node_modules','dist','.idea','.git','.cache'],// 测试覆盖率配置coverage:{provider:'v8',// 或 'istanbul'reporter:['text','json','html'],reportsDirectory:'./coverage',exclude:['node_modules/**','tests/**','vite.config.js']},// 模拟 DOM 环境setupFiles:['./tests/setup.js']}})

测试工具配置:

// tests/setup.jsimport{expect,afterEach}from'vitest'import{cleanup}from'@testing-library/vue'importmatchersfrom'@vitest/expect'// 扩展 Vitest 的 expectexpect.extend(matchers)// 在每个测试后清理 DOMafterEach(()=>{cleanup()})

组件测试示例:

<!-- components/HelloWorld.vue --> <template> <h1>{{ msg }}</h1> <button @click="count++">count is: {{ count }}</button> <p>Edit <code>components/HelloWorld.vue</code> to test hot module replacement.</p> </template> <script setup> import { ref } from 'vue' defineProps({ msg: String }) const count = ref(0) </script>
// tests/unit/HelloWorld.test.jsimport{describe,it,expect}from'vitest'import{mount}from'@vue/test-utils'importHelloWorldfrom'@/components/HelloWorld.vue'describe('HelloWorld',()=>{it('renders properly',()=>{constwrapper=mount(HelloWorld,{props:{msg:'Hello World'}})expect(wrapper.text()).toContain('Hello World')})it('counter starts at 0 and increments',async()=>{constwrapper=mount(HelloWorld)// 初始值expect(wrapper.find('button').text()).toBe('count is: 0')// 点击按钮awaitwrapper.find('button').trigger('click')// 验证值已更新expect(wrapper.find('button').text()).toBe('count is: 1')})it('reactive props work correctly',()=>{constwrapper=mount(HelloWorld,{props:{msg:'Updated Message'}})expect(wrapper.find('h1').text()).toBe('Updated Message')})})

组合式函数测试:

// composables/useCounter.jsimport{ref}from'vue'exportfunctionuseCounter(initialValue=0){constcount=ref(initialValue)constincrement=()=>{count.value++}constdecrement=()=>{count.value--}constreset=()=>{count.value=initialValue}return{count,increment,decrement,reset}}
// tests/unit/composables/useCounter.test.jsimport{describe,it,expect}from'vitest'import{useCounter}from'@/composables/useCounter'describe('useCounter',()=>{it('should initialize with default value 0',()=>{const{count}=useCounter()expect(count.value).toBe(0)})it('should initialize with provided initial value',()=>{const{count}=useCounter(5)expect(count.value).toBe(5)})it('should increment counter',()=>{const{count,increment}=useCounter(0)increment()expect(count.value).toBe(1)})it('should decrement counter',()=>{const{count,decrement}=useCounter(5)decrement()expect(count.value).toBe(4)})it('should reset counter to initial value',()=>{const{count,increment,reset}=useCounter(10)increment()increment()expect(count.value).toBe(12)reset()expect(count.value).toBe(10)})})

API 测试:

// utils/request.js (测试版)importaxiosfrom'axios'// Mock axiosexportconstmockAxios={get:vi.fn(),post:vi.fn(),put:vi.fn(),delete:vi.fn()}exportdefault{get:(url,config)=>mockAxios.get(url,config),post:(url,data,config)=>mockAxios.post(url,data,config),put:(url,data,config)=>mockAxios.put(url,data,config),delete:(url,config)=>mockAxios.delete(url,config)}
// tests/unit/utils/api.test.jsimport{describe,it,expect,beforeEach,vi}from'vitest'import{mockAxios}from'@/utils/request'describe('API utilities',()=>{beforeEach(()=>{// 重置 mockvi.clearAllMocks()})it('should make GET request',async()=>{constmockResponse={data:{id:1,name:'Test'}}mockAxios.get.mockResolvedValue(mockResponse)constresult=awaitmockAxios.get('/api/users/1')expect(mockAxios.get).toHaveBeenCalledWith('/api/users/1')expect(result).toEqual(mockResponse)})it('should handle API errors',async()=>{constmockError=newError('Network Error')mockAxios.get.mockRejectedValue(mockError)awaitexpect(mockAxios.get('/api/users/1')).rejects.toThrow('Network Error')expect(mockAxios.get).toHaveBeenCalledWith('/api/users/1')})})

测试工具函数:

// tests/utils/index.jsimport{mount}from'@vue/test-utils'import{setActivePinia,createPinia}from'pinia'// 创建带 Pinia 的包装器exportfunctioncreateWrapper(Component,options={}){// 创建新的 Pinia 实例constpinia=createPinia()returnmount(Component,{...options,global:{plugins:[pinia],...(options.global||{})}})}// 模拟路由exportfunctionmockRouter(){return{push:vi.fn(),replace:vi.fn(),go:vi.fn(),back:vi.fn(),forward:vi.fn()}}// 模拟响应式数据exportfunctionmockReactive(obj){returnvi.fn(()=>obj)}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/2 23:12:45

YOLOv8性能提升方案:CoordAtt注意力机制集成与优化全流程教程

文章目录 YOLOv8集成CoordAtt注意力机制详细教程 一、本文介绍 二、CoordAtt注意力机制原理深度解析 2.1 传统注意力机制的局限性 2.2 CoordAtt的核心创新 2.3 CoordAtt的工作原理 2.4 CoordAtt与其他注意力机制的对比 三、CoordAtt代码实现详解 3.1 代码结构分析 3.2 关键实现…

作者头像 李华
网站建设 2026/9/2 23:11:32

学霸同款2026 AI论文网站TOP9:本科生毕业论文写作全测评

学霸同款2026 AI论文网站TOP9&#xff1a;本科生毕业论文写作全测评 2026年学术写作工具测评&#xff1a;为本科生量身打造的AI论文网站榜单 随着人工智能技术的不断进步&#xff0c;越来越多的本科生开始借助AI工具辅助毕业论文写作。然而&#xff0c;面对市场上琳琅满目的AI论…

作者头像 李华
网站建设 2026/9/2 23:11:25

2026年阿里巴巴Java高级架构师面试标准手册限时开源!

本来已经在为去大厂工作摩拳擦掌的Java朋友&#xff0c;社招又是需要5年以上的&#xff0c; 今年显得格外艰难&#xff1a; 就业人数高达874万&#xff01;人才竞争加剧&#xff01;疫情让大多数公司的招聘需求缩减&#xff01;对社招来说&#xff0c;人才招聘要求愈来愈高&am…

作者头像 李华
网站建设 2026/9/1 22:58:35

Spring Boot 4 全面拥抱 Jackson 3

Spring Boot 4 将默认 JSON 库从 Jackson 2 切换到了 Jackson 3。如果你是资深 Spring Boot 应用开发者&#xff0c;Jackson 一定不陌生&#xff0c;它是 Spring Boot 中 Java 对象 ↔ JSON 的事实标准。Jackson 在 Spring Boot 4 中依赖结构大致是这样&#xff1a;spring-boot…

作者头像 李华
网站建设 2026/8/30 20:17:59

微信小程序开发框架全解析:成熟项目架构、主流技术与优劣对比

微信小程序凭借“无需下载、即开即用”的特性&#xff0c;成为企业轻量化获客、服务落地的核心载体。对于成熟的小程序项目&#xff0c;绝非简单堆砌页面与接口&#xff0c;而是有着标准化的框架结构和技术选型逻辑。本文将从“成熟项目框架结构”“主流技术框架选型”“各框架…

作者头像 李华
网站建设 2026/9/2 22:18:41

香港科技大学开发WebSeek:让网页数据分析像搭积木一样简单

你有没有这样的经历&#xff1a;想要比较不同网站的商品价格&#xff0c;或者需要从各个新闻网站收集信息来验证一条消息的真实性&#xff0c;结果发现自己在无数个浏览器标签页之间疲于奔命&#xff0c;还要不断地复制粘贴数据到Excel表格中&#xff1f;这种碎片化的工作方式不…

作者头像 李华