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 插件
bash 复制代码
vue add @vue/unit-jest

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

二、检查 package.json 脚本

确保你的 package.json 中有以下脚本:

javascript 复制代码
"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:

javascript 复制代码
// 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. 运行所有测试
bash 复制代码
npm run test:unit

或使用 Jest 命令:

bash 复制代码
npm run test
  1. 查看测试覆盖率
bash 复制代码
npm run test:coverage

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

五、Jest 配置(可选)

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

javascript 复制代码
"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:

javascript 复制代码
// 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,所以解决不掉,有解决办法烦请共享下

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

报错信息

问题定位

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

原因分析

大模型回答如下

解决方案

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

总结

|---------|------------------------|
| 步骤 | 命令 |
| 安装 Jest | vue add @vue/unit-jest |
| 运行测试 | npm run test:unit |
| 查看覆盖率 | npm run test:coverage |
| 编写测试 | tests/unit/*.spec.js |

相关推荐
康小汪6 小时前
AI 写 Vue 总写成同一个味道:给它装 Skills,装的不是知识是边界
前端·vue.js·人工智能·ai编程·最佳实践
智能运维指南6 小时前
研制过程“两张皮“怎么破:研制一体化支撑平台的定位、能力边界与落地前提
java·前端·人工智能·嘉为蓝鲸
白山编程大哥8 小时前
Java 后端如何优雅地把 List 集合返回给前端
java·前端·list
Flynt9 小时前
我把热榜那篇"禁用 axios"逐条实测了一遍:结论大体对,坑在它没讲的地方
前端·javascript·axios
Csvn9 小时前
bundle优化
前端
北冥有鱼10 小时前
发版后动态路由点击报 `Failed to fetch dynamically imported module`」问题上的完整排查与修复过程
前端·vue.js
静默回滚10 小时前
视频压到 25 MB 以内,码率要算、音轨要扣、余量要留
前端
用户372037492601810 小时前
把 10MB 中文语义模型塞进浏览器:STSB 做到教师模型的 93%,但线上 top1 只有 42%
前端
光锥智能10 小时前
海康机器人举行2026移动机器人新品发布会:箱式存拣升级,「明智」系列发布
java·前端·机器人
计算机魔术师10 小时前
Anthropic 上市文件最吓人的一幕,不是亏损 807 亿
前端