Vue2 应用测试学习 02 - TDD 案例(案例介绍和创建、编写测试用例)

本文主要是介绍Vue2 应用测试学习 02 - TDD 案例(案例介绍和创建、编写测试用例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

案例介绍

下面使用 TodoMVC 提供的开源 Todos List 任务清单示例,学习使用 TDD 方式开发 Vue 应用。

案例演示效果:Vue.js • TodoMVC

基本功能包括:

  • 输入任务内容,点击回车,任务被添加到列表中
  • 切换单个或所有任务完成状态
  • 删除任务
  • 显示未完成任务数量
  • 删除所有已完成的任务
  • 数据筛选
  • 修改任务内容(回车保存修改,ESC取消编辑,内容为空则删除任务)

案例创建

创建组件文件 src\components\TodoApp\index.vue,从 Github 仓库的 index.html 中拷贝页面内容:

<!-- src\components\TodoApp\index.vue -->
<template><section class="todoapp"><header class="header"><h1>todos</h1><input class="new-todo" placeholder="What needs to be done?" autofocus /></header><section class="main"><input id="toggle-all" class="toggle-all" type="checkbox" /><label for="toggle-all">Mark all as complete</label><ul class="todo-list"><!-- These are here just to show the structure of the list items --><!-- List items should get the class `editing` when editing and `completed` when marked as completed --><li class="completed"><div class="view"><input class="toggle" type="checkbox" checked /><label>Taste JavaScript</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template" /></li><li><div class="view"><input class="toggle" type="checkbox" /><label>Buy a unicorn</label><button class="destroy"></button></div><input class="edit" value="Rule the web" /></li></ul></section><!-- This footer should be hidden by default and shown when there are todos --><footer class="footer"><!-- This should be `0 items left` by default --><span class="todo-count"><strong>0</strong> item left</span><!-- Remove this if you don't implement routing --><ul class="filters"><li><a class="selected" href="#/">All</a></li><li><a href="#/active">Active</a></li><li><a href="#/completed">Completed</a></li></ul><!-- Hidden if no completed items are left ↓ --><button class="clear-completed">Clear completed</button></footer></section>
</template>

在 App.vue 中引入组件:

<template><div id="app"><TodoApp /></div>
</template><script>
import TodoApp from '@/components/TodoApp'export default {name: 'App',components: { TodoApp }
}
</script>

从 package.json 中找到样式依赖 todomvc-app-css,复制 index.css 到项目中:新建 src\style\index.css 文件。

main.js 中引入:

// src\main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './style/index.css'Vue.config.productionTip = falsenew Vue({router,store,render: h => h(App)
}).$mount('#app')

npm run serve启动应用,查看效果 http://localhost:8080/

划分组件单元

下面按照 TDD(测试驱动开发) 方式开发应用,首先将功能按照组件拆分。

TodoHeader

<!-- src\components\TodoApp\TodoHeader.vue -->
<template><header class="header"><h1>todos</h1><input class="new-todo" placeholder="What needs to be done?" autofocus /></header>
</template><script>
export default {name: 'TodoHeader'
}
</script>

TodoFooter

<!-- src\components\TodoApp\TodoFooter.vue -->
<template><!-- This footer should be hidden by default and shown when there are todos --><footer class="footer"><!-- This should be `0 items left` by default --><span class="todo-count"><strong>0</strong> item left</span><!-- Remove this if you don't implement routing --><ul class="filters"><li><a class="selected" href="#/">All</a></li><li><a href="#/active">Active</a></li><li><a href="#/completed">Completed</a></li></ul><!-- Hidden if no completed items are left ↓ --><button class="clear-completed">Clear completed</button></footer>
</template><script>
export default {name: 'TodoFooter'
}
</script>

TodoItem

<!-- src\components\TodoApp\TodoItem.vue -->
<template><li><!-- <li class="completed"> --><div class="view"><input class="toggle" type="checkbox" /><!-- <input class="toggle" type="checkbox" checked /> --><label>Taste JavaScript</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template" /></li>
</template><script>
export default {name: 'TodoItem'
}
</script>

TodoApp

