README.md 3.6 KB

E2E 测试框架

基于 Playwright 的端到端测试框架,用于验证完整的用户流程和系统功能。

目录结构

tests/e2e/
├── specs/                 # 测试用例
│   ├── auth/             # 认证相关测试
│   │   ├── login.spec.ts
│   │   ├── register.spec.ts
│   │   └── logout.spec.ts
│   ├── users/            # 用户管理测试
│   │   ├── user-crud.spec.ts
│   │   └── profile.spec.ts
│   └── admin/            # 管理后台测试
├── fixtures/             # 测试数据
│   └── test-users.json
├── pages/                # 页面对象模型
│   ├── login.page.ts
│   ├── register.page.ts
│   ├── dashboard.page.ts
│   └── user-management.page.ts
├── utils/                # 测试工具
│   ├── test-setup.ts
│   ├── test-teardown.ts
│   └── helpers.ts
├── playwright.config.ts  # Playwright 配置
├── global-setup.ts       # 全局设置
└── global-teardown.ts    # 全局清理

安装和设置

安装依赖

pnpm install

安装 Playwright 浏览器

npx playwright install --with-deps

运行测试

运行所有 E2E 测试

pnpm test:e2e

运行特定测试文件

pnpm test:e2e tests/e2e/specs/auth/login.spec.ts

使用 UI 模式运行测试

pnpm test:e2e:ui

调试模式

pnpm test:e2e:debug

仅运行 Chromium 测试

pnpm test:e2e:chromium

测试数据

测试用户账号:

  • 管理员: admin / admin123
  • 普通用户: testuser / test123

CI/CD 集成

GitHub Actions

测试在每次 push 到 main/develop 分支和 pull request 时自动运行。

本地开发

  1. 启动开发服务器:pnpm dev
  2. 运行测试:pnpm test:e2e

测试报告

测试完成后会生成以下报告:

  • HTML 报告: tests/e2e/playwright-report/
  • JUnit 报告: test-results/junit.xml
  • 控制台输出: 实时测试进度和结果

编写测试

页面对象模型 (Page Objects)

使用页面对象模式封装页面交互逻辑:

class LoginPage {
  async login(username: string, password: string) {
    await this.usernameInput.fill(username);
    await this.passwordInput.fill(password);
    await this.loginButton.click();
  }
}

测试用例结构

test.describe('用户认证', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/login');
  });

  test('成功登录', async ({ loginPage, dashboardPage }) => {
    await loginPage.login('admin', 'admin123');
    await dashboardPage.expectToBeVisible();
  });
});

最佳实践

  1. 使用页面对象: 封装页面交互逻辑
  2. 使用夹具数据: 在 fixtures/ 中管理测试数据
  3. 使用等待策略: 使用 page.waitForLoadState('networkidle')
  4. 使用断言: 验证页面状态和业务逻辑
  5. 处理异步操作: 使用适当的等待和重试机制

故障排除

常见问题

  1. 浏览器启动失败: 运行 npx playwright install
  2. 测试超时: 检查服务器是否正常运行
  3. 元素找不到: 使用正确的选择器和等待策略

调试技巧

  • 使用 test.e2e:debug 启动调试模式
  • 使用 page.pause() 暂停测试执行
  • 查看 Playwright 追踪文件

性能优化

  • 使用 fullyParallel: true 并行执行测试
  • 使用 workers 配置控制并发数
  • 使用 retries 处理偶发性失败

监控和警报

  • GitHub Actions 集成 Slack 通知
  • 测试失败时自动发送警报
  • 历史测试结果追踪和分析