Cypress.io Mochawesome report with screenshots (Hooks)

Bothi Palani
1 min readFeb 22, 2021

Attach Screenshots for Moachawesome report when tests fails at Hooks (before, beforEach, after, afterEach)

I was looking for many places to find out how to generate mochawesome report with screenshots when cypress e2e tests fail at before & after tests. I could only see few references so I thought of putting down all my learnings here!

I assume you know how to setup the framework to generate the report if not please follow these blogs,

what is to be done to attach the screenshots when the tests fail during Hooks?

You need to put the following code in your cypress/support/index.js file

Cypress.on('test:after:run', (test, runnable) => {
if (test.state === 'failed') {
let item = runnable;
const nameParts = [runnable.title];

while (item.parent) {
nameParts.unshift(item.parent.title);
item = item.parent;
}

if (runnable.hookName) {
nameParts.push(`${runnable.hookName} hook`);
}

const fullTestName = nameParts.filter(Boolean).join(' -- ');
const screenshotPath = `assets/${Cypress.spec.name}/${fullTestName} (failed).png`.replace(' ', ' ');

addContext({ test }, screenshotPath);
}

Please make sure mochawesome-report/mochawesome.json has the correct value for the key `context`.

--

--