这是我参与「第五届青训营 」伴学笔记创作活动的第13天,今天进入组件库项目阶段,由我来负责单元测试这一模块。
1.jest单元测试用于在项目上线之前检测bug,以及提升回归效率和保证代码质量
2.本项目采用vue-test-utils来进行单元测试,用覆盖率来作为判断组件库优劣的标准
3.怎样做单元测试?
i,对于基于vue-cli建立的vue项目,我们可以通过引入依赖来快速的体验单元测试
vue add @vue/unit-jest
ii,单元测试基础:
describe("说明",=>{
//用于放测试用例
})
it("描述",() =>{ //用于写断言(对结果的预期) })
iii,尝试运行第一个单元测试用例
describe('测试', () => {
it('测试用例', () => {
// 演示一下,断言字符串'hello'内容是'hello',当然我这么写,结果肯定是true的。
// epect后面的字符串以后会变成真正的页面内容。
expect('hello').toContain('hello')
})
})
iv,对单组件进行单元测试 组件代码:
// counter.vue
<template>
<div>
<span class="count">{{ count }}</span>
<button @click="increment">Increment</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}
</script>
<style>
</style>
单元测试代码:
import { mount } from '@vue/test-utils'
import Counter from '@/components/counter'
describe('测试counter组件', () => {
// 现在挂载组件,你便得到了这个包裹器
const wrapper = mount(Counter)
it('测试是否渲染了<span class="count">0</span>', () => {
expect(wrapper.html()).toContain('<span class="count">0</span>')
})
// 也便于检查已存在的元素
it('测试是否存在一个按钮', () => {
expect(wrapper.find('button').exists()).toBe(true)
})
// 模拟用户交互
it('单击按钮将增加计数', () => {
// 测试组件中count的初始值是0
expect(wrapper.vm.count).toBe(0)
const button = wrapper.find('button')
// 触发按钮点击事件
button.trigger('click')
// 点击累加按钮后 count的值应该变为1
expect(wrapper.vm.count).toBe(1)
})
// 页面dom解构发生变化以后需要等页面更新后才能拿到内容。
it('单击按钮将增加计数文本', async () => {
// 此处count已经不是0了,上面已经点击了一次,此时变为1
expect(wrapper.text()).toContain('1')
const button = wrapper.find('button')
await button.trigger('click')
expect(wrapper.text()).toContain('2')
})
// 断言触发方法
it('断言触发increment方法后的结果', async () => {
expect(wrapper.text()).toContain('2')
wrapper.vm.increment()
// 触发事件后断言页面信息
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('3')
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('3')
})
// 断言触发的事件
it('断言触发事件后的结果', async () => {
wrapper.vm.$emit('foo')
// 断言事件已经被触发
expect(wrapper.emitted().foo). toBeTruthy()
})
// 组件不会自动注销,我们需要手动注销
// wrapper.destroy()
})
最后我们通过覆盖率来体验本次测试的优劣 %stmts是语句覆盖率(statement coverage):是不是每个语句都执行了? %Branch分支覆盖率(branch coverage):是不是每个if代码块都执行了? %Funcs函数覆盖率(function coverage):是不是每个函数都调用了? %Lines行覆盖率(line coverage):是不是每一行都执行了?