如何在Playwright框架中为Cucumber HTML报告添加截图?
在Playwright+Cucumber框架中为失败场景添加截图到HTML报告的问题
我正在尝试给Playwright测试框架的Cucumber HTML报告添加截图,初始的reporter.js代码如下:
const reporter = require('cucumber-html-reporter') const options = { theme: 'bootstrap', jsonFile: 'cucumber_report.json', output: 'reports/cucumber_report.html', reportSuiteAsScenario: true, scenarioTimestamp: true, launchReport: true, } reporter.generate(options)
根据cucumber-html-reporter的截图存储文档,我在reporter.js的配置里补充了以下内容:
{ ... output: '/report/cucumber_report.html', screenshotsDirectory: 'screenshots/', storeScreenshots: true }
文档说明storeScreenshots: true会将截图存储到指定目录,目录不存在时会自动创建,但运行测试后并未生成预期的screenshots目录。我通过npm run testAndReport执行测试流程,对应的package.json脚本配置如下:
"scripts": { "test": "./node_modules/.bin/cucumber-js --require cucumber.js --require step-definitions/**/*.js -f json:cucumber_report.json --publish-quiet", "report": "node reporter.js", "testAndReport": "npm run test; npm run report" }
更新:
我在hooks.js中添加了如下After钩子:
After(async function (scenario) { const img = await global.page.screenshot({ path: `screenshots/${scenario.pickle.name}.png` }) await this.attach(img, 'image/png') await global.page.close() await global.context.close() })
使用这段代码时,每个测试场景都成功添加了截图。但当我修改钩子,尝试仅在测试失败时添加截图后:
if (scenario.result.status === 'failed') { const img = await global.page.screenshot({ path: `screenshots/${scenario.pickle.name}.png` }) await this.attach(img, 'image/png') }
修改后再也没有截图被添加到报告中。
内容的提问来源于stack exchange,提问作者user9847788
相关产品推荐
相关产品推荐

