如何在Cucumber-html-reporter中用Puppeteer为失败步骤附加截图?
Let's break down why you're hitting this error and walk through the fixes to get your failure screenshots attached properly to your Cucumber reports.
Root Cause
The attach method is a built-in part of Cucumber's default World object. When you created a custom CustomWorld class without inheriting from the default World, you lost access to this method. Additionally, incorrect context binding in your hook or outdated Cucumber API usage can also trigger this error.
Solution 1: Inherit from Cucumber's Default World Class
The simplest fix is to have your CustomWorld extend Cucumber's native World class, which gives you immediate access to this.attach and other built-in methods.
Update your world.js like this:
const expect = require("chai"); const puppeteer = require("puppeteer"); const { setWorldConstructor, World } = require("cucumber"); // Import default World const helpers = require("../../helpers"); const config = require("../../config"); class CustomWorld extends World { // Extend the default World async launchBrowser(){ this.browser = await puppeteer.launch({ headless: config.isHeadless, args: config.args, }); this.page = await this.browser.newPage(); await this.page.setViewport({ width: config.viewportWidth, height: config.viewportHeight }); } } setWorldConstructor(CustomWorld);
Solution 2: Fix Hook Context and Scenario Object Usage
Make sure you're using the correct syntax for your Cucumber version, and avoid arrow functions in hooks (they break this context):
Update your addCase.js:
const { Given, When, Then, Before, After } = require('cucumber'); // Use a regular function (not arrow) to preserve `this` context After(async function({ scenario }) { if (scenario.result.status === 'failed') { const screenShot = await this.page.screenshot(); // Now this.attach should work since we inherited from World await this.attach(screenShot, 'image/png'); } });
Solution 3: Verify Cucumber-html-reporter Configuration
Double-check your reporter settings to ensure screenshots are enabled (set storeScreenshots to true, not false):
const reporter = require('cucumber-html-reporter'); const options = { // Other configs... screenshotsDirectory: './screenshots/', // Define where screenshots are stored storeScreenshots: true, // Enable screenshot storage in reports // Other configs... }; reporter.generate(options);
Quick Compatibility Check
- For Cucumber v6 and earlier: Ensure your custom World doesn't override the default context, and use
this.attachdirectly in hooks. - For Cucumber v7+: Extending the
Worldclass is the recommended approach, as it aligns with updated API standards.
Following these steps should resolve the "not a function" error and let you attach screenshots to failed test steps in your cucumber-html-reporter output.
内容的提问来源于stack exchange,提问作者Ilija Ivanovski

