Vue Testing Library
简单且完整的 Vue.js 测试工具,鼓励良好的测试实践。
Vue Testing Library 是一个构建在 DOM Testing Library 和 @vue/test-utils 之上的轻量级适配器。
目录
安装
本模块通过 npm 分发,应作为您项目的 devDependencies 之一进行安装:
npm install --save-dev @testing-library/vue
该库包含 peerDependencies 个针对 Vue 3 和
@vue/compiler-sfc 的列表。
您可能还希望安装 jest-dom,以便使用 自定义
Jest 匹配器。
如果您使用的是 Vue 2,请安装该库的第 5 版:
npm install --save-dev @testing-library/vue@^5
一个基础示例
<template>
<p>Times clicked: {{ count }}</p>
<button @click="increment">increment</button>
</template>
<script>
export default {
name: 'Button',
data: () => ({
count: 0,
}),
methods: {
increment() {
this.count++
},
},
}
</script>
import {render, screen, fireEvent} from '@testing-library/vue'
import Button from './Button'
test('increments value on click', async () => {
// The `render` method renders the component into the document.
// It also binds to `screen` all the available queries to interact with
// the component.
render(Button)
// queryByText returns the first matching node for the provided text
// or returns null.
expect(screen.queryByText('Times clicked: 0')).toBeTruthy()
// getByText returns the first matching node for the provided text
// or throws an error.
const button = screen.getByText('increment')
// Click a couple of times.
await fireEvent.click(button)
await fireEvent.click(button)
expect(screen.queryByText('Times clicked: 2')).toBeTruthy()
})
你可能希望安装
jest-dom以添加诸如.toBeInTheDocument()等便捷的断言。在上面的示例中,你可以编写expect(screen.getByText('Times clicked: 0')).toBeInTheDocument()。
使用
byText查询并不是查询元素的唯一方式,也不是最佳方式。阅读 Which query should I use? 以了解替代方案。在上面的示例中,getByRole('button', {name: 'increment'})可能是获取按钮元素的最佳选择。
更多示例
你可以在 the test directory 中找到针对不同场景和流行库的测试示例。
其中包含:
欢迎贡献更多示例!
指导原则
我们只尝试公开那些鼓励你编写与 Vue 组件使用方式紧密相似的测试的方法和工具。
本项目包含的工具基于以下指导 原则:
- 如果它与渲染组件相关,它处理的是 DOM 节点,而不是 组件实例,也不应鼓励处理组件 实例。
- 它应该对测试单个 Vue 组件或完整的 Vue 应用程序普遍有用。
- 工具的实现和 API 应该简单且灵活。
归根结底,我们希望这个库能够相当 轻量、简单且易于理解。
文档
类型定义
请注意,需要 TypeScript 4.X。
TypeScript 类型定义位于 types 目录中。
ESLint 支持
如果您想要对使用 Vue Testing Library 的测试文件进行 lint 检查,可以使用 官方插件:eslint-plugin-testing-library。
问题
想要贡献代码?请查找 Good First Issue 标签。
🐛 缺陷
对于缺陷、文档缺失或 意外行为,请 提交 issue。
💡 功能请求
请 提交 issue 以建议新功能。通过添加 👍 来为功能 请求投票。这有助于维护者优先确定要处理的内容。
❓ 问题
对于与使用该库相关的问题,请访问支持社区 而不是在 GitHub 上提交 issue。