用 vue create 创建项目的时候选手动配置,然后选择 jest,生成的项目中就会有一个 jest 的配置文件 jest.config.js 和一个对 HelloWorld.vue 组件的单测示例 tests/unit/example.spec.js。用 Cli 创建的项目的时候,单元测试的准备工作脚手架已经帮你做好了,你直接运行 npm run test:unit 就能把单测示例跑起来。
jest.config.js
首先,我们来看一下 jest 配置文件,默认生成的配置文件只有 preset 属性,另外几个属性我们可以了解一下:
module.exports = {
preset: '@vue/cli-plugin-unit-jest',
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
// 相当于loader
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: ['/node_modules/'],
// 相当于alias
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
// 生成快照
snapshotSerializers: ['jest-serializer-vue'],
// 单元测试文件路径
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)',
],
testURL: 'http://localhost/',
};
example.spec.js
我们再来看一下 CLI 自动生成的单测示例:
import { shallowMount, mount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message';
const wrapper = shallowMount(HelloWorld, {
propsData: { msg },
});
// 断言
expect(wrapper.text()).toMatch(msg);
});
});
- Vue Test Utils 是 Vue.js 官方的单元测试实用工具库,更多语法
- describe: 定义一个测试集
- it: 每个 it 包含单元测试的最小集
- shallowMount:浅渲染,只渲染 HelloWorld 组件,里面的子组件不渲染
- mount: 正常的渲染,子组件也会渲染
- npm run test -- --watchAll, 加了 watchAll 参数,单元测试代码保存的时候会自动运行
再来个示例
Counter.vue
<template>
<div>
<span>count: {
{ count }}</span>
<button @click="handleClick">count++</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
handleClick() {
this.count++;
this.$emit('change', this.count);
},
},
};
</script>
<style></style>
Counter.spec.js
import { mount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';
import sinon from 'sinon';
describe('Counter.vue', () => {
const change = sinon.spy();
const wrapper = mount(Counter, {
listeners: {
change,
},
});
it('renders counter html', () => {
expect(wrapper.html()).toMatchSnapshot();
});
it('count++', () => {
const button = wrapper.find('button');
button.trigger('click');
expect(wrapper.vm.count).toBe(1);
// 断言change方法被调用了
expect(change.called).toBe(true);
button.trigger('click');
expect(change.callCount).toBe(2);
});
});
Sinon
Sinon是用来辅助我们进行前端测试的,在我们的代码需要与其他系统或者函数对接时,它可以模拟这些场景,从而使我们测试的时候不再依赖这些场景。
Sinon有主要有三个方法辅助我们进行测试:spy,stub,mock。