DEV Community

Open Sauce Projects
Open Sauce Projects

Posted on

Tech bits 1 - Cypress screenshot errors in headless mode

In this series, I share key lessons I’ve learned—one concept per post—for future me and anyone it might help.

In Cypress headless mode, when a test encounters an error, you can see the result of the test as a screenshot. However, the screenshot doesn’t show the cause of the error—it only shows where the error occurred (e.g., the failing selector or the function like then where it happened).

You can work around this limitation by creating a separate screenshot that displays the error message directly on the page.

Cypress.on("fail", (error, runnable) => {
   // Append the error message to the body
   cy.document().then((doc) => {
      const errorDiv = doc.createElement("div");
      errorDiv.innerText = `Error: ${error.message}`;
      errorDiv.style.position = "fixed";
      errorDiv.style.top = "0";
      errorDiv.style.left = "0";
      errorDiv.style.backgroundColor = "red";
      errorDiv.style.color = "white";
      errorDiv.style.padding = "10px";
      errorDiv.style.zIndex = "9999";
      doc.body.appendChild(errorDiv);
   });

   // Wait a moment so it renders
   cy.wait(500);

   // Take the screenshot
   cy.screenshot("errors/error_screenshot_with_message");

   // Rethrow the error to fail the test
   throw error;
});
Enter fullscreen mode Exit fullscreen mode

This code block listens for the fail event. When triggered, it creates a red banner at the top of the page displaying the error message. The code should be placed inside the cypress/support/e2e.ts file (or e2e.js if you're using JavaScript).

Happy coding!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.