Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Cypress Visual Regression: Baseline Screenshots Guide

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through capturing baseline screenshots for visual regression tests in Cypress. Visual regression testing compares screenshots of your UI against a stored baseline to catch unintended visual changes. By the end, you'll have a repeatable process for generating and managing these baseline images using Cypress and the cypress-image-diff plugin.

What You'll Need

  • A working Cypress project (Cypress 10 or later recommended).
  • Node.js and npm installed.
  • Basic familiarity with Cypress test structure.
  • The cypress-image-diff plugin installed (see Step 1).

Step-by-Step

  1. Install the plugin
    In your project root, run: npm install cypress-image-diff --save-dev. This plugin provides the commands and configuration needed for visual comparisons.
  2. Configure Cypress to use the plugin
    In your cypress.config.js (or cypress.config.ts), add the plugin setup. For Cypress 10+, you'll need to import the plugin and register it in the setupNodeEvents function. Example:
    const { defineConfig } = require('cypress');
    const { addCypressImageDiffPlugin } = require('cypress-image-diff');
    
    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          addCypressImageDiffPlugin(on, config);
          return config;
        },
      },
    });
  3. Import the commands in your support file
    In cypress/support/e2e.js (or your support file), add: import 'cypress-image-diff/commands'; This makes the cy.compareVisual command available.
  4. Write a test that uses visual comparison
    Create a spec file, e.g., visual.spec.js. Inside a test, visit a page and call cy.compareVisual('homepage'). Example:
    describe('Visual Regression', () => {
      it('should match the homepage baseline', () => {
        cy.visit('/');
        cy.compareVisual('homepage');
      });
    });
    The first argument is a unique name for the screenshot.
  5. Run the test to generate baselines
    Run npx cypress run (or npx cypress open and run the test). On the first run, the plugin will detect no baseline exists and create one automatically. It will save the image in the cypress-visual-screenshots/baseline/ directory by default.
  6. Verify the baseline was created
    Check the cypress-visual-screenshots folder. You should see a subfolder baseline containing the screenshot with the name you provided (e.g., homepage.png).
  7. Commit the baseline to version control
    Add the cypress-visual-screenshots/baseline folder to your repository. This ensures all team members and CI environments use the same baseline.
  8. Run the test again to confirm it passes
    Run the test a second time. This time, the plugin compares the current screenshot to the baseline. If they are identical, the test passes. If there are differences, it will fail and save diff images in cypress-visual-screenshots/diff/.

Common Mistakes

  • Not committing baselines: If you don't commit the baseline folder, each developer will generate their own baseline, leading to false failures.
  • Ignoring dynamic content: Timestamps, random IDs, or animated elements cause flaky tests. Freeze or mock these before taking the screenshot.
  • Running tests in different environments: A baseline captured on a Mac with different fonts will differ on a Linux CI. Use consistent environment settings or Docker.
  • Using the same name for different pages: If you reuse a screenshot name across tests, the baseline will be overwritten or mismatched.

Tips

  • Set a viewport: Always set cy.viewport(width, height) before the comparison to ensure consistent dimensions.
  • Wait for network idle: Use cy.intercept to wait for API calls or use cy.wait(0) after page load to avoid capturing mid-load states.
  • Use a dedicated baseline branch: When updating baselines intentionally, create a separate branch and merge after review.
  • Leverage the plugin's failure output: The diff images help you see exactly what changed, making debugging easier.

Troubleshooting

Test fails on first run but passes on second
This is normal—the first run creates the baseline, the second compares. If you want the first run to pass, you can run with --env updateSnapshots=true to force updating baselines.

Baseline not created
Check that the plugin is correctly configured in setupNodeEvents. Also ensure you've imported the commands in the support file. If using TypeScript, verify your tsconfig includes the plugin types.

Diff images show whole page as different
This often happens due to scroll position or viewport differences. Ensure you're not scrolling before the screenshot, and set a fixed viewport.

Fonts render differently on CI
Install the same fonts on CI, or use a Docker image with a known font setup. Alternatively, set a tolerance threshold in the plugin configuration.

The command cy.compareVisual is not recognized
Re-check that you've added import 'cypress-image-diff/commands'; to your support file and that the plugin is installed.

Frequently Asked Questions

Can I use Cypress's built-in screenshot command instead?

Yes, but you'd need to write custom comparison logic. The plugin simplifies the process with built-in diffing and reporting.

How do I update a baseline intentionally?

Run the test with the environment variable UPDATE_SNAPSHOTS=true (or updateSnapshots=true depending on your plugin version). This overwrites the baseline with the current screenshot.

What if my page has animations?

Disable CSS animations in your test by injecting a style tag that sets animation: none !important before the screenshot.

Can I compare only a specific element?

Yes, pass a selector as the second argument: cy.compareVisual('header', { selector: 'header' }). The plugin will capture only that element.

How do I ignore a small area that changes frequently?

Use the ignoreAreas option in the plugin configuration to specify rectangles to exclude from comparison.

Is visual regression testing slow?

It can be, especially with many screenshots. Run visual tests in a separate spec file and consider using parallelization or running them only on a schedule.