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

求Playwright JavaScript自定义位置截图嵌入标准报告的代码

在Playwright JavaScript中给指定步骤添加截图到标准报告

直接用Playwright Test内置的API就能实现,不需要额外插件。核心是在test.step里生成截图,再通过test.info().attach把截图绑定到对应步骤,用npx playwright show-report查看报告时,截图会直接显示在步骤详情里。

基础实现示例

const { test, expect } = require('@playwright/test');

test('带步骤截图的测试用例', async ({ page }) => {
  await page.goto('https://example.com');

  // 第一步:访问页面后添加截图
  await test.step('访问目标页面并截图', async () => {
    // 生成截图,fullPage可选,按需开启整页截取
    const pageScreenshot = await page.screenshot({ fullPage: true });
    // 将截图附加到当前步骤
    test.info().attach('页面初始状态', {
      body: pageScreenshot,
      contentType: 'image/png',
    });
    // 这里可以加你的断言逻辑
    await expect(page).toHaveTitle('Example Domain');
  });

  // 第二步:操作后添加截图
  await test.step('点击跳转链接并截图', async () => {
    await page.getByRole('link', { name: 'More information' }).click();
    const afterClickScreenshot = await page.screenshot();
    test.info().attach('跳转后页面', {
      body: afterClickScreenshot,
      contentType: 'image/png',
    });
    await expect(page).toHaveTitle('IANA — IANA-managed Reserved Domains');
  });
});

进阶:封装重复逻辑

如果多个测试用例都需要步骤截图,可以封装成工具函数减少重复代码:

const { test, expect } = require('@playwright/test');

// 封装步骤截图函数
async function addStepScreenshot(page, stepDesc, screenshotName) {
  await test.step(stepDesc, async () => {
    const screenshot = await page.screenshot({ fullPage: true });
    test.info().attach(screenshotName, {
      body: screenshot,
      contentType: 'image/png',
    });
  });
}

test('使用封装函数的测试', async ({ page }) => {
  await page.goto('https://example.com');
  
  await addStepScreenshot(page, '加载首页完成', '首页截图');
  await expect(page).toHaveTitle('Example Domain');

  await page.getByRole('link', { name: 'More information' }).click();
  await addStepScreenshot(page, '跳转到详情页', '详情页截图');
  await expect(page).toHaveTitle('IANA — IANA-managed Reserved Domains');
});

查看报告

运行测试后执行:

npx playwright show-report

打开报告后,点击对应的测试步骤,就能看到内嵌的截图了——不需要额外下载,直接在步骤详情里查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:45:44