Cypress 8.6.0 adds overwrite option to cy.screenshot

Cypress has the in-build capacity to take screenshots, whether you are running in interactive mode using cypress open or cypress run and even in CI as a part of the pipeline.

It can also capture screenshots automatically on the failure of a test case when running via cypress run.

However, to take a manual screenshot, we can use the cy.screenshot() command.

Syntax

cy.screenshot()
cy.screenshot(fileName)
cy.screenshot(options)
cy.screenshot(fileName, options)

Before

Before version 8.6.0, the captured screenshots appends a number at the end of each screenshot taken within the same test.

describe("screenshot example", () => {
  it("should append number to the screenshot",() => {
     cy.visit("www.google.co.in");
     cy.screenshot("screenshot");
     cy.screenshot("screenshot");

      cy.readFile(
      `cypress/screenshots/${path.basename(__filename)}/screenshot (1).png`
    ).should("exist");
  })
})

After running the above test, we can notice that there are two files with the name screenshot.png and screenshot (1).png in the screenshots folder. We can confirm the same with the images of the passing test and the directory.

After

Cypress 8.6.0 introduced the overwrite option to the cy.screenshot command. By default, the overwrite is false and, when overwrite is set to true, the new screenshot will overwrite an existing screenshot with the same file name.

describe("screenshot example", () => {
  it("should append number to the screenshot",() => {
     cy.visit("www.google.co.in");
     cy.screenshot("screenshot");
     cy.screenshot("screenshot",{overwrite: true});

      cy.readFile(
      `cypress/screenshots/${path.basename(__filename)}/screenshot (1).png`
    ).should("not.exist");
  })
})

Notice how we have passed the overwrite: true to the second screenshot command and, now it will overwrite the existing screenshot and not append a number with a new file. We can confirm it with the following images of the test and the directory.

Need help on your Ruby on Rails or React project?

Join Our Newsletter