<!-- src\components\TodoApp\index.vue -->
<template><section class="todoapp"><TodoHeader /><section class="main"><input id="toggle-all" class="toggle-all" type="checkbox" /><label for="toggle-all">Mark all as complete</label><ul class="todo-list"><!-- These are here just to show the structure of the list items --><!-- List items should get the class `editing` when editing and `completed` when marked as completed --><TodoItem /><TodoItem /></ul></section><!-- This footer should be hidden by default and shown when there are todos --><TodoFooter /></section>
</template><script>
import TodoHeader from './TodoHeader'
import TodoFooter from './TodoFooter'
import TodoItem from './TodoItem'export default {name: 'TodoApp',components: { TodoHeader, TodoFooter, TodoItem }
}
</script>

TodoHeader 组件

TodoHeader 组件的功能是在文本框中输入内容,按下回车应该发送一个自定义事件,自定义事件传递一个字符串,并在最后清空文本框。

编写测试用例

首先编写测试用例,文件位置推荐就近原则。

在 TodoApp 组件文件夹下创建测试用例文件夹,文件夹名为 __tests__,Vue Test Utils 会查找这这个目录下的文件,作为测试文件执行。

测试文件最好以测试的组件名命名:TodoHeader.js

// src\components\TodoApp\__tests__\TodoHeader.js
import { shallowMount } from '@vue/test-utils'
import TodoHeader from '@/components/TodoApp/TodoHeader'describe('TodoHeader.vue', () => {test('New todo', async () => {const wrapper = shallowMount(TodoHeader)// 可以给元素添加一个专门用于测试的 `data-testid`,方便测试的时候获取这个元素const input = wrapper.findComponent('input[data-testid="new-todo"]')const text = 'play'// 文本框填入内容// 操作视图也建议使用 await 等待一下// 因为它可能会修改 vm 实例的状态,这样更稳妥一些await input.setValue(text)// 等待触发回车事件await input.trigger('keyup.enter')// 断言组件对外发送一个 new-todo 事件expect(wrapper.emitted()['new-todo']).toBeTruthy()// 断言事件发送的参数expect(wrapper.emitted()['new-todo'][0][0]).toBe(text)// 断言文本框已清空expect(input.element.value).toBe('')})
})

使用监视模式运行测试(结果当然是失败):

# 监视并运行全部测试文件
npm run test:unit -- --watch
# or 监视并运行指定测试文件
npm run test:unit -- TodoHeader.js --watch

完善组件功能

接着根据测试用例完善组件功能:

<!-- src\components\TodoApp\TodoHeader.vue -->
<template><header class="header"><h1>todos</h1><inputclass="new-todo"placeholder="What needs to be done?"autofocusdata-testid="new-todo"@keyup.enter="handleNewTodo"/></header>
</template><script>
export default {name: 'TodoHeader',methods: {handleNewTodo (e) {const value = e.target.value.trim()if (!value.length) {return}this.$emit('new-todo', value)e.target.value = ''}}
}
</script>

可以发现,除非调试样式,整个过程完全不需要打开浏览器,就可以完成这个组件的功能开发,并且大多数情况下,开发出来的功能一定是正确的。

在组件开发完成并通过测试后,可以将代码进行 git 提交,这样重新运行测试命令watch 模式下,文件没有变更,就不再会对它进行测试了。

TodoApp 组件

TodoApp 作为父组件应该接收 TodoHeader 发出的自定义事件,然后通过一个函数来处理它: TodoApp 应该管理一个数组,可以向这个数组添加任务项。

编写测试用例

// src\components\TodoApp\__tests__\TodoApp.js
import { shallowMount } from '@vue/test-utils'
import TodoApp from '@/components/TodoApp'
import TodoItem from '@/components/TodoApp/TodoItem'describe('TodoApp.vue', () => {test('New todo', async () => {const wrapper = shallowMount(TodoApp)const text = 'play'// 调用组件的方法,添加任务项wrapper.vm.handleNewTodo(text)// 期望管理的数组中包含刚添加的任务项const todo = wrapper.vm.todos.find(t => t.text === text)expect(todo).toBeTruthy()})test('Todo List', async () => {const wrapper = shallowMount(TodoApp)// 初始化默认数据,并等待视图更新const todos = [{ id: 1, text: 'eat', done: false },{ id: 2, text: 'play', done: true },{ id: 3, text: 'sleep', done: false }]await wrapper.setData({todos})// 期望指定子组件被渲染了3个expect(wrapper.findAllComponents(TodoItem).length).toBe(todos.length)})
})

完善组件功能

<!-- src\components\TodoApp\index.vue -->
<template><section class="todoapp"><TodoHeader @new-todo="handleNewTodo" /><section class="main"><input id="toggle-all" class="toggle-all" type="checkbox" /><label for="toggle-all">Mark all as complete</label><ul class="todo-list"><!-- These are here just to show the structure of the list items --><!-- List items should get the class `editing` when editing and `completed` when marked as completed --><TodoItem v-for="todo in todos" :key="todo.id" /></ul></section><!-- This footer should be hidden by default and shown when there are todos --><TodoFooter /></section>
</template><script>
import TodoHeader from './TodoHeader'
import TodoFooter from './TodoFooter'
import TodoItem from './TodoItem'export default {name: 'TodoApp',components: { TodoHeader, TodoFooter, TodoItem },data () {return {todos: []}},methods: {handleNewTodo (text) {const lastTodo = this.todos[this.todos.length - 1]this.todos.push({id: lastTodo ? lastTodo.id + 1 : 1,text,done: false})}}
}
</script>

TodoItem 组件

内容展示&处理完成状态

编写测试用例

// src\components\TodoApp\__tests__\TodoItem.js
import { shallowMount } from '@vue/test-utils'
import TodoItem from '@/components/TodoApp/TodoItem'describe('TodoItem.vue', () => {// 使用 vscode 注解声明 type 以使用类型提示/** @type {import('@vue/test-utils').Wrapper} */let wrapper = nullbeforeEach(() => {const todo = {id: 1,text: 'play',done: true}wrapper = shallowMount(TodoItem, {propsData: {todo}})})test('text', () => {// 断言文本内容expect(wrapper.findComponent('[data-testid="todo-text"]').text()).toBe(wrapper.vm.todo.text)})test('done', async () => {const done = wrapper.findComponent('[data-testid="todo-done"]')const todoItem = wrapper.findComponent('[data-testid="todo-item"]')// 断言完成状态expect(done.element.checked).toBeTruthy()// 断言 class - classes(获取 DOM 节点的 class 数组)expect(todoItem.classes()).toContain('completed')// 修改复选框状态,并等待视图更新await done.setChecked(false)// 断言 classexpect(todoItem.classes('completed')).toBeFalsy()})
})

TodoApp 组件中向子组件 TodoItem 传入必填 prop,否则测试会报错:

<TodoItem v-for="todo in todos" :key="todo.id" :todo="todo" />

完善组件功能

<!-- src\components\TodoApp\TodoItem.vue -->
<template><li data-testid="todo-item" :class="{completed:todo.done}"><div class="view"><!-- eslint-disable-next-line vue/no-mutating-props --><input v-model="todo.done" data-testid="todo-done" class="toggle" type="checkbox" /><label data-testid="todo-text">{{ todo.text }}</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template" /></li>
</template><script>
export default {name: 'TodoItem',props: {todo: {type: Object,required: true}}
}
</script>

删除任务

TodoItem 点击删除按钮,向父组件发送删除事件,并把任务项的 id 传递给父组件,父组件通过一个方法处理删除操作。

编写测试用例

test('delete todo', async () => {const deleteBtn = wrapper.findComponent('[data-testid="delete"]')await deleteBtn.trigger('click')expect(wrapper.emitted()['delete-todo']).toBeTruthy()expect(wrapper.emitted()['delete-todo'][0][0]).toBe(wrapper.vm.todo.id)
})

完善组件功能

<button data-testid="delete" class="destroy" @click="$emit('delete-todo', todo.id)"></button>

TodoApp 删除操作

编写测试用例

// src\components\TodoApp\__tests__\TodoApp.js
import { shallowMount } from '@vue/test-utils'
import TodoApp from '@/components/TodoApp'
import TodoItem from '@/components/TodoApp/TodoItem'describe('TodoApp.vue', () => {/** @type {import('@vue/test-utils')/Wrapper} */let wrapper = nullbeforeEach(async () => {wrapper = shallowMount(TodoApp)const todos = [{ id: 1, text: 'eat', done: false },{ id: 2, text: 'play', done: true },{ id: 3, text: 'sleep', done: false }]// 初始化默认数据,并等待视图更新await wrapper.setData({todos})})test('New todo', async () => {const text = 'play'// 调用组件的方法,添加任务项wrapper.vm.handleNewTodo(text)// 期望管理的数组中包含刚添加的任务项const todo = wrapper.vm.todos.find(t => t.text === text)expect(todo).toBeTruthy()})test('Todo List', async () => {// 期望指定子组件被渲染了3个expect(wrapper.findAllComponents(TodoItem).length).toBe(wrapper.vm.todos.length)})test('Delete Todo', async () => {// 正向测试 传递一个真实的 idawait wrapper.vm.handleDeleteTodo(1)expect(wrapper.vm.todos.length).toBe(2)expect(wrapper.findAllComponents(TodoItem).length).toBe(2)})test('Delete Todo', async () => {// 反向测试 传递要给不存在的 idawait wrapper.vm.handleDeleteTodo(123)expect(wrapper.vm.todos.length).toBe(3)expect(wrapper.findAllComponents(TodoItem).length).toBe(3)})
})

完善组件功能

<!-- src\components\TodoApp\index.vue -->
<template><section class="todoapp"><TodoHeader @new-todo="handleNewTodo" /><section class="main"><input id="toggle-all" class="toggle-all" type="checkbox" /><label for="toggle-all">Mark all as complete</label><ul class="todo-list"><!-- These are here just to show the structure of the list items --><!-- List items should get the class `editing` when editing and `completed` when marked as completed --><TodoItemv-for="todo in todos":key="todo.id":todo="todo"@delete-todo="handleDeleteTodo"/></ul></section><!-- This footer should be hidden by default and shown when there are todos --><TodoFooter /></section>
</template><script>
import TodoHeader from './TodoHeader'
import TodoFooter from './TodoFooter'
import TodoItem from './TodoItem'export default {name: 'TodoApp',components: { TodoHeader, TodoFooter, TodoItem },data () {return {todos: []}},methods: {handleNewTodo (text) {const lastTodo = this.todos[this.todos.length - 1]this.todos.push({id: lastTodo ? lastTodo.id + 1 : 1,text,done: false})},handleDeleteTodo (todoId) {const index = this.todos.findIndex(t => t.id === todoId)if (index !== -1) {this.todos.splice(index, 1)}}}
}
</script>

TodoItem 双击获得编辑状态

编写测试用例

test('edit todo style', async () => {const label = wrapper.findComponent('[data-testid="todo-text"]')const todoItem = wrapper.findComponent('[data-testid="todo-item"]')const todoEdit = wrapper.findComponent('[data-testid="todo-edit"]')// 触发双击事件await label.trigger('dblclick')// 断言 classexpect(todoItem.classes()).toContain('editing')// 失去焦点await todoEdit.trigger('blur')expect(todoItem.classes('editing')).toBeFalsy()
})

完善组件功能

<!-- src\components\TodoApp\TodoItem.vue -->
<template><li data-testid="todo-item" :class="{completed: todo.done,editing: isEditing}"><div class="view"><!-- eslint-disable-next-line vue/no-mutating-props --><input v-model="todo.done" data-testid="todo-done" class="toggle" type="checkbox" /><label data-testid="todo-text" @dblclick="isEditing=true">{{ todo.text }}</label><button data-testid="delete" class="destroy" @click="$emit('delete-todo', todo.id)"></button></div><inputclass="edit"value="Create a TodoMVC template"data-testid="todo-edit"@blur="isEditing=false"/></li>
</template><script>
export default {name: 'TodoItem',props: {todo: {type: Object,required: true}},data () {return {isEditing: false}}
}
</script>

TodoItem 自动获得焦点

通过自定义指令实现自动获得焦点。

<!-- src\components\TodoApp\TodoItem.vue -->
<template><li data-testid="todo-item" :class="{completed: todo.done,editing: isEditing}"><div class="view"><!-- eslint-disable-next-line vue/no-mutating-props --><input v-model="todo.done" data-testid="todo-done" class="toggle" type="checkbox" /><label data-testid="todo-text" @dblclick="isEditing=true">{{ todo.text }}</label><button data-testid="delete" class="destroy" @click="$emit('delete-todo', todo.id)"></button></div><inputv-focus="isEditing"class="edit"value="Create a TodoMVC template"data-testid="todo-edit"@blur="isEditing=false"/></li>
</template><script>
export default {name: 'TodoItem',props: {todo: {type: Object,required: true}},directives: {focus (element, binding) {if (binding.value) {element.focus()}}},data () {return {isEditing: false}}
}
</script>

TodoItem 保存修改

编写测试用例

test('save edit todo', async () => {const label = wrapper.findComponent('[data-testid="todo-text"]')const todoEdit = wrapper.findComponent('[data-testid="todo-edit"]')// 触发双击事件await label.trigger('dblclick')// 编辑文本框中的内容展示expect(todoEdit.element.value).toBe(wrapper.vm.todo.text)// 修改文本框的值const text = 'Hello'await todoEdit.setValue(text)// 触发回车保存事件await todoEdit.trigger('keyup.enter')// 断言是否对外发送一个自定义事件expect(wrapper.emitted()['edit-todo']).toBeTruthy()expect(wrapper.emitted()['edit-todo'][0][0]).toEqual({id: wrapper.vm.todo.id,text})// 断言编辑状态被取消expect(wrapper.vm.isEditing).toBeFalsy()
})

完善组件功能

// template
<inputv-focus="isEditing"class="edit":value="todo.text"data-testid="todo-edit"@blur="isEditing=false"@keyup.enter="handleEditTodo"/>// js
methods: {handleEditTodo (e) {this.$emit('edit-todo', {id: this.todo.id,text: e.target.value})// 取消编辑状态this.isEditing = false}
}

TodoApp 保存修改

编写测试用例

test('Edit Todo', async () => {const todo = { id: 2, text: 'abc' }// 修改任务await wrapper.vm.handleEditTodo(todo)expect(wrapper.vm.todos[1].text).toBe(todo.text)// 内容为空时删除任务todo.text = ''await wrapper.vm.handleEditTodo(todo)expect(wrapper.vm.todos.find(t => t.id === todo.id)).toBeFalsy()
})

完善组件功能

// template
<TodoItemv-for="todo in todos":key="todo.id":todo="todo"@delete-todo="handleDeleteTodo"@edit-todo="handleEditTodo"
/>// js
handleEditTodo ({ id, text }) {const todo = this.todos.find(t => t.id === id)if (!todo) {return}if (!text.trim().length) {// 执行删除操作return this.handleDeleteTodo(id)}// 执行修改操作todo.text = text
}

TodoItem 取消编辑

编写测试用例

test('cancel edit todo', async () => {const label = wrapper.findComponent('[data-testid="todo-text"]')const todoEdit = wrapper.findComponent('[data-testid="todo-edit"]')// 触发双击事件await label.trigger('dblclick')// 备份原内容const text = wrapper.vm.todo.text// 修改内容await todoEdit.setValue('bbb')// 触发 ESC 取消事件await todoEdit.trigger('keyup.esc')// 断言内容没有被修改expect(wrapper.vm.todo.text).toBe(text)// 断言编辑状态被取消expect(wrapper.vm.isEditing).toBeFalsy()
})

完善组件功能

// template
<inputv-focus="isEditing"class="edit":value="todo.text"data-testid="todo-edit"@blur="isEditing=false"@keyup.enter="handleEditTodo"@keyup.esc="handleCancelEdit"/>// js
handleCancelEdit () {this.isEditing = false
}

这篇关于Vue2 应用测试学习 02 - TDD 案例(案例介绍和创建、编写测试用例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1097915

相关文章

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编

python如何创建等差数列

《python如何创建等差数列》:本文主要介绍python如何创建等差数列的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python创建等差数列例题运行代码回车输出结果总结python创建等差数列import numpy as np x=int(in

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

前端如何通过nginx访问本地端口

《前端如何通过nginx访问本地端口》:本文主要介绍前端如何通过nginx访问本地端口的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、nginx安装1、下载(1)下载地址(2)系统选择(3)版本选择2、安装部署(1)解压(2)配置文件修改(3)启动(4)

怎么用idea创建一个SpringBoot项目

《怎么用idea创建一个SpringBoot项目》本文介绍了在IDEA中创建SpringBoot项目的步骤,包括环境准备(JDK1.8+、Maven3.2.5+)、使用SpringInitializr... 目录如何在idea中创建一个SpringBoot项目环境准备1.1打开IDEA,点击New新建一个项

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(