公司安排的培训,要我们写一个表格组件,加上单元测试,覆盖率达到百分百,代码我写完了,但是单元测试之前重来没写过,不想占用周末时间去学api,非常非常简单的组件,思聊我把代码发你,事成之后红包奉上
修改现成框架组件5分钟,不用占用周末,立省50
使用一下jest进行单元测试即可
什么样的单元测试?黑盒测试?
看用什么框架,不同框架有它不同的启动过程,有些框架会提供测试样例的,如果没有,就看下你自己的项目是怎样的一个启动过程,启动之后有些不是启动必要的业务需要去掉,之后直接运行测试代码就可以,测试单元离不开assert断言函数,断言全部通过了,也就代表测试单元通过了,没通过就找下原因,主要也就这两点,没什么难的
1.如果是vue组件测试 参考:https://cn.vuejs.org/v2/cookbook/unit-testing-vue-components.html
2.如果是功能测试 可以写一个分页功能测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let add = (a, b) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(a + b)
}, 200)
})
};
let expect = (result) => {
return {
toBe: function (actual) {
if (actual !== result) {
throw new Error("期望值与实际值不等")
}
}
}
};
let test = function (desc, fn) {
try {
fn();
} catch (e) {
console.log(`${desc}没有通过`)
}
}
test('加法测试', async () => {
expect(await add(1, 2)).toBe(4)
})
</script>
</body>
</html>
1.安装依赖
npm install jest vue-jest babel-jest @vue/test-utils -D
2.编写 jest 配置文件
// ./test/unit/jest.conf.js
const path = require('path');
module.exports = {
rootDir: path.resolve(__dirname, '../../'), // 类似 webpack.context
moduleFileExtensions: [ // 类似 webpack.resolve.extensions
'js',
'json',
'vue',
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1', // 类似 webpack.resolve.alias
},
transform: { // 类似 webpack.module.rules
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
},
setupFiles: ['<rootDir>/test/unit/setup'], // 类似 webpack.entry
coverageDirectory: '<rootDir>/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.js
import 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
<template>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg: 'Hello Jest',
};
},
};
</script>
对该组件进行测试
// ./src/components/hello-world/hello-world.spec.js
import { shallowMount } from '@vue/test-utils';
import HelloWorld from './hello-world';
describe('<hello-world/>', () => {
it('should render correct contents', () => {
const wrapper = shallowMount(HelloWorld);
expect(wrapper.find('.hello h1').text())
.toEqual('Welcome to Your Vue.js App');
});
});
6.启动测试
npm run unit
jest 会自动扫描项目目录下所有文件名以 .spec.js/.test.js 结尾的测试文件,并执行测试用例。