1. 创建项目
- 使用vue-cli3创建项目,询问单元测试解决方案时选择Jest。详细步骤
-
项目目录
image.png
2. 使用
- Counter.vue (在
src/components/
下创建该文件)
<template>
<div>
<div>{{ computedCount }}</div>
<button @click="inc">加</button>
<button @click="dec">减</button>
<button @click="reset">重置</button>
</div>
</template>
<script>
export default {
props: {
factor: { type: Number, default: 1 }
},
data() {
return {
count: 0
};
},
methods: {
inc() {
this.count++;
},
dec() {
this.count--;
},
reset() {
this.count = 0;
}
},
computed: {
computedCount: function() {
return this.count * this.factor;
}
}
};
</script>
- Counter.spec.js (在
tests/unit
下创建该文件)
import { mount } from '@vue/test-utils'
import Counter from '@/components/Counter.vue'
describe("Counter.vue", () => {
it("渲染Counter组件", () => {
const wrapper = mount(Counter)
expect(wrapper.element).toMatchSnapshot()
})
it("初始化之为0", () => {
const wrapper = mount(Counter)
expect(wrapper.vm.count).toEqual(0)
})
it("加1", () => {
const wrapper = mount(Counter)
wrapper.vm.inc()
expect(wrapper.vm.count).toEqual(1)
})
it("减1", () => {
const wrapper = mount(Counter)
wrapper.vm.dec()
expect(wrapper.vm.count).toEqual(-1)
})
it("重置", () => {
const wrapper = mount(Counter)
wrapper.vm.reset()
expect(wrapper.vm.count).toEqual(0)
})
it("因数为10加1操作", () => {
const wrapper = mount(Counter, { propsData: { factor: 10 } })
wrapper.vm.inc()
expect(wrapper.vm.computedCount).toEqual(10)
})
})
3. 运行测试
- Run your tests
npm run test
- Lints and fixes files
npm run lint
- Run your unit tests
npm run test:unit
网友评论