DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

How to Reduce Flaky Visual Regression Tests Caused by Network Requests

Mock the requests that define a visual state, assert the expected UI before capture, and keep real-backend integration tests separate.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make the data and the capture point predictable: mock the requests that determine the visual state, wait for the expected UI to appear, and take the screenshot only after that assertion passes. A request finishing is useful evidence, but it does not guarantee that the application has finished rendering. Keep separate integration tests for behavior that depends on the live backend.

Why network requests make visual tests flaky

A screenshot records a page at one moment. If a response varies between runs, or the capture happens before network-driven updates finish, the same test can produce different images without any change to the frontend code. Cypress summarizes the issue plainly: “Real API responses change over time, which makes screenshots change too.” Cypress Documentation: Visual testing in Cypress.

As an Amazon Associate I earn from qualifying purchases.

Typical causes include API data that changes, delayed responses, UI updates that run after a response arrives, and third-party content outside the test’s control. The fix is not simply to wait longer. Decide which state the screenshot is meant to verify, make its inputs stable, and verify that state before capturing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose what the visual test should prove

Known frontend state

If the question is whether a component renders correctly for a particular response, route the relevant request to a stable fixture. This makes the test repeatable and isolates presentation from changes in live data.

#1 Best Overall
Sale
Pearson Computer Networking, 8E
  • brand: Pearson
  • Computer Networking, 8e

Live integration behavior

If the question is whether the service returns the right data, a mocked response cannot answer it. Keep separate integration coverage that exercises the real backend. Stubbing improves determinism by narrowing what the visual test proves; it does not validate the production API’s current behavior.

Stabilize the request and capture sequence

  1. Identify the relevant request. Find the API call or calls that directly determine the component or page state in the screenshot. Avoid intercepting unrelated traffic indiscriminately.
  2. Return an explicit fixture. Use data that represents the state under test—such as a populated list, empty state, or error—and keep it stable across runs.
  3. Reach the state deliberately. Use the normal user action or setup path that should produce the state. Wait for the relevant intercepted response if it helps coordinate the test.
  4. Assert the visible result. Check for the expected text, element, or state after the response. A completed request does not by itself prove the application has finished updating the UI.
  5. Capture after the assertion. Take the snapshot only once the intended state is observable. Do not use a fixed sleep as the sole readiness check.
  6. Keep the screenshot focused. Prefer a meaningful component or page state over a broader capture when unrelated content adds noise. Mask only the smallest region that truly cannot be controlled.

“Network idle” is not a universal readiness signal: polling or long-lived requests can prevent idleness, while an idle page may still not show the expected application state. Use a state assertion as the deciding condition.

Cypress: intercept a request and wait for the UI

Cypress documents using cy.intercept() with fixture data, waiting for an aliased request, and checking the intended UI before taking a snapshot. Adapt this example to your visual-testing command or snapshot integration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
describe('items visual state', () => {
  it('renders the known items response', () => {
    cy.intercept('GET', '/api/items', { fixture: 'items.json' }).as('getItems');

    cy.visit('/items');
    cy.wait('@getItems');
    cy.get('[data-testid="item-list"]').should('be.visible');
    cy.contains('[data-testid="item-list"]', 'Example item').should('be.visible');

    // Call the snapshot command used by your visual-testing integration here.
  });
});

The fixture should contain the exact state the test intends to compare. The request wait coordinates the network step; the UI assertions establish that the relevant content is present. Cypress’s visual-testing guidance also recommends capturing after the page has stopped changing and checking a functional condition. Cypress visual testing guidance.

Playwright: route the request in the test context

Playwright supports routing and mocking with browserContext.route() or page.route(). A context-level route can be set before creating or navigating the page, so the response is controlled from the start:

import { test, expect } from '@playwright/test';

 test('renders a stable items state', async ({ browser }) => {
  const context = await browser.newContext();
  await context.route('**/api/items', async route => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify([{ id: '1', name: 'Example item' }]),
    });
  });

  const page = await context.newPage();
  await page.goto('/items');
  await expect(page.getByTestId('item-list')).toContainText('Example item');
  // Capture the screenshot here, after the state assertion.
  await context.close();
});

In a real project, retain your configured Playwright fixture and base URL rather than creating a separate context solely for this example. Playwright’s official guide documents both routing methods and notes a Service Worker caveat: if native route handling does not see requests, block Service Workers in the context with serviceWorkers: 'block'. Playwright network documentation.

Keep rendering conditions consistent

Once the response and UI state are stable, reduce unrelated sources of screenshot differences:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Use a consistent browser and operating-system environment where practical.
  • Keep viewport dimensions and device scale consistent; font availability can also affect layout and wrapping.
  • Disable or settle animations before capture. Cypress cautions that waiting for animation during an action does not stop an unrelated animation elsewhere from appearing mid-frame.
  • Control content you own; for a small, genuinely uncontrolled third-party region, mask only that region rather than widening the allowed difference across the image.

These controls matter because a rendering-environment change can produce a visual diff unrelated to the application change being tested.

Troubleshoot failures that remain

The fixture is not being used

Confirm the route pattern matches the actual request method and URL, register the route before navigation or the triggering action, and check whether the request is made by a different origin or path than expected. In Playwright, check whether a Service Worker is intercepting traffic; its network guide recommends blocking Service Workers when native routing needs to observe and handle requests.

The request passed but the screenshot is still early

Add an assertion for the actual rendered state—such as expected text, a visible component, or a loading indicator disappearing—and capture only after it succeeds. Do not treat response completion as proof that all application updates have completed.

The screenshot changes despite stable data

Check viewport, browser and operating-system consistency, fonts, and animations. Inspect whether a small third-party element is changing independently; control it if it is within scope, or mask only that region if it is not.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You need to diagnose intermittent runs

Review the request outcome and timing alongside the screenshot and DOM state. Chromatic documents unstable-test diagnostics that include network requests, console logs, DOM snapshots, and snapshot metadata. Those traces can help identify whether the cause is variable data, timing, or rendering rather than a code regression. Chromatic flaky-test documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Where visual-testing services fit

Managed visual-testing and review tools can help organize snapshots and investigate unstable runs, but they are optional: the cited documentation does not establish that a service is required to make network responses deterministic. Cypress lists integrations including Argos, Chromatic, Percy, Sauce Labs Visual, and SmartBear VisualTest; that list is an example of integrations mentioned in its documentation, not an endorsement. Cypress visual testing guidance. Chromatic also documents Playwright integration and resource archive timing configuration. Chromatic Playwright documentation.

Or skip the browser setup

For an on-demand screenshot rather than a test-controlled browser session, ScreenshotNeo provides a screenshot API and MCP server. One GET request returns an image or PDF; the API also accepts parameters used by other screenshot APIs.

cURL (see the ScreenshotNeo API documentation):

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

It can accept cookie or consent banners and remove 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 are not billed, with the page verdict and billing status reported in response headers. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—let AI agents use it through an MCP client. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up free for 1,000 screenshots a month, with no card required.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.