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

如何通过代码配置Playwright在Cucumber集成场景下失败时自动截图

Cucumber + Playwright 实现测试失败自动截图

需求完全可行,不会因为使用Cucumber运行测试就无法实现截图功能。Playwright Test内置的自动截图依赖其官方测试运行器的配置,但手动启动浏览器时,我们可以通过Cucumber的钩子(Hooks)结合Playwright的截图API手动实现相同效果。

具体实现步骤

  1. 借助Cucumber的After钩子,在每个测试场景执行完毕后检查是否失败
  2. 若场景失败,调用Playwright的page.screenshot()方法完成截图并保存

代码示例

在Cucumber的support/hooks.js文件中添加以下逻辑:

const { After } = require('@cucumber/cucumber');
const fs = require('fs').promises;
const path = require('path');

// 确保截图目录存在,避免保存时出错
const ensureScreenshotDir = async () => {
  const dir = path.join(process.cwd(), 'screenshots');
  try {
    await fs.access(dir);
  } catch {
    await fs.mkdir(dir, { recursive: true });
  }
};

After(async function (scenario) {
  await ensureScreenshotDir();
  
  // 判断当前场景是否执行失败
  if (scenario.result.status === 'FAILED') {
    // 生成唯一截图文件名,避免重名覆盖
    const screenshotName = `${scenario.pickle.name.replace(/\s+/g, '-')}-${Date.now()}.png`;
    const screenshotPath = path.join('screenshots', screenshotName);
    
    // 执行全屏截图并保存到指定路径
    await this.page.screenshot({ path: screenshotPath, fullPage: true });
    
    // 可选:将截图附加到Cucumber测试报告中(支持的报告器可直接展示截图)
    await this.attach(await fs.readFile(screenshotPath), 'image/png');
  }
});

关键注意事项

  • 共享页面对象:需要确保page对象能在Cucumber的World上下文(即示例中的this.page)中访问到,可在Before钩子中初始化浏览器、上下文和页面,并挂载到World对象上
  • 自定义配置:可根据需求调整截图的命名规则、是否全屏截取、保存路径等参数
  • 报告集成:如果使用支持附件的Cucumber报告器,附加截图后能在报告中直接查看失败场景的页面状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:15:45