'Mochawesome use AddContext in afterEach with cypress

I spent the last 10 days trying to use the function addContext in the afterEach function as I'm using in "test:after:run" post action. The reason to do this is that I made visual testing during the test cases. This helps me to have a very useful screenshot that provides the difference between two images.

I would like to add those screenshots in the Mochawesome report using the addContext function, but in the "test:after:run" I'm not able to look into a folder to find the screenshots or use cy.task. On the other hand, I'm able to use cy.task in the afterEach. Now everything I tried to use as first parameter of addContext function is not working.

My code here:

Cypress.on("test:after:run", (test, runnable) => {
    let item = runnable
    const fullTestName = giveFullTestName(item, runnable.title)
    // This is to add the failed image when the test fails
    if (test.state === "failed") {
        const imageUrl = `../cypress/snapshots/actual/${Cypress.spec.name
            }/${fullTestName} (failed).png`
        addContext({ test }, imageUrl.replace('#', '%23').replace(':', ''));
    }
});

The previous section doesn't allow to use cy.task commands.

afterEach(() => {
    const test = cy.state('runnable')?.ctx;
    cy.task('screenshots').then(elements => {
        elements.forEach(element => {
            addContext({ test }, element.replace('#', '%23').replace(':', ''))
        })
    })                                                                                                                                        
});

The screenshots task is returning all the screenshots generated during the test case.

I tried to use as parameter without any success:

test['_runnable'], test['test'] and test['currentTest']

Test object

Could anyone help me to add those screenshots to the report?

Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source