当前位置: 首页 > news >正文

Vue 2 项目中快速集成 Jest 单元测试(超详细教程)

在 Vue 项目中编写单元测试,是提升代码质量和维护性的关键一步。本文将带你从零开始,在一个 Vue 2 + Vue CLI 项目中集成 Jest 作为单元测试框架,并运行第一个测试用例。

✅ 适用于 Vue 2 项目(如你使用的是 vue-cli-service)

✅ 基于 @vue/cli-plugin-unit-jest 官方插件

✅ 包含完整命令、配置说明和测试示例

一、安装 Jest 及相关依赖
如果你的项目已经使用 Vue CLI 创建,只需添加官方的 Jest 插件即可。

1. 安装 Jest 插件

vue add @vue/unit-jest


⚠️ 注意:这个命令会自动安装 @vue/cli-plugin-unit-jest 和 @vue/test-utils 等必要依赖。

二、检查 package.json 脚本
确保你的 package.json 中有以下脚本:

"scripts": {"test:unit": "vue-cli-service test:unit","test": "jest","test:watch": "jest --watch","test:coverage": "jest --coverage"
}
  • npm run test:unit:使用 Vue CLI 运行测试(推荐)
  • npm run test:直接运行 Jest(适合 CI)
  • --watch:监听文件变化
  • --coverage:生成测试覆盖率报告

三、创建第一个测试文件
假设你有一个组件:src/components/HelloWorld.vue

1. 创建测试文件
在 tests/unit/ 目录下创建 HelloWorld.spec.js:

// tests/unit/HelloWorld.spec.js
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'describe('HelloWorld.vue', () => {it('renders props.msg when passed', () => {const msg = 'Welcome to Jest Testing'const wrapper = shallowMount(HelloWorld, {propsData: { msg }})expect(wrapper.text()).toMatch(msg)})
})

四、运行测试

1. 运行所有测试

npm run test:unit

或使用 Jest 命令:

npm run test

2. 查看测试覆盖率

npm run test:coverage

运行后会在项目根目录生成 coverage/ 文件夹,打开 coverage/lcov-report/index.html 可查看详细报告。

五、Jest 配置(可选)

Jest 的配置默认由 Vue CLI 管理,你也可以在 package.json 中添加 jest 字段进行自定义:

"jest": {"testMatch": ["**/tests/unit/**/*.spec.(js|jsx|ts|tsx)"],"moduleFileExtensions": ["js","json","vue"],"transform": {"^.+\\.js$": "babel-jest",".*\\.(vue)$": "vue-jest"},"testEnvironment": "jsdom","setupFiles": ["<rootDir>/tests/setup.js"]
}

创建 setup.js(处理 DOM 操作)
有些组件会操作 document,在测试中可能报错(如 querySelector is null),可创建 tests/setup.js:

// tests/setup.js
if (typeof document !== 'undefined') {if (!document.body) {document.body = document.createElement('body')}
}

并在 jest 配置中引入。

六、常见问题解决

问题解决方案
document is not defined 确保 testEnvironment: "jsdom"
Unexpected token 'export' 检查 babel.config.js 是否正确
Test suite failed to run安装 vue-jest@^3.0.7 和 babel-jest
TypeError: Cannot read property 'classList' of null 在操作 DOM 前加 if (el) 判断

七、推荐最佳实践

  • 测试文件命名:xxx.spec.js 或 xxx.test.js
  • 测试文件位置:src同级创建 tests文件夹 或者在测试的源码同级目录添加
  • 使用 shallowMount:避免渲染子组件
  • mock 接口请求:避免真实网络调用
  • 覆盖核心逻辑:props、events、computed、methods

八、遇到的问题

1. [vue-jest]: Less are not currently compiled by vue-jest

这个报错大模型回答受限于vue2,所以解决不掉,有解决办法烦请共享下

2. TypeError: Cannot read property 'createElement' of null

报错信息

问题定位

耗费大量时间排查之后发现是因为代码中在created()调用了getModelList()这个接口请求的方法导致报错读不到createElement和worker process得问题

原因分析

大模型回答如下

解决方案

mock接口请求并document.querySelector(不然会在调用此方法时报错报错)

总结

步骤 命令
安装 Jestvue add @vue/unit-jest
运行测试 npm run test:unit
查看覆盖率 npm run test:coverage
编写测试 tests/unit/*.spec.js
http://www.dtcms.com/a/339306.html

相关文章:

  • 云计算学习100天-第23天
  • github 上传代码步骤
  • 【Python】新手入门:python模块是什么?python模块有什么作用?什么是python包?
  • Day13_【DataFrame数据组合merge连接】【案例】
  • 嵌入式开发学习———Linux环境下网络编程学习(三)
  • 第5.5节:awk算术运算
  • RabbitMQ:交换机(Exchange)
  • LeetCode-17day:贪心算法
  • 95、23种设计模式之建造者模式(4/23)
  • 大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
  • 抓取手机游戏相关数据
  • 细化的 Spring Boot 和 Spring Framework 版本对应关系
  • c++计算器(简陋版)
  • 【全面推导】策略梯度算法:公式、偏差方差与进化
  • 差分(附带例题题解)
  • 深度学习 --- 基于ResNet50的野外可食用鲜花分类项目代码
  • 基于单片机身体健康监测/身体参数测量/心率血氧血压
  • 接口性能测试工具 - JMeter
  • . keepalived+haproxy
  • Ubuntu22.04安装docker最新教程,包含安装自动脚本
  • 【QT入门到晋级】进程间通信(IPC)-socket(包含详细分析及性能优化)
  • Day08 Go语言学习
  • C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
  • es7.x es的高亮与solr高亮查询的对比对比说明
  • 彻底清理旧版本 Docker 的痕迹
  • pytorch学习笔记-模型训练、利用GPU加速训练(两种方法)、使用模型完成任务
  • 常见的软件图片缩放,算法如何选择?
  • 深入解析Spring MVC运行流程:从请求到响应的完整旅程
  • 完整的训练与测试套路 小土堆pytorch记录
  • PyTorch自动求导