Protractor结合Cucumber时Cucumber Reporter无法捕获截图
解决Protractor + Cucumber中cucumber-html-reporter无法捕获和保存截图的问题
看起来你遇到的核心问题是截图的保存逻辑与报告工具的配置没做好衔接,我来帮你一步步修复这个问题:
核心问题分析
- 当前
hooks.js仅把截图附加到了场景中,但没有将截图文件保存到cucumber-html-reporter指定的目录,导致报告无法读取到截图资源 - 路径配置可能使用了相对路径,引发工具无法定位目标目录的问题
- Cucumber生成的JSON报告需要包含截图的关联信息,才能让HTML报告正确渲染出截图
步骤1:修复Reporter配置(reporter.js)
首先确保所有路径使用绝对路径,避免相对路径引发的文件定位问题,同时补全必要的配置项:
const reporter = require("cucumber-html-reporter"); const path = require('path'); const datetime = new Date().toISOString().replace(/[:.]/g, '-'); // 定义绝对路径,替换成你项目的实际目录结构 const htmlReports = path.resolve(__dirname, './reports'); const targetjsonDir = path.resolve(__dirname, './reports/json'); // Cucumber JSON报告输出目录 const screenshotsDirectory = path.join(htmlReports, 'screenshots'); const cucumberReporteroptions = { theme: "bootstrap", jsonDir: targetjsonDir, output: path.join(htmlReports, `cucumber_reporter_${datetime}.html`), reportSuiteAsScenarios: true, storeScreenshots: true, screenshotsDirectory: screenshotsDirectory, launchReport: true, ignoreBadJsonFile: true, scenarioTimestamp: true, // 可选:为场景添加时间戳 metadata: { // 可选:添加测试环境元数据 "App Version": "1.0.0", "Test Environment": "Staging", "Browser": "Chrome", "Platform": "Windows 10", "Executed": "Local" } }; class Reporter { static createHTMLReport() { try { reporter.generate(cucumberReporteroptions); } catch (err) { console.error("Failed to generate cucumber HTML report:", err); } } } // 导出Reporter类,方便测试完成后调用 module.exports = Reporter;
步骤2:修复Hooks截图逻辑(hooks.js)
修改hooks,不仅要把截图附加到场景,还要将截图文件保存到指定目录,并关联到Cucumber的报告元数据中:
const fs = require('fs'); const path = require('path'); const htmlReports = path.resolve(__dirname, './reports'); const screenshotsDir = path.join(htmlReports, 'screenshots'); // 确保截图目录存在,不存在则创建 if (!fs.existsSync(screenshotsDir)) { fs.mkdirSync(screenshotsDir, { recursive: true }); } After(async function(scenario) { // 可选:只在场景失败时捕获截图,去掉if条件可捕获所有场景的截图 if (scenario.result.status === 'failed') { try { const screenshotBase64 = await browser.takeScreenshot(); // 生成唯一的截图文件名,避免重名覆盖 const screenshotName = `${scenario.pickle.name.replace(/\s+/g, '_')}_${new Date().toISOString().replace(/[:.]/g, '-')}.png`; const screenshotPath = path.join(screenshotsDir, screenshotName); // 将base64截图保存为文件到指定目录 fs.writeFileSync(screenshotPath, screenshotBase64, 'base64'); // 附加截图到场景,让Cucumber JSON报告包含该信息 await this.attach(screenshotBase64, 'image/png'); // 关键:将截图路径关联到场景,让html-reporter能识别并显示 scenario.attachments.push({ path: screenshotPath, mediaType: 'image/png' }); } catch (err) { console.error("Failed to capture and save screenshot:", err); } } });
步骤3:确保Cucumber生成JSON报告
在你的cucumber.js配置文件中,开启JSON报告输出,这样cucumber-html-reporter才能读取到包含截图信息的报告:
module.exports = { default: { format: [ 'json:reports/json/cucumber-report.json', // 输出JSON报告到指定目录 'progress' // 控制台显示执行进度 ], require: ['steps/**/*.js', 'hooks.js', 'reporter.js'], // 其他你的Cucumber配置,比如tags等 } };
步骤4:测试验证
- 运行你的Protractor+Cucumber测试
- 检查
reports/screenshots目录是否生成了截图文件 - 查看生成的HTML报告,确认失败(或所有)场景下是否显示了截图
这样修改后,应该就能解决截图无法保存和无法在报告中显示的问题了。
内容的提问来源于stack exchange,提问作者Bhuvnesh Sainani
相关产品推荐
相关产品推荐

