How to Perform Screenshot Testing in Cypress

Learn how to perform screenshot testing in Cypress for pages, elements, and behavior changes. Use BrowserStack to run these tests on real browsers and devices, and review screenshots directly in its dashboard.

Guide Banner Image
Home Guide How to Perform Screenshot Testing in Cypress

How to Perform Screenshot Testing in Cypress

Cypress provides built‑in support for capturing screenshots and DOM snapshots during test runs. These tools help you detect unexpected changes to your application’s layout or structure as your code evolves. It also helps spot visual or structural regressions and maintain a more stable test suite.

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

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.

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

Cypress provides a built‑in screenshot() method that can be called either as a chainable command or as a global command. Below is the syntax for each.

As a Chainable Command

.screenshot()

.screenshot(fileName)

.screenshot(options)

.screenshot(fileName, options)

As a Global Command

cy.screenshot()

cy.screenshot(fileName)

cy.screenshot(options)

cy.screenshot(fileName, options)

Each method allows you to capture a screenshot with or without a custom filename and with optional settings.

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

Types of Snapshots in Cypress

Cypress supports two types of snapshots. These approaches serve different testing needs and help you understand how your application changes over time.

1. DOM Snapshots

DOM snapshots capture the structure and state of your page at a specific point during a test. These snapshots are created using the @cypress/snapshot plugin. Instead of capturing an image, this method saves the HTML and text of the element or page.

It allows you to compare its structure between test runs. This is especially useful for verifying that elements, text, and structure remain unchanged across test executions.

2. Image-Based Snapshots

Image-based snapshots are captured using the built‑in cy.screenshot() method in Cypress. These snapshots save an actual image of the page or element and are ideal for identifying visual changes such as layout shifts, font changes, or unexpected rendering issues.

Prerequisites for Cypress Snapshot Testing

Before you can capture screenshots in Cypress, make sure you have the following in place:

  • Install Cypress: Install Cypress as a development dependency if it’s not already added to your project:
npm install cypress --save-dev
  • Set Up a Test Project: Ensure you have a working Cypress project configured. This includes a cypress.config.js or cypress.json file and a cypress directory with test files.
  • Familiarity with the cy.screenshot() Command: Understand the syntax and options available for capturing screenshots, such as filenames and settings like blackout, clip, or capture.
  • Have a Page or Element to Test: Identify a page or specific element you want to capture. This allows you to write focused and meaningful screenshot tests.

How to Perform Screenshot Testing using Cypress

Cypress offers several ways to capture screenshots depending on your testing needs. You can capture an entire page, target a specific element, customize filenames, use built‑in options, and even save screenshots for visual comparisons. Here are the most common methods:

1. Capturing a Full Page Screenshot

Cypress can capture the entire page as it appears during test execution.

Example: The following test captures a full-page screenshot of the BrowserStack demo site.

it('Captures a full page screenshot', () => {

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

  cy.screenshot();

});

This command captures a screenshot of the page as it appears and saves it to the cypress/screenshots directory.

2. Capturing a Specific Element

Cypress allows capturing only a specific element by selecting it first.

Example: This test captures a screenshot of the Sign In button.

it('Captures a specific element screenshot', () => {

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

  cy.get('#signin').screenshot();

});

This command captures only the #signin element and saves the screenshot as an image.

3. Using cy.screenshot() for Custom Filenames

Cypress supports custom names for screenshots, making them easy to locate and review.

Example: The test captures the Sign In button and saves the screenshot with a custom filename.

it('Captures a screenshot with a custom filename', () => {

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

  cy.get('#signin').screenshot('sign_in_button');

});

This command saves the screenshot of the Sign In button as sign_in_button.png in the screenshots directory.

4. Using Screenshot Options

Cypress provides advanced options like blackout, capture, and scale to give users more control over screenshots. These options can be used individually or combined, depending on the test requirements.

Option 1: blackout

This option allows certain elements to be hidden when capturing a screenshot.

Example:

it('Captures a screenshot with a blacked out element', () => {

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

  cy.screenshot({ blackout: ['#header'] }); 

});

The #header element is hidden from the screenshot, making it ideal for ignoring dynamic or irrelevant sections.

