剧作家测试自动化实践
 
E2E使用Playwright结合TypeScript、页面对象模型和Allure报告进行测试。
🎯 特性
- ✅ 页面对象模型架构
- ✅ TypeScript用于类型安全
- ✅ 有历史/趋势的诱惑报告
- ✅ GitHub操作带有浏览器缓存的CI/CD
- ✅ 跨浏览器测试(Chromium、Firefox、WebKit)
- ✅ 为不稳定的测试重试逻辑
- ✅ 用于测试隔离的定制夹具
📋 安装
npm ci # Install dependencies
npx playwright install # Install browsers🧪 运行测试
# Run all tests
npx playwright test
# Run specific file
npx playwright test homepage.spec.ts
# Run by tag
npx playwright test --grep '@smoke'
# Run by title
npx playwright test -g "should login successfully"
# Run last failed
npx playwright test --last-failed
# Run headed/debug mode
npx playwright test --headed
npx playwright test --debug
# Run specific browser
npx playwright test --project=chromium📋 列出测试
npx playwright test --list # All tests
npx playwright test --list --grep '@smoke' # Filtered by tag📊 报告
剧作家HTML报告
npx playwright show-report诱惑报告
🌐 推荐:在GitHub页面上查看
每次CI运行后都会自动部署报告:
- 网址:
https://.github.io// - 设置: 回购设置→ 页面→ 来源: gh页面 分支
- 优点: 始终保持最新状态,包括趋势,无需本地设置
本地生成:
npm run allure:serve # Generate and open (auto-starts server)
npm run allure:generate # Generate only
npm run allure:open # Open existing report
npm run allure:clean # Clean old reports📊 趋势: 运行测试2-3次以上,查看趋势图(持续时间、重试次数、历史记录)。
注: 如果从GitHub Actions下载工件,请不要打开index.html直接。通过HTTP提供服务:cd allure-report && npx -y serve -p 8080 .→ http://localhost:8080
🔄 GitHub操作
测试在以下情况下自动运行:
- 推到
main,feature/**,fix/**分支 - 将请求拉到
main - 手动触发
浏览器缓存已启用 -第一次运行速度较慢,随后每个浏览器的运行速度要快60秒左右。
🏗️ 项目结构
├── tests/ # Test specs
├── pages/ # Page Objects
├── actions/ # Reusable actions
├── helpers/ # Utilities
├── data/ # Test data
├── constants/ # Selectors, configs
├── fixtures/ # Custom fixtures
├── .cursor/ # Cursor AI rules & commands
│ ├── rules/ # Workspace rules
│ └── commands/ # Custom commands
└── .github/ # GitHub configuration
└── workflows/ # CI/CD workflows📝 写作测试
test('example', async ({ homePage, cartPage }) => {
await homePage.goto();
await homePage.addFirstNProductsToCart(2);
await cartPage.assertCartItemsExactCount(2);
});🔧 版本管理
# Check version
npx playwright --version
npm ls @playwright/test
# Upgrade
npm install playwright@latest
npm install playwright@1.50.1 # Specific version
# Fix multiple versions
rm -rf node_modules package-lock.json
npm install重要提示: 更新 .github/workflows/playwright.yml 与剧作家的版本相匹配。
🧪 测试与整理
npx tsc -p tsconfig.json # Check TypeScript
npx eslint . # Lint
npx eslint . --fix # Lint and fix💡 最佳实践
- 标签测试:
@smoke,@sanity,@flaky - 使用
.fixme()用于带注释的失败测试 - 在页面构造函数中保留定位器
- 将测试数据集中到
data/ - 遵循安排→ Act → 断言模式
