How to Perform Screenshot Testing in Cypress

Understand the process of performing screenshot testing in Cypress with this guide. Test on real devices using BrowserStack Automate.

Get Started free
Guide Banner Image
Home Guide How to Perform Screenshot Testing in Cypress

How to Perform Screenshot Testing in Cypress

In modern test automation, frameworks like Cypress are designed to run tests autonomously, often via command-line or CI/CD tools like Jenkins.

When a test fails, the automation tool must provide clear insights or evidence for debugging. Cypress allows screenshots and videos to be captured during test runs, making identifying and fixing issues easier.

This guide will explore how engineers can leverage screenshot testing in Cypress to enhance test stability, debugging, and overall test effectiveness.

What is Cypress Screenshot?

In Cypress, a screenshot is an image capturing the browser’s screen at a specific moment during test execution. Cypress has built-in functionality to automatically capture screenshots, regardless of whether the test is run in interactive mode (using cypress open) or headless mode (using cypress run or as part of a CI pipeline).

The tool is designed to take screenshots automatically when a test fails without needing any additional code. This feature simplifies debugging by providing visual evidence of the application’s state at the time of failure.

Syntax for Cypress Screenshot

Below is the syntax for Cypress Screenshot:

.screenshot()

.screenshot(fileName)

.screenshot(options)

.screenshot(fileName, options)

Or,

cy.screenshot()

cy.screenshot(fileName)

cy.screenshot(options)

cy.screenshot(fileName, options)

What is Screenshot Testing?

Screenshot testing involves capturing a snapshot of a web page or application at a specific point in time. This screenshot is then used to compare against the expected result during future test runs. The purpose is to verify if the visual appearance of elements on the screen is consistent and matches the expected outcome.

For example, imagine testing a table on a webpage. A screenshot of the table is captured, and its contents are verified against the provided data. In future test runs, this captured screenshot is compared with the current screenshot to ensure the content hasn’t changed, without having to manually check the details every time.

Key Benefits of Screenshot Testing:

  • Eliminates Repetitive Verification: Screenshot testing removes the need for testers to manually compare the expected and actual results in each iteration. It automates the process of verifying visual elements, saving time and effort.
  • Easier Comparisons: Instead of manually copying and pasting results for comparison, screenshots offer a visual reference. This method improves the clarity and accuracy of comparison by instantly highlighting any differences.
  • Efficient Testing for Large Applications: For large, complex applications, manually verifying test results can be exhausting. Screenshot testing simplifies the process by automating the comparison and focusing on key visual aspects.

Types of Screenshot Tests:

  1. DOM Snapshot Testing: This captures a screenshot of the Document Object Model (DOM) when the real results are loaded. It allows testers to inspect both the UI components and the underlying code for discrepancies.
  2. Component Snapshot Testing: This method captures the state and contents of specific UI components being tested. By storing these snapshots in a central repository, testers can quickly compare current test results with the reference images for fast, accurate results.
  3. Updating Snapshots: Screenshots need to be updated whenever there are changes to the UI or test flow. Whenever the expected results are modified or a new testing scenario is introduced, the snapshots should be reviewed and updated accordingly to reflect the new expectations.

Naming Conventions used for Cypress screenshots

Cypress follows specific default naming conventions when saving screenshots. These conventions help in organizing screenshots effectively, especially when dealing with multiple tests and runs. Here are the key naming patterns used by Cypress:

  • Default Screenshot Naming: By default, screenshots are saved with a path relative to the screenshots folder, followed by the spec file location, and the test suite and test name. The format looks like:
{screenshotsFolder}/{specPath}/{testName}.png
  • Custom Screenshot Naming: If a custom name is provided for the screenshot, that name is used instead of the default test suite and test name. The format for a named screenshot is:
{screenshotsFolder}/{specPath}/{name}.png
  • Handling Duplicate Screenshots: For duplicate screenshots, Cypress appends a number to differentiate them. The first duplicate screenshot will be named like this:
{screenshotsFolder}/{specPath}/{testName} (1).png
  • Failure Screenshot Naming: When a test fails, Cypress automatically adds “(failed)” to the screenshot’s name, using the default naming convention. The screenshot format in case of failure looks like:
{screenshotsFolder}/{specPath}/{testName} (failed).png

How to Perform Screenshot Testing using Cypress

For this demo, https://bstackdemo.com/ will be used.

The first step is to access the part of the application that needs to be tested and capture the snapshot. For this example, the login page of the dummy site will be used.

Next, the snapshot npm module must be added as a dev dependency using the command:

npm i -D @cypress/snapshot

After that, you need to add this add-on to cypress/support/command.js by inserting the line,

require('@cypress/snapshot').register()

This command will add the snapshot() command to be used.

After that, you can start to script and run the test flow. For this particular scenario, let’s use the login button of the site. Here, let us take a snapshot of the Sign In button and store the snapshot.

When you run the code with Cypress console you can verify the snapshot content by hovering or clicking on the snapshot in the runner.

How snapshot is captured cypress

How the snapshot is captured 

Snapshot captured displayed in Cypress Console

How the snapshot captured is displayed in Cypress Console

Snapshot js content

Snapshot js content

Code Snippet :

/// <reference types="cypress" />


describe('Snapshot test with Cypress', () => {


  beforeEach(() => {



    cy.visit('https://bstackdemo.com')


  })



  it('Take the snapshot of a result', () => {



    /* In here the snapshot that is taken will be refered and accepted by tester and, only after that 

    we can use that snapshot as an comparison component for the test*/

    cy.visit('https://bstackdemo.com/')

    cy.get("#signin").click();

    cy.get("#login-btn").snapshot(); //This snapshot will be referred and compared everytime this runs

    cy.get("#login-btn").click();

  })

})

The repository for this simple can be found here.

Screenshot Testing on Real Devices

Best practices for Screenshot Testing

Here are some best practices to ensure accurate and efficient screenshot testing:

  • Verify the snapshot: Ensure that the captured screenshot meets the expected criteria before proceeding with further testing. This step is crucial to confirming the test’s validity.
  • Update snapshots regularly: Always update snapshots when there are changes in the testing flows or scenarios. This helps in maintaining accurate references for future tests and avoiding failures due to outdated snapshots.
  • Track changes in expected results: If the expected results change, update the snapshots accordingly. This ensures that the testing process remains aligned with the current application state.
  • Utilize testing tools effectively: Platforms like BrowserStack allow easy execution of screenshot testing, reducing time and effort. Combining snapshot testing with Cypress enhances test accuracy and helps detect issues earlier.
  • Ensure iterative test success: By keeping snapshots updated, iterative testing becomes more effective in finding and resolving quality issues in the application.

BrowserStack Automate Banner

Conclusion

Screenshot testing in Cypress offers a powerful and efficient way to validate UI consistency and functionality. By following best practices such as regularly updating snapshots, verifying results, and utilizing testing tools like BrowserStack, teams can streamline their testing process, reduce errors, and ensure higher-quality applications

Talk to an Expert

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
Automation Testing Cypress Testing Tools