Option 2: capture

This option specifies the area of the page to capture. It can be set to viewport (visible area) or fullPage.

Example:

it('Captures only the viewport area', () => {

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

  cy.screenshot({ capture: 'viewport' }); 

});

This captures only the visible area of the page (without scrolling) and makes the screenshot focused and concise.

Option 3: scale

This option increases the pixel density of the screenshot, making it crisp and suitable for review on high‑resolution displays.

Example:

it('Captures a scaled screenshot', () => {

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

  cy.screenshot({ scale: true }); 

});

This captures a higher‑quality page version and is ideal for comparing subtle design changes.

5. Capturing Screenshots for Behavioral Changes

Screenshot testing can also be used to confirm visual changes caused by user interactions.

Example: This test captures a screenshot after clicking the Sign In button.

it('Captures a screenshot after an interaction', () => {

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

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

  cy.screenshot('after_sign_in_click');

});

This command captures the page state after clicking the Sign In button, making it easy to review changes resulting from the interaction.

6. Running the Test and Viewing Results

Tests can be run in Cypress, and the results can be reviewed in the screenshots directory.

Example: The command below runs the test and saves screenshots to the cypress/screenshots directory.

npx cypress run

This command executes the test in headless mode, captures screenshots, and saves them in the cypress/screenshots directory for review.

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

How BrowserStack Enhances Cypress Screenshot Testing

BrowserStack is a cloud-based testing platform that enables Cypress tests to be executed on real browsers and devices over the internet. It captures screenshots, videos, logs, and other artifacts directly within its dashboard, making it ideal for cross-browser visual testing and debugging.

Here’s how to use BrowserStack Automate for Cypress testing.

1. Install BrowserStack CLI

Install the BrowserStack Cypress CLI, which links your local Cypress setup to the cloud:

npm install -g browserstack-cypress-cli

This command provides access to commands like browserstack-cypress init and run –sync

2. Initialize Configuration

Generate a baseline browserstack.json file in your project root:

browserstack-cypress init

This file includes placeholders for your BrowserStack username, access_key, target browsers, and other required settings.

3. Update browserstack.json

Open the file and edit the placeholders:

{

  "auth": {

    "username": "YOUR_USERNAME",

    "access_key": "YOUR_ACCESS_KEY"

  },

  "browsers": [

    { "browser": "chrome", "os": "Windows 10", "versions": ["latest"] },

    { "browser": "firefox", "os": "OS X Mojave", "versions": ["latest"] }

  ],

  "run_settings": {

    "cypress_config_file": "cypress.config.js",

    "project_name": "Your Project Name",

    "build_name": "Build #1",

    "parallels": 3

  }

}

Note: Add or change browser entries and adjust parallels to match your test plan.

4. Serve Your Application

Ensure your app is running locally before triggering tests:

npm start

By default, BrowserStack connects to port 3000, or update your config to match your server.

5. Execute Cypress on BrowserStack

Run your tests on the cloud with screenshots and logs automatically synchronized:

browserstack-cypress run --sync

This command runs tests remotely, captures screenshots and videos, and syncs artifacts to your local build_artifacts folder.

6. View Dashboard Results

On BrowserStack’s Automate dashboard:

  • Open a test session
  • Navigate to the Screenshots tab to view captured images
  • Watch recorded videos and logs
  • Examine timestamps and browser metadata

7. (Optional) Run Tests Locally

To preview screenshots before launching cloud tests, execute tests locally via Cypress:

npx cypress open

Run spec files like screenshot_full_spec.js, screenshot_element_spec.js, or screenshot_options_spec.js, and inspect screenshots in cypress/screenshots.

Talk to an Expert

Conclusion

Cypress screenshot testing makes it straightforward to capture and review an application’s visual state. By using built‑in methods like cy.screenshot() and leveraging its options, you can spot layout changes, broken elements, and unexpected behavior across test runs.

With BrowserStack, Cypress screenshot tests can be taken beyond the local environment. It gives access to over 3,500+ real browsers and devices. This makes it easier to run Cypress screenshot testing at scale and review results in a central, cloud‑based dashboard.

Try BrowserStack for Free

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
Automation Testing Cypress Testing Tools

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord