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 DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk6 min

How to Test a Web App in Offline Network Mode With Cypress

Use Chrome DevTools Protocol emulation to test a Cypress app while the browser is offline, or use cy.intercept() to fail one request. Includes cleanup and troubleshooting guidance.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To test a web app as genuinely offline in Cypress, use Chrome DevTools Protocol network emulation: enable the Network domain, set offline: true, and assert both the browser’s offline state and the app’s visible behavior. Restore network access in cleanup hooks so a failed test cannot leave the browser offline. For a single failed API call rather than whole-browser offline behavior, use cy.intercept() with forceNetworkError: true.

Choose the failure you need to test

Test goal Technique Useful assertion
Exercise app behavior that depends on the browser being offline, including navigator.onLine or online/offline event handling Emulate offline network conditions through the Chrome DevTools Protocol Check navigator.onLine, the app’s offline indicator, and the visible result of an operation that needs the network
Make one matching browser request fail while leaving other traffic available cy.intercept() with forceNetworkError: true Assert the app’s user-facing result and that the aliased request has an error property

These approaches test different things. A forced request error does not, by itself, make the browser report that it is offline. Conversely, browser-wide offline emulation can affect more than the one request relevant to a focused error-handling test.

As an Amazon Associate I earn from qualifying purchases.

Emulate browser-wide offline mode

Cypress’s offline recipe uses Cypress.automation('remote:debugger:protocol', ...) to send Chrome DevTools Protocol commands. The calls return promises, so chain them from Cypress commands such as .then() rather than starting them without waiting.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Reusable Cypress commands

Add helpers such as these to your Cypress support file or spec. Enable the Network domain before emulating conditions; when restoring, bring the browser online before disabling the domain.

const setOffline = () => {
  return Cypress.automation('remote:debugger:protocol', {
    command: 'Network.enable',
    args: {},
  }).then(() => {
    return Cypress.automation('remote:debugger:protocol', {
      command: 'Network.emulateNetworkConditions',
      args: {
        offline: true,
        latency: 0,
        downloadThroughput: 0,
        uploadThroughput: 0,
      },
    });
  });
};

const setOnline = () => {
  return Cypress.automation('remote:debugger:protocol', {
    command: 'Network.emulateNetworkConditions',
    args: {
      offline: false,
      latency: 0,
      downloadThroughput: 0,
      uploadThroughput: 0,
    },
  }).then(() => {
    return Cypress.automation('remote:debugger:protocol', {
      command: 'Network.disable',
      args: {},
    });
  });
};

Test offline behavior and recovery

Replace the URL, selectors, and expected messages with those from your application. The example first visits while online, then makes the browser offline, checks the browser state, and exercises an action that fetches data.

describe('offline behavior', () => {
  beforeEach(() => {
    // Recover from state left by an earlier test before visiting the app.
    setOnline();
  });

  afterEach(() => {
    // Cleanup also runs when a test fails.
    setOnline();
  });

  it('shows an offline error and recovers when connectivity returns', () => {
    cy.visit('/users');

    setOffline().then(() => {
      cy.window().its('navigator.onLine').should('equal', false);
    });

    cy.contains(/offline/i).should('be.visible');
    cy.get('[data-cy=fetch-users]').click();
    cy.contains('Could not fetch users').should('be.visible');

    setOnline().then(() => {
      cy.window().its('navigator.onLine').should('equal', true);
    });

    cy.get('[data-cy=fetch-users]').click();
    cy.get('[data-cy=user-list]').should('be.visible');
  });
});

The sample assertions are illustrative: choose selectors and messages that reflect your app. If your application updates its offline indicator only in response to an offline event, assert that UI after switching state as well as checking navigator.onLine. Test recovery through the same user action or workflow users rely on.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Test one request failure with cy.intercept()

