测试种类
测试的学问很深,有很多种不同的测试类型:
- 单元测试:测试给定函数、类和复用逻辑
- 组件测试:检测咱们组件的挂载、渲染和交互性
- 端到端测试:通过真实网络请求我们应用并检测夸多页面的功能特性
在我们项目中,我们是代码的制造者,我们主要关注代码逻辑、组件渲染和交互,组件逻辑也非常清楚,因此我们只做单测,属于白盒测试。
单元测试框架:Vitest
Vitest
是Vue/Vite团队成员维护的单元测试框架,它可以使用和Vite同一个配置并且使用相同的转换流程,因此安装配置都非常快捷!
安装Vitest
yarn add -D vitest happy-dom @testing-library/vue
配置,vite.config.js
/// <reference types="vitest" />
import { defineConfig } from 'vite'
export default defineConfig({
// ...
test: {
// enable jest-like global test APIs
globals: true,
// simulate DOM with happy-dom
// (requires installing happy-dom as a peer dependency)
environment: 'happy-dom',
// 支持tsx组件,很关键
transformMode: {
web: [/.[tj]sx$/]
}
}
})
`避免类型错误提示
ts配置添加类型
// tsconfig.json
{
"compileroptions": {
"types": ["vitest/globals"]
}
}
编写测试
// Test.test.ts
test('it should work', () => {
const { getByText } = render(Test, {
props: {
msg: 'hello'
}
})
// assert output
getByText('hello')
})
添加脚本
{
// ...
"scripts": {
"test": "vitest"
}
}
运行
> npm test
原则
- 单元测试应该写的很小,仅覆盖单独函数、类、可复用逻辑或模块
- 单测关注逻辑正确性而且仅关注应用程序功能的一个小块
- 对于可视部分,组件测试验证的是基于输入的props和slots渲染输出的结果
- 对于行为逻辑,组件测试验证响应用户输入事件后正确的渲染更新和派发事件
实战
学会基本用法和原则之后,我们需要实战一下,下面我们给我们的Button组件编写几个单测练练手。
// button.test.ts
import { render } from '@testing-library/vue'
import Button from '../src/button'
// 基础按钮
test('it should work', () => {
const { getByRole } = render(Button)
getByRole('button')
})
// 插槽
test('default slot should be 按钮', () => {
const { getByText } = render(Button)
getByText('按钮')
})
test('default slot should work', () => {
const { getByText } = render(Button, {
slots: {
default() {
return 'button'
}
}
})
getByText('button')
})
// 按钮类型
test('default type should be secondary', () => {
// 默认secondary
const { getByRole } = render(Button)
const button = getByRole('button')
expect(button.classList.contains('s-btn--secondary')).toBe(true)
})
test('type should work', () => {
// 默认secondary
const { getByRole } = render(Button, {
props: {
type: 'primary'
}
})
const button = getByRole('button')
expect(button.classList.contains('s-btn--primary')).toBe(true)
})
运行单侧
yarn test
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/79692.html