如何在Playwright生成测试报告后执行自定义代码上传至Xray Cloud
在Playwright测试结束且报告生成后上传Xray Cloud结果的方案
方案1:自定义Playwright Reporter(推荐)
Playwright的Reporter API提供了onEnd钩子,这个钩子会在所有测试执行完成、报告文件生成完毕后触发,完美匹配你的需求。
步骤:
- 创建自定义Reporter文件(比如
xray-reporter.ts):
import { Reporter, FullConfig, Suite } from '@playwright/test'; import { XrayClient } from 'xray-automation-js'; export class XrayReporter implements Reporter { private xrayClient: XrayClient; // 配置Xray上传参数和报告路径 private readonly reportConfig = { projectKey: 'YOUR_PROJECT_KEY', // 其他Xray上传配置 }; private readonly reportPath = './playwright-report/junit.xml'; constructor() { // 初始化Xray客户端 this.xrayClient = new XrayClient({ baseUrl: 'https://xray.cloud.getxray.app/api/v2', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }); } // 测试全部结束、报告生成后执行上传 async onEnd(_config: FullConfig, _suite: Suite) { try { await this.xrayClient.submitResults(this.reportPath, this.reportConfig); console.log('✅ Xray测试结果上传成功'); } catch (error) { console.error('❌ Xray测试结果上传失败:', error); } } // 实现Reporter接口的其他必填方法(空实现即可) onBegin() {} onTestBegin() {} onTestEnd() {} }
- 在
playwright.config.ts中注册自定义Reporter,同时保留junit reporter生成报告:
import { defineConfig } from '@playwright/test'; import { XrayReporter } from './xray-reporter'; export default defineConfig({ reporter: [ ['junit', { outputFile: './playwright-report/junit.xml' }], // 生成JUnit格式报告 ['list'], // 保留控制台的测试结果输出 [XrayReporter], // 启用自定义Xray上传Reporter ], // 其他Playwright配置... });
方案2:串联命令行脚本(简单直接)
如果不想自定义Reporter,可以通过在package.json中串联测试命令和上传脚本,确保测试完成生成报告后再执行上传。
步骤:
- 创建独立的上传脚本(比如
upload-xray.js):
const { XrayClient } = require('xray-automation-js'); async function uploadToXray() { const xrayClient = new XrayClient({ baseUrl: 'https://xray.cloud.getxray.app/api/v2', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }); const reportPath = './playwright-report/junit.xml'; const uploadConfig = { projectKey: 'YOUR_PROJECT_KEY', }; try { await xrayClient.submitResults(reportPath, uploadConfig); console.log('✅ Xray结果上传成功'); } catch (err) { console.error('❌ 上传失败:', err); process.exit(1); } } uploadToXray();
- 在package.json中添加组合脚本:
{ "scripts": { "test": "playwright test", "test:upload": "npm run test && node upload-xray.js" } }
- 执行测试+上传:
npm run test:upload
为什么globalTeardown不行?
Playwright的globalTeardown是在测试进程即将退出前执行的,而JUnit报告的生成是Playwright内部在测试进程退出的最后阶段完成的,因此globalTeardown执行时报告文件还未生成,导致上传失败。
内容的提问来源于stack exchange,提问作者Radu Theodor
相关产品推荐
相关产品推荐

