Cypress: Adding screenshots to mochawesome report with nested test hierarchy

Alok Sharma

--

Reporting is one of the very important feature of any automation framework. Test report should be clear, containing the necessary details that are informative to both technical, business and non-technical stakeholders.

We are using Cypress automation framework with Typescript for frontend automation. Earlier, the team relied on cypress-cucumber-reporter as we were using Cypress with BDD. But recently, we decided to get rid of the BDD layer.

This simplified the suite; however, this activity highlighted the need to change reporting as well (as we are no longer using BDD).

We decided to go with mochawesome reporting as it was quite simple and informative. Gradually, we are planning to use addContext method of mochawesome to enrich the generated report with more metadata.

There were a number of articles online; elaborating how to use mochawesome library and how we can add screenshots of the failed tests in the report.

We tried but the solution was not working for us. The problem was that some of the failed screenshots were not pulled in the generated report

We had added below code in support/index.ts file, in order to name and save the screenshot file.

//adding screenshots to the report
const addContext = require(‘mochawesome/addContext’);
Cypress.on(‘test:after:run’, (test, runnable) => {
if (test.state === ‘failed’) {
const screenshotFileName = `${runnable.parent.title} — ${test.title} (failed).png`;
addContext({
test
}, `assets/${Cypress.spec.name}/${screenshotFileName}`);
}
});

On further investigation we found that the above code works fine as long as your tests in the spec file are linear, which means, all tests in a spec file are under a single describe/context block (describe>it). But as soon as, you start nesting the tests, the report is unable to pull screenshots for the failed tests with multiple parents (describe>describe>it). This happens because while saving the screenshot for failed test; Cypress prefixes all the parent descriptions in the test file name. But in the above code snippet we are just navigating to a parent which is just one level up; assuming there won’t be any nesting.

In order to avoid this scenario, we replaced the above snippet with below code snippet and it worked for both nested as well as linear tests.

const addContext = require(“mochawesome/addContext”);
Cypress.on(“test:after:run”, (test, runnable) => {
let screenshotFileName = `${test.title} (failed).png`;
if (test.state === “failed”) {
try {
let parent = runnable.parent;
while (parent?.title !== “”) {
screenshotFileName = `${parent?.title} — ${screenshotFileName}`;
console.log(“🚀 screenshotFileName”, screenshotFileName);
parent = parent?.parent;
}
addContext(
{
test,
},
`assets/${Cypress.spec.name}/${screenshotFileName}`
);
} catch (err) {
console.error(err);
}
}
});

--

--