如何使用 PUPPETEER 附加 cucumber-html-reporter 中失败步骤的屏幕截图?

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

错误:

 TypeError: this.attach is not a function

在 After hooks 函数中尝试使用以下代码:

if (!(scenario.result.status === 'failed')) return;
    try {
        const data18 = await driver.takeScreenshot();
        const image18 = Buffer.from(data18, 'base64');
        await this.World.attach(image18, 'image/png');
    } catch (e) {
        console.log(e.message);
    }

此代码将检查场景是否失败。如果失败,它将捕获驱动程序屏幕截图,并在 nodejs 缓冲区的帮助下附加到 this.world 对象。

您必须在构造函数中声明附加:

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

文档上有一些说明:https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/world.md

那么您在 After (this.attach) 中的调用将正常工作。