在 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(不然會在調用此方法時報錯報錯)
總結
步驟 | ?命令 |
安裝 Jest | vue add @vue/unit-jest |
運行測試? | npm run test:unit |
查看覆蓋率? | npm run test:coverage |
編寫測試? | tests/unit/*.spec.js |