1、假设你已经有一个vue-cli3的项目,先安装Jest 所需要的依赖:
cnpm i @vue/test-utils babel-jest jest jest-serializer-vue jest-transform-stub vue-jest -D
2、修改 babel.config.js 文件,主要解决使用Babel的问题 ,参考:https://jestjs.io/docs/en/getting-started#using-babel
module.exports = {
presets: [
['@vue/app', {
useBuiltIns: 'entry',
}]
],
// 新增的配置,
"env": {
"test": {
"presets": ["env"]
}
}
}
3、增加 jest.conf.js 配置文件
const path = require('path');
module.exports = {
verbose: true,
testURL: 'http://localhost/',
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
moduleNameMapper: {
// eslint-disable-next-line no-useless-escape
'^@\/(.*?\.?(js|vue)?|)$': '<rootDir>/src/$1', // @路径转换,例如:@/components/Main.vue -> rootDir/src/components/Main.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|scss|sass)$': '<rootDir>/test/unit/__mocks__/styleMock.js' // 模拟加载样式文件
},
testMatch: [ //匹配测试用例的文件
'<rootDir>/test/unit/specs/*.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/components/**/*.(js|vue)',
'src/components/tabs-cards/*.(vue)',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**'
]
}
4、在package.json 的 scripts 里添加测试命令
"unit": "jest --config test/unit/jest.conf.js --coverage"
另外,如果遇到如下错误,主要是因为 babel-jest不支持babel7,解决方案是安装 babel-core@^7.0.0-bridge.0插件
Failed to collect coverage from *****
ERROR: Plugin 0 specified in "******" provided an invalid property of "default" (While processing preset: "****8/node_modules/@vue/babel-preset-app/index.js")
STACK: Error: Plugin 0 specified in "*****/node_modules/@vue/babel-preset-app/index.js" provided an invalid property of "default" (While processing preset: "*****/node_modules/@vue/babel-preset-app/index.js")
cnpm install --save-dev babel-core@^7.0.0-bridge.0
参考资料:
https://segmentfault.com/a/1190000008628067
https://github.com/ElemeFE/element/blob/dev/test/unit/specs/button.spec.js
https://deltice.github.io/jest/docs/zh-Hans/getting-started.html#content
网友评论