舒適提示:vue-cli3版本已經自帶了jest的單元測試環境。css
開始搭建vue
安裝依賴包node
npm install babel-plugin-transform-vue-jsx jest jest-serializer-vue vue-test-utils babel-jest vue-jest
建立測試目錄(通常習慣放在項目的根目錄)webpack
mkdir test/unit cd test/unit
建立配置文件git
爲何要模擬加載部分靜態文件呢?github
由於jest單元測試無需真實加載靜態資源與解析css樣式,jest主要工做是業務邏輯的執行與數據的比對。web
const path = require('path'); module.exports = { verbose: true, testURL: 'http://localhost/', rootDir: path.resolve(__dirname, '../../'), moduleFileExtensions: [ 'js', 'json', 'vue' ], moduleNameMapper: { '^@\/(.*?\.?(js|vue)?|)$': '<rootDir>/src/$1', # @路徑轉換,例如:@/views/shop/info.vue -> rootDir/src/shop/info.vue '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/test/unit/__mocks__/fileMock.js', # 模擬加載靜態文件 '\\.(css|less)$': 'identity-obj-proxy' # 模擬加載樣式文件 }, testMatch: [ '<rootDir>/test/unit/**/*.spec.js' ], transform: { '^.+\\.js$': '<rootDir>/node_modules/babel-jest', '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest' }, testPathIgnorePatterns: [ '<rootDir>/test/e2e' ], setupFiles: ['<rootDir>/test/unit/setup'], snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'], coverageDirectory: '<rootDir>/test/unit/coverage', collectCoverageFrom: [ 'src/views/**/*.(js|vue)', '!src/main.js', '!src/router/index.js', '!**/node_modules/**' ] };
建立腳本命令vue-cli
# package.json 添加如下運行命令 "scripts": { ... "unit": "jest --config test/unit/jest.conf.js --coverage", },
運行npm
npm run unit 報錯:Plugin/Preset files are not allowed to export objects,webpack
該問題由:babel-jest@24.xxx的版本與babel@6.xx的版本不匹配形成的。
解決方法:咱們把babel-jest@24.xx版本降爲21.0.1就能夠了
npm uninstall babel-jest
npm install babel-jest@21.0.1
修改完畢後再次運行
npm run unit
報錯:error:Duplicate declaration "h" # h函數聲明重複
該問題由:.babelrc重複使用了babel-plugin-transform-vue-jsx 形成的
{ "presets": [ "stage-3", ["env", { "modules": false, "targets": { "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] } }], ], "plugins": ["transform-vue-jsx","syntax-jsx"], # 保留這裏的transform-vue-jsx "env": { "test": { "presets": ["env", "stage-3"], "plugins": ["transform-vue-jsx","transform-es2015-modules-commonjs", "dynamic-import-node"] # 刪除這裏的transform-vue-jsx } } }
修改完畢後再次運行
npm run unit
報錯:error:Duplicate declaration "h" # h函數聲明重複
這是babel-plugin-transform-vue-jsx的bug。若是出現這個錯誤建議使用babel-plugin-transform-vue-jsx@3.3.0版本查看詳情
npm uninstall babel-plugin-transform-vue-jsx
npm install babel-plugin-transform-vue-jsx@3.3.0
報錯:Cannot read property 'nodeName' of undefined
這是通常是UI框架組件庫的版本過低,一些組件不支持node環境運行。
簡單粗暴的解決方法:
npm update 更新依賴
修改完畢後再次運行
npm run unit # 完美
目錄結構:json
測試用例:
# seckillActivity.spec.js import {mount} from 'vue-test-utils'; # API文檔 let test = () => { return true; }; describe('測試', () => { it('驗證測試', () => { expect(test()).toBe(true); }); }) ;
靜態文件加載