ScreenshotNeo

BlogHow-to

How to Fix Cypress Screenshot Comparison Failures

Fix Cypress screenshot diffs by separating real UI changes from flaky captures, then stabilize state, timing, rendering, and baselines.

By the ScreenshotNeo team30 September 202611 min read

How to Fix Cypress Screenshot Comparison Failures

A Cypress screenshot comparison failure means that the captured pixels differ from a baseline. It does not, by itself, prove that the product is broken. Cypress captures screenshots; a plugin or hosted visual-testing service compares them and manages baselines. First decide whether the difference is an intended application change. If it is not, make the captured state deterministic: wait for the UI you care about, control API data and time, remove transient animation, use a fixed viewport and rendering environment, and capture the smallest useful boundary.

Cypress documents visual testing as a separate comparison layer and documents cy.screenshot() as the capture command. Read the visual testing guide and the screenshot command API for version-specific behavior.

1. Classify the failure before changing anything

Open the diff, the actual image, and the expected baseline. Identify the shape of the change:

Diff pattern Likely cause First action
Large, coherent layout or color change Intentional UI change or a real regression Compare the change with the product requirement and recent commits.
Text, prices, dates, counters, or avatars change Live or random data Stub the response, seed fixed data, or freeze the clock.
Only a spinner, transition, cursor, or skeleton differs Capture occurred during transient rendering Assert the settled state and disable or await the specific animation.
Fonts wrap differently or every text edge changes Different browser, operating system, font files, scale, or viewport Run comparison and baseline generation in the same pinned environment.
Only the bottom or a lazy image differs Capture boundary or lazy loading Use the intended full-page behavior and wait for the relevant content.
Intermittent, different region on each run Race condition, network dependency, or nondeterministic app state Reproduce repeatedly and remove the source of variation; do not simply approve a random baseline.

A pixel difference is evidence to investigate, not an automatic product bug. Approve a new baseline only after confirming that the visual change is intentional.

2. Make the application state explicit

Screenshot commands are asynchronous. The page can change between issuing the command and the actual capture, and a screenshot does not retry chained assertions. Keep assertions that establish the state in separate commands immediately before the capture.

A stable visual test controls data, time, rendering, and the comparison boundary.
A stable visual test controls data, time, rendering, and the comparison boundary.
describe('checkout summary', () => {
  it('captures the loaded summary', () => {
    cy.intercept('GET', '/api/cart', {
      fixture: 'cart.json'
    }).as('cart');

    cy.visit('/checkout');
    cy.wait('@cart');

    // Assert the state the image depends on.
    cy.get('[data-testid="checkout-summary"]')
      .should('be.visible')
      .and('contain', 'Subtotal');
    cy.get('[data-testid="loading-spinner"]')
      .should('not.exist');

    cy.screenshot('checkout-summary');
  });
});

Prefer a meaningful condition over an arbitrary sleep. A fixed delay can hide a race on a fast machine and still be too short on a slow one. If a transition has a known end state, assert that state or wait for the specific transition rather than adding a large global delay.

Control API responses and test data

Use cy.intercept() with fixtures or explicit response bodies for APIs that affect pixels. Seed the database with stable records when stubbing is not appropriate. Remove random IDs, rotating recommendations, current weather, ad slots, and third-party content from the visual-test path.

cy.intercept('GET', '/api/profile', {
  statusCode: 200,
  body: {
    name: 'Ada Lovelace',
    plan: 'Team',
    avatarUrl: '/fixtures/ada.png'
  }
}).as('profile');

cy.visit('/account');
cy.wait('@profile');
cy.get('[data-testid="profile-card"]').should('contain', 'Ada Lovelace');
cy.screenshot('profile-card');

Freeze time when time is visible

Dates, countdowns, relative timestamps, and time-based feature flags can change between the baseline and the comparison. Freeze the browser clock before visiting the page and advance it deliberately when the test needs another point in time.

it('renders the fixed renewal date', () => {
  cy.clock(new Date('2026-01-15T12:00:00Z').getTime());
  cy.visit('/billing');
  cy.get('[data-testid="renewal-date"]').should('contain', 'Jan 15');
  cy.screenshot('billing-renewal');
});

If the application reads time on the server, control that value in the API fixture as well; freezing only the browser clock cannot change a timestamp already returned by the server.

3. Stabilize animation, transitions, and lazy rendering

Cypress screenshot capture documents disableTimersAndAnimations as enabled by default for screenshot capture. That setting does not guarantee that every page animation, CSS transition, canvas animation, video, or asynchronous rendering step has stopped. Cypress actionability options such as waitForAnimations and animationDistanceThreshold apply to action commands such as clicks; they are not a universal visual snapshot freeze.

