@tianyio/quality-helper
Version:
A comprehensive quality helper tool for project scaffolding and management
187 lines (136 loc) • 3.2 kB
Markdown
# 自动化测试指南
## 测试工具链
### Vitest
- **功能**: 基于 Vite 的单元测试框架
- **特性**:
- 快速的测试执行
- 浏览器环境模拟 (happy-dom)
- 代码覆盖率报告
- UI 测试界面
### 测试目录结构
```
project/
├── test/
│ └── setup.ts # 测试环境设置
├── src/
│ └── **/*.test.ts # 测试文件
└── vitest.config.ts # Vitest 配置
```
## 编写测试
### 基本测试结构
```typescript
import { describe, it, expect } from 'vitest'
import { add } from './math'
describe('math utils', () => {
it('should add two numbers correctly', () => {
expect(add(1, 2)).toBe(3)
expect(add(-1, 1)).toBe(0)
expect(add(0, 0)).toBe(0)
})
})
```
### 异步测试
```typescript
import { describe, it, expect } from 'vitest'
describe('async operations', () => {
it('should resolve promise', async () => {
const result = await Promise.resolve('test')
expect(result).toBe('test')
})
})
```
### Vue 组件测试
```typescript
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'
describe('MyComponent', () => {
it('should render correctly', () => {
const wrapper = mount(MyComponent)
expect(wrapper.text()).toContain('Hello')
})
})
```
## 运行测试
### 命令行选项
```bash
# 运行测试 (开发模式)
pnpm test
# 运行测试 (一次性)
pnpm test:run
# 运行测试并生成覆盖率报告
pnpm test:coverage
# 在浏览器中查看测试界面
pnpm test:ui
```
### 高级用法
```bash
# 运行特定文件的测试
pnpm test:run src/utils/math.test.ts
# 运行特定测试套件
pnpm test:run --grep "math utils"
# 监听模式
pnpm test --watch
```
## 测试最佳实践
### 1. 测试命名
- 使用清晰、描述性的测试名称
- 遵循 "should do something" 的命名约定
### 2. 测试结构
- 每个测试应该只测试一个功能
- 使用 AAA 模式 (Arrange, Act, Assert)
### 3. 测试数据
- 使用真实的数据进行测试
- 避免硬编码的测试数据
### 4. 测试覆盖率
- 目标覆盖率: 80%+
- 关注关键业务逻辑的覆盖率
## 调试测试
### 1. 使用调试器
```bash
# 在调试模式下运行测试
pnpm test --inspect-brk
```
### 2. 输出详细信息
```bash
# 显示测试详细输出
pnpm test:run --reporter=verbose
```
### 3. 过滤测试
```bash
# 只运行特定测试
pnpm test:run --grep "specific test"
```
## 集成到 CI/CD
### GitHub Actions 示例
```yaml
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22.x
- name: Install dependencies
run: pnpm install
- name: Run tests
run: pnpm test:run
- name: Check coverage
run: pnpm test:coverage
```
### GitLab CI 示例
```yaml
test:
stage: test
script:
- pnpm install
- pnpm test:run
- pnpm test:coverage
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
```