You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright生成测试报告后执行自定义代码上传至Xray Cloud

在Playwright测试结束且报告生成后上传Xray Cloud结果的方案

方案1:自定义Playwright Reporter(推荐)

Playwright的Reporter API提供了onEnd钩子,这个钩子会在所有测试执行完成、报告文件生成完毕后触发,完美匹配你的需求。

步骤:

  1. 创建自定义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() {}
}
  1. 在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中串联测试命令和上传脚本,确保测试完成生成报告后再执行上传。

步骤:

  1. 创建独立的上传脚本(比如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();
  1. 在package.json中添加组合脚本:
{
  "scripts": {
    "test": "playwright test",
    "test:upload": "npm run test && node upload-xray.js"
  }
}
  1. 执行测试+上传:
npm run test:upload

为什么globalTeardown不行?

Playwright的globalTeardown是在测试进程即将退出前执行的,而JUnit报告的生成是Playwright内部在测试进程退出的最后阶段完成的,因此globalTeardown执行时报告文件还未生成,导致上传失败。


内容的提问来源于stack exchange,提问作者Radu Theodor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:23:18