如何在Playwright(TypeScript)自动化测试中获取测试统计并集成至CI/CD邮件
获取Playwright测试统计数据并集成到CI邮件通知
1. 生成可解析的JSON测试报告
在CI的Playwright测试命令中添加JSON报告输出参数,让测试结果以结构化格式保存:
修改.yml配置中script段的测试命令:
npx playwright test sample.spec.ts --reporter json=test-results.json
同时将生成的test-results.json加入到artifacts列表,确保后续邮件脚本能访问到:
artifacts: paths: - ./playwright-report/ - ./Screenshot/ - ./Reports/ - ./test-results.json # 新增JSON结果文件 when: always expire_in: 7 days
2. 在Email.ts中解析统计数据
更新Email.ts脚本,读取JSON结果文件并提取所需的测试指标:
import * as fs from 'fs'; // 接收CI传递的参数 const commitSha = process.argv[2]; const pipelineId = process.argv[3]; const jobId = process.argv[4]; // 读取并解析测试结果 const testResults = JSON.parse(fs.readFileSync('../test-results.json', 'utf-8')); const summary = testResults.summary; // 提取核心统计数据 const passedCount = summary.stats.passed || 0; const failedCount = summary.stats.failed || 0; // 统计Flaky测试(Playwright中标记为flaky的测试用例) const flakyCount = testResults.suites.reduce((total: number, suite: any) => { return total + suite.tests.filter((test: any) => test.status === 'flaky').length; }, 0); // 计算总执行时长(转换为分钟) const startTime = new Date(testResults.startTime); const endTime = new Date(testResults.endTime); const totalDuration = ((endTime.getTime() - startTime.getTime()) / 1000 / 60).toFixed(2); // 构建邮件正文 const emailContent = ` <h2>自动化测试执行报告</h2> <p><strong>提交哈希:</strong> ${commitSha}</p> <p><strong>流水线ID:</strong> ${pipelineId}</p> <p><strong>任务ID:</strong> ${jobId}</p> <table border="1" cellpadding="6" cellspacing="0"> <tr> <th>测试状态</th> <th>数量</th> </tr> <tr> <td>通过</td> <td>${passedCount}</td> </tr> <tr> <td>失败</td> <td>${failedCount}</td> </tr> <tr> <td>Flaky</td> <td>${flakyCount}</td> </tr> </table> <p><strong>总执行时长:</strong> ${totalDuration} 分钟</p> `; // 替换为你的实际邮件发送逻辑(例如使用nodemailer) // 示例: // import nodemailer from 'nodemailer'; // const transporter = nodemailer.createTransport({ // // 邮件服务配置 // }); // await transporter.sendMail({ // from: 'sender@example.com', // to: 'recipient@example.com', // subject: `测试结果通知 - 流水线 ${pipelineId}`, // html: emailContent // }); console.log(emailContent); // 用于调试,实际发送时移除
3. 简化CI配置的冗余命令
原.yml中的script段存在重复的npm安装命令,可简化为:
script: - | npm ci # 自动安装package-lock.json中定义的所有依赖 npx playwright install --with-deps npx playwright install msedge chrome npx playwright test sample.spec.ts --reporter json=test-results.json npm install -g typescript # 若编译email.ts需要全局TS,保留此行
说明:npm ci会完整安装项目依赖,无需单独执行npm install @playwright/test、npm install mysql等命令。
4. 确认package.json依赖配置
确保package.json中包含必要的依赖项:
{ "devDependencies": { "@playwright/test": "^1.35.1", "typescript": "^5.0.0", "allure-playwright": "^2.0.0" }, "dependencies": { "mysql": "^2.18.1" } }
内容的提问来源于stack exchange,提问作者Arun Yadav
相关产品推荐
相关产品推荐

