这篇文章有三部分,阅读完大概需要 10 分钟(代码块较多,建议使用电脑浏览)
一: 搭建基于 jest 的 vue 单元测试环境
二: 使用 vue-test-util 提高测试编码效率
三: 复杂场景下的测试(模块,异步,rxjs)
第一部分: 搭建基于 jest 的 vue 单元测试环境
因为 jest 包含了 karma + mocha + chai + sinon 的所有常用功能,零配置开箱即用,所以这个教程只讲解 jest。
1.安装依赖
npm install jest vue-jest babel-jest @vue/test-utils -D
2.编写 jest 配置文件
// ./test/unit/jest.conf.jsconst path = require('path');
module.exports = {
rootDir: path.resolve(__dirname, '../../'), // 类似 webpack.context moduleFileExtensions: [ // 类似 webpack.resolve.extensions 'js',
'json',
'vue',
],
moduleNameMapper: {
'^@/(.*)$': '/src/$1', // 类似 webpack.resolve.alias },
transform: { // 类似 webpack.module.rules '^.+\\.js$': '/node_modules/babel-jest',
'.*\\.(vue)$': '/node_modules/vue-jest',
},
setupFiles: ['/test/unit/setup'], // 类似 webpack.entry coverageDirectory: '/test/unit/coverage', // 类似 webpack.output collectCoverageFrom: [ // 类似 webpack 的 rule.include 'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**',
],
};
3.编写启动文件 setup.js
// ./test/unit/setup.jsimport Vue from 'vue';
Vue.config.productionTip = false;
4.加入启动 jest 的 npm script
"scripts": {
"unit": "jest --config test/unit/jest.conf.js --coverage",
},
5.编写第一个测试文件
有一个组件
// ./src/components/hello-world/hello-world.vue
{ { msg }}
export default {
name: 'HelloWorld',
data() {
return {
msg: 'Hello Jest',
};
},
};
对该组件进行测试
// ./src/components/hello-world/hello-world.spec.js
import { shallowMount } from '@vue/test-utils&