第一步:配置页面,以及熟悉jest 的工程文件后缀都是xx.test.js,我们在运行一个jest工程的时候,jest会自动查找运行的后缀为*.test.js的脚本进行单元测试。machers 众多的匹配判断器可以去代码学院前端测试查看内容 第二步:编写TodoList.vue 第三步引入vue/test-utils TodoLis import { shallowMount } from '@vue/test-utils' import TodoList from '../../TodoList' import Header from '../../components/Header' it('TodoLit 初始化时,undoList 应该为空', () => { const wrapper = shallowMount(TodoList) const undoList = wrapper.vm.$data.undoList expect(undoList).toEqual([]) }) it('TodoList 监听到 Header 的 添加 事件时,会增加一个内容', () => { const content = 'daima.net' const wrapper = shallowMount(TodoList) const header = wrapper.find(Header) header.vm.$emit('add', content) const undoList = wrapper.vm.$data.undoList expect(undoList).toEqual([content]) })
Header.vue代码
<template>
<div class='header'>
<div class='header-content'>
TodoList
<input
class='header-input'
data-test='input'
v-model="inputValue"
@keyup.enter="addTodoItem"
placeholder="Add TodoItem"
/>
</div>
</div>
</template>
<script>
export default {
name: 'Header',
data () {
return {
inputValue: ''
}
},
methods: {
addTodoItem () {
if (this.inputValue) {
this.$emit('add', this.inputValue)
this.inputValue = ''
}
}
}
}
</script>
<style scoped lang="stylus">
.header {
line-height: 80px;
background: #3468ff;
}
.header-content {
width: 500px;
margin: 0 auto;
color: #FFF;
font-size: 24px;
}
.header-input {
float: right;
width: 360px;
margin-top: 16px;
line-height: 24px;
outline: none;
color: #333;
text-indent: 10px;
}
</style>
TodoList.vue代码
<template>
<div>
<Header @add="addUndoItem" />
<ul>
<li v-for="item in undoList" :key="item">{{item}}</li>
</ul>
</div>
</template>
<script>
import Header from './components/Header'
export default {
name: 'TodoList',
components: {
Header
},
data () {
return {
undoList: []
}
},
methods: {
addUndoItem (inputValue) {
this.undoList.push(inputValue)
}
}
}
</script>
<style scoped lang="stylus">
</style>