For a visual-test route, add a stylesheet that disables transitions and animations you do not intend to verify:

/* visual-test.css */
*, *::before, *::after {
  animation-duration: 0s !important;
  animation-delay: 0s !important;
  transition-duration: 0s !important;
  transition-delay: 0s !important;
  caret-color: transparent !important;
}

Load that stylesheet only in the test environment or inject equivalent CSS in a controlled test hook. Do not hide an animation that is itself the feature under test. For a carousel, video, canvas, or WebGL scene, pause it at a known frame or replace it with deterministic test content.

Lazy-loaded images need both a stable source and a settled capture point. Assert that the image has loaded before taking the screenshot:

cy.get('[data-testid="hero-image"]')
  .should('be.visible')
  .and(($img) => {
    expect($img[0].complete).to.equal(true);
    expect($img[0].naturalWidth).to.be.greaterThan(0);
  });
cy.screenshot('hero');

4. Make rendering conditions match

Pixel comparisons are sensitive to the renderer. Generate baselines and compare them with the same operating-system image, browser version, installed fonts, viewport, device scale, locale, timezone, and color behavior whenever possible. A baseline produced on a laptop can differ from one produced in a CI container even when the DOM is identical.

Cypress documents a default viewport of 1000 × 660 pixels. Those are defaults, not universal targets. Set the dimensions your product supports explicitly:

// cypress.config.js
const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    viewportWidth: 1440,
    viewportHeight: 900,
    video: false
  }
});

You can also set dimensions for one test with cy.viewport(1440, 900). Keep browser versions pinned in CI, install the exact web fonts used by the application, and avoid comparing screenshots made at different display scales. Set locale and timezone explicitly when formatted text depends on them.

5. Choose the right screenshot boundary

A full-page screenshot can expose unrelated changes in navigation, recommendations, ads, or content below the component you are testing. Capture the smallest boundary that answers the test question:

  • Element: best for a component or isolated state.
  • Viewport: useful for a page-level composition at a fixed size.
  • Full page: useful for a document or route where below-the-fold layout matters.
  • Runner: useful for debugging the Cypress command itself, rarely ideal as a product baseline.
cy.get('[data-testid="pricing-card"]').screenshot('pricing-card');
cy.screenshot('dashboard-viewport');
cy.screenshot('dashboard-full-page', { capture: 'fullPage' });

The available capture options and accepted values can vary by Cypress version and by the comparison integration. Check the current Cypress.Screenshot API and your plugin or service documentation before copying an option into a shared configuration.

6. Handle dynamic regions without hiding real regressions

If a clock, rotating ad, live chart, or third-party avatar cannot be made deterministic, isolate it. Prefer a narrow mask or blackout supported by your comparison tool over raising a threshold for the entire page. A global threshold can conceal a real spacing, color, or typography regression.

Before masking, ask whether the content can instead be replaced with a fixture, a local asset, or a test-only endpoint. Keep the mask selector as small and documented as possible, and review it when the component changes.

7. Review and update baselines safely

  1. Inspect the diff and identify every changed region.
  2. Trace each region to an application commit, data change, rendering change, or capture race.
  3. Run the test again in the same environment to check whether the output is repeatable.
  4. For an intended design change, update the baseline using the comparison tool’s documented approval workflow.
  5. Commit the new baseline with the code change and a useful explanation.

Cypress retries are disabled by default. A passing retry can reveal flakiness, but it does not prove that a newly captured appearance is correct. Use retries as a diagnostic signal, then fix the nondeterministic cause. See Cypress’s test retries guide.

8. A complete deterministic Cypress example

describe('orders page visual check', () => {
  beforeEach(() => {
    cy.clock(new Date('2026-02-01T10:00:00Z').getTime());

    cy.intercept('GET', '/api/orders*', {
      fixture: 'orders.json'
    }).as('orders');

    cy.intercept('GET', '/api/notifications', {
      statusCode: 200,
      body: { unread: 0 }
    }).as('notifications');

    cy.visit('/orders');
    cy.wait(['@orders', '@notifications']);

    cy.get('[data-testid="orders-table"]').should('be.visible');
    cy.get('[data-testid="orders-loading"]').should('not.exist');
  });

  it('captures the stable table', () => {
    cy.viewport(1440, 900);
    cy.get('[data-testid="orders-table"]')
      .screenshot('orders-table');
  });
});

This example separates synchronization from capture, fixes time, controls API data, sets the viewport explicitly, and scopes the image to the table. Add the comparison command required by your selected plugin or service after the capture step; Cypress itself does not provide the image-comparison layer.

