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

如何为Playwright执行通过的测试添加附加信息并关联留存

为已通过测试添加附加信息的实现方案

Playwright 原生提供了测试信息附加能力,完全适配你的需求,不需要自行维护全局存储对象,也不会因为重试特性导致数据丢失,具体实现方式如下:

  • 核心调用方法
    Playwright 内置的test.info().attach()接口可以直接将任意类型的内容和当前测试用例绑定,支持对象、截图、文本等多种格式,示例代码如下:
    import { test } from '@playwright/test';
    
    test('工单生成测试', async ({ page }) => {
      // 测试运行中生成的业务数据
      const workOrder = {
        id: 'WO2024001',
        amount: 3999,
        createTime: new Date().toISOString()
      };
    
      // 附加结构化对象数据
      await test.info().attach('工单信息', {
        body: JSON.stringify(workOrder, null, 2),
        contentType: 'application/json'
      });
    
      // 附加截图
      await test.info().attach('提交成功页截图', {
        body: await page.screenshot({ fullPage: true }),
        contentType: 'image/png'
      });
    });
    
  • 封装自定义调用方法
    你可以通过扩展Playwright fixture快速封装成你想要的test.addInfo调用形式:
    import { test as baseTest } from '@playwright/test';
    
    // 扩展fixture
    export const test = baseTest.extend({
      addInfo: async ({}, use) => {
        await use(async (name, content) => {
          if (typeof content === 'object' && !Buffer.isBuffer(content)) {
            // 对象自动转JSON存储
            await test.info().attach(name, {
              body: JSON.stringify(content, null, 2),
              contentType: 'application/json'
            });
            return;
          }
          // 其他类型直接传入
          await test.info().attach(name, { body: content });
        });
      }
    });
    
    // 测试中直接调用
    test('采购单生成测试', async ({ page, addInfo }) => {
      const purchaseOrder = { id: 'PO2024001', supplier: 'XX供应商' };
      await addInfo('采购单信息', purchaseOrder);
    });
    
  • 数据导出与报告读取
    所有附加的信息会自动关联到对应测试用例,你可以直接通过Playwright的内置报告获取:
    • HTML报告中点击对应测试用例即可直接查看所有附件内容
    • JSON报告中会包含每个测试用例的attachments字段,存储了附件的路径、格式等信息,可直接读取导出

该方案完全基于Playwright的原生测试上下文实现,重试时每个重试批次的测试数据会独立存储,不会出现丢失问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:03