Search code examples
javascriptpuppeteercucumberjs

How to attach screenshots for failed steps in cucumber-html-reporter using PUPPETEER?


addCase.js:

const {Given, When, Then, Before, After} = require('cucumber');

After(async function(scenario) {
    if (scenario.result.status === 'failed') {
        const screenShot = await this.page.screenshot();
        this.attach(screenShot,'image/png');
    }
});

world.js:

const expect = require("chai");
const puppeteer = require("puppeteer");
const {setWorldConstructor} = require("cucumber");
const helpers = require("../../helpers");
const config = require("../../config");

class CustomWorld{

    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);

ERROR:

 TypeError: this.attach is not a function
  • I tried with scenario.attach() - error: scenario.attach() not a function
  • Also tried with simple storeScreenshot: false in my reporter.js (no change)

Solution

  • You have to declare the attach inside constructor:

    function CustomWorld({ attach, parameters }) {
      this.attach = attach
      this.parameters = parameters
    }
    

    There are a few instructions on the docs: https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/world.md

    Then your call inside After (this.attach) will work normally.