9. Troubleshooting common failures

Symptom or error Cause Fix
“Timed out retrying” before the screenshot The asserted element never reached the expected state, often because an API request failed or the selector is wrong. Inspect the command log and network request, assert the correct loading and success states, and fix or stub the dependency.
Screenshot contains a spinner or skeleton Capture ran before data rendering completed. Wait for the aliased request and assert that the loading element is gone.
Only dates or countdowns differ Browser or server time changed. Use cy.clock() and return fixed timestamps from fixtures.
Text is shifted or wrapped differently Viewport, font, browser, OS, or device scale differs. Pin the environment, install the same fonts, and set viewport dimensions explicitly.
Diff appears only in CI CI uses a different container, browser build, font set, locale, or timezone. Run baseline generation and comparison in the same CI image and print environment details in diagnostics.
Diff moves between runs Uncontrolled network data, random values, animation, or race condition. Stub data, freeze time, disable the relevant animation, and assert the settled state. Do not approve intermittent output.
Full-page capture differs below the fold Lazy content or unrelated page changes are included. Wait for required images, or capture the component or viewport that the test actually owns.
Changing waitForAnimations has no effect That option concerns actionability, not every animation during screenshot capture. Disable or await page animation separately and use the screenshot API’s documented options where appropriate.
Comparison command is undefined The comparison plugin is not installed or its command was not registered. Check the plugin’s current installation and support files; Cypress only supplies capture.
Baseline approval hides later bugs An expected-looking diff was approved without checking all regions. Review the complete diff, connect it to an intentional change, and keep masks narrow.

10. Performance, reliability, and cost

  • Capture fewer pixels: element screenshots are faster and produce less review noise than full-page images when the component is the unit under test.
  • Control network work: fixtures reduce latency and remove external variability. Keep one focused test for real integration behavior rather than making every visual test depend on live services.
  • Reuse setup: authenticated sessions and deterministic seed data reduce repeated login and setup time, provided the session itself is stable.
  • Keep baselines reviewable: store images with the code or in the comparison service according to the chosen workflow, and retain the diff artifact for failures.
  • Use retries carefully: retries can expose flaky output but add runtime and do not repair nondeterminism.
  • Budget for hosted comparison: hosted services may provide managed rendering, dashboards, pull-request review, or broader browser coverage. Confirm current pricing, browser matrix, retention, and data-handling terms before choosing one.

Cypress’s visual-testing guide lists local plugins and hosted services as different workflow choices. Compare baseline ownership, rendering consistency, browser coverage, review flow, data handling, integration fit, and current price. The guide names Cypress Image Diff, Cypress Image Snapshot, Cypress Visual Regression, Visual Regression Diff, Pixeleye, Applitools, Argos, Chromatic, and Sauce Labs Visual; verify each project’s current commands and terms before implementation.

11. Or skip the browser setup

When the goal is a clean screenshot of a URL rather than an in-browser interaction test, ScreenshotNeo provides a single GET request that returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers.

Transient consent and overlay elements can change the pixels that a screenshot captures.
Transient consent and overlay elements can change the pixels that a screenshot captures.

See the ScreenshotNeo API documentation for options such as full-page capture, CSS-element capture, dark mode, device presets, retina scale, custom CSS and JavaScript, waits, request blocking, headers, cookies, user agents, timezone and geolocation, caching, signed links, asynchronous jobs, webhooks, bulk capture, and usage reporting.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', bytes);

ScreenshotNeo also has an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan.

Create a free ScreenshotNeo account to get 1,000 screenshots a month without a card.

12. FAQ

Does Cypress compare screenshots by itself?

No. Cypress captures images; a plugin or external visual-testing service performs comparison and baseline review.

Should I increase the diff threshold?

Only when you understand the rendering noise and your comparison tool documents the setting. Fix state and environment first, and avoid a global threshold that can hide real regressions.

Why does a screenshot fail even though the test passes?

Functional assertions can pass while pixels vary because of time, data, fonts, animation, viewport, browser, or capture boundary. Add deterministic setup and a state assertion immediately before capture.

Are Cypress failure screenshots visual baselines?

No. Cypress can automatically capture diagnostic screenshots for failed tests during cypress run, but those images are not automatically baseline comparisons.

When should I use a full-page screenshot?

Use it when the document’s below-the-fold layout is part of the requirement. Otherwise, an element or viewport capture usually gives a more focused and stable signal.

Can retries fix visual flakiness?

Retries can reveal that output is nondeterministic. They do not establish which appearance is correct or remove the underlying race.