舒适提示: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); }); }) ;
静态文件加载