Use an intercept when the question is whether a particular API failure is handled correctly, not whether the app observes a browser-wide offline state. Register the route before visiting if initialization sends the request immediately; otherwise, register it before the action that triggers the request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.intercept('GET', '/api/users', { forceNetworkError: true }).as('getUsers');
cy.visit('/users');

cy.get('[data-cy=fetch-users]').click();
cy.wait('@getUsers').should('have.property', 'error');
cy.contains('Could not fetch users').should('be.visible');

forceNetworkError forces an error for the matched intercepted request. This is useful for testing a request-level failure path, but do not use it as evidence that navigator.onLine becomes false.

Account for cache and request timing

  • A resource served from the browser cache may never reach the network layer, so an intercept may not see it. If your route does not fire, check whether the request was cached and whether the URL and method match.
  • Register intercepts before cy.visit() when app startup can issue the request. Registering after the request has already started is too late to observe that request.
  • cy.request() runs from Cypress’s Node process, not from the browser. Use it for direct API testing where appropriate, but not as a substitute for observing an app-originated browser request.

Restore state reliably

An offline browser can disrupt Cypress’s communication with the test runner. Restore connectivity before and after each test, including after a failure. A setup hook protects a test from state left by an earlier test; a teardown hook prevents the current test from leaking state to the next one.

  1. Before the test, set the browser online and disable network emulation.
  2. Visit the app in its expected starting state.
  3. Switch offline only for the portion of the test that needs it.
  4. Restore online conditions as soon as offline assertions are complete.
  5. In teardown, restore online conditions again so failures do not leave the browser disconnected.

If you use Cypress hooks, ensure the hook itself waits for the returned automation promise. Where browser or Cypress behavior makes teardown unreliable, keep the offline interval short and restore connectivity within the test immediately after the offline assertions, as well as using hooks for recovery.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Browser and Cypress version considerations

The detailed Cypress offline recipe was published November 12, 2020 and uses Chrome Debugger Protocol commands. It says the example does not run in Firefox and identifies Electron, Chrome, and Edge as compatible at that time. Cypress 16’s networking documentation describes native interception for Chrome, Chromium, and Edge, with Firefox, WebKit, and Electron using the legacy network path. Those statements concern related but distinct networking capabilities; they do not establish identical offline-emulation behavior across every current browser and Cypress combination.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Run the offline test on the Cypress and browser versions pinned by your project before relying on it in CI.
  • If your suite targets several browsers, gate this protocol-based test where needed and retain browser-independent tests for the app’s visible error and recovery behavior.
  • Prefer assertions about application behavior—rendered errors, offline indicators, or response outcomes—over transport metadata that can vary between network paths.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

The test runner stops responding or the run fails after switching offline

Restore the browser to online conditions before continuing. Keep network emulation active only while checking offline behavior, and use both setup and teardown cleanup. Confirm that your test waits for each automation promise.

navigator.onLine remains true

Check that Network.enable completed before the emulation command and that the automation call is being run in a supported browser/version combination. The detailed recipe is based on Chrome Debugger Protocol; do not assume equivalent behavior in every browser.

The app does not show its offline state

Check which signal the app uses. Some interfaces react to online/offline events or update only after an attempted request. Assert the browser state and then trigger the network-dependent action; do not assume that a status indicator will change merely because an API call fails.

The intercept never matches

Confirm the URL pattern and method, register the intercept before the request begins, and check whether the browser served a cached response. A request issued during initialization requires the intercept to be registered before cy.visit().

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

An assertion on an intercepted request differs across browsers

Network handling paths can differ by browser. Focus on the app’s rendered outcome where possible, and verify transport-specific assertions against each browser/version you actually run.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a replacement for Cypress offline-behavior tests. It can capture a page when you need a screenshot artifact without configuring a browser capture flow yourself. A single GET request returns a PNG, JPEG, WebP, or PDF; for example, this cURL call saves a WebP screenshot:

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

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.

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.

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

Leave a Reply

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

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.