测试的学问很深,有很多种不同的测试类型:
在我们项目中,我们是代码的制造者,我们主要关注代码逻辑、组件渲染和交互,组件逻辑也非常清楚,因此我们只做单测,属于白盒测试。
Vitest是Vue/Vite团队成员维护的单元测试框架,它可以使用和Vite同一个配置并且使用相同的转换流程,因此安装配置都非常快捷!
安装Vitest
yarn add -D vitest happy-dom @testing-library/vue
配置,vite.config.js
///
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
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a9Sg6SoZ-1665996199411)(https://secure2.wostatic.cn/static/rUPEZnMLANd91dxtk7FKgJ/image.png?auth_key=1665995535-hnGp391uUqbsLN6vTrvjCA-0-4b449808bbdea5008b631a31b2d71d89?auth_key=1665995989-8AZVfrTLaFvXbiZBrEZpPB-0-ef910e9eaf2410e0ed19cfe6eb2451fd)]](https://1000bd.com/contentImg/2024/04/29/584c72a9c7b126f9.png)
学会基本用法和原则之后,我们需要实战一下,下面我们给我们的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
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z9OfA6Cc-1665996199412)(https://secure2.wostatic.cn/static/vjZESUshqZrtvszDHrpi4P/image.png?auth_key=1665995535-t3NhNpKJE6FoVhwNS7hSvc-0-5f8dd01e6c87faf5bd8206ea1744268c?auth_key=1665995989-9kMnGTE5cKsaE5rbeCDUDQ-0-91f573971af8c30578a7f6a8242e075b)]](https://1000bd.com/contentImg/2024/04/29/3bda440cb5bc75e4.png)