Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 35 ยท Network and Data

Intercepting and Mocking Network Requests

Learn to intercept network requests with cy.intercept and page.route: stub responses, simulate errors and slow replies, and wait for requests in your tests.

Your web app talks to servers, and servers are the least predictable part of an end-to-end test. They can be slow, empty, down, or full of data that changes every day. Both Cypress and Playwright can sit between the page and the network: they intercept a request, and then either answer it themselves (a stub or mock), change it, let it through, or make it fail. This gives you control over exactly the situations that are hard to produce with a real backend: an empty list, a 500 error, a timeout, a response that arrives late.

In this lesson you will learn the interception APIs of both tools (cy.intercept and page.route), how to wait for a request to finish, and how to simulate errors and slow replies. You will also build a small request interceptor as a stand-in. For waiting concepts, see Auto-Waiting in Playwright and How Cypress Commands Really Work.

Cypress, Playwright and a real server cannot run on this site, so the real code is read-only. The runnable examples are stand-ins: a fake network layer written in plain Node.js that reproduces how routes are matched, answered and awaited. It is not the real code of either tool.

Why mock the network at all

There are two honest reasons, and they pull in different directions.

  • Control. A stub lets a test create situations on demand: no data, a huge list, a validation error, a failing payment provider. You do not need to prepare a database for each case, and the test runs fast and the same way every time.
  • Realism. A real request exercises the real server, and that is the only way to know the front end and back end agree.

A good suite uses both. Most of the suite's journey tests can use a real test backend (see Test Data and Logging In Fast), while edge case tests stub the network: failures, empty states, slow replies. Do not stub everything, or you only test that your stub matches your guess about the server.

flowchart LR
  P["Page (your app)"] -->|"request"| I{"Interceptor in the test tool"}
  I -->|"no rule"| S["Real server"]
  I -->|"fulfill"| R["Fake response"]
  I -->|"abort"| E["Network error"]
  I -->|"continue, modified"| S
  S --> I
  R --> P
  E --> P
  I -->|"response"| P

The interceptor sees every request; per rule it answers, fails or forwards it.

Intercepting in Cypress

cy.intercept() registers a rule. Give the rule an alias with .as() so you can wait for it.

JavaScript
// Cypress (read-only)
describe('user list', () => {
  it('shows users from the API', () => {
    // answer from a file in cypress/fixtures/users.json
    cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers')

    cy.visit('/users')
    cy.wait('@getUsers')                       // wait until the request happened
    cy.get('[data-cy=user-row]').should('have.length', 2)
  })

  it('shows an empty state', () => {
    cy.intercept('GET', '/api/users', { body: [] }).as('getUsers')
    cy.visit('/users')
    cy.wait('@getUsers')
    cy.contains('No users yet').should('be.visible')
  })

  it('shows an error message when the server fails', () => {
    cy.intercept('GET', '/api/users', { statusCode: 500, body: { error: 'boom' } })
    cy.visit('/users')
    cy.contains('Something went wrong').should('be.visible')
  })

  it('handles a network failure', () => {
    cy.intercept('GET', '/api/users', { forceNetworkError: true })
    cy.visit('/users')
    cy.contains('You appear to be offline').should('be.visible')
  })

  it('shows a loading spinner while the response is slow', () => {
    cy.intercept('GET', '/api/users', { delay: 1500, body: [] })
    cy.visit('/users')
    cy.get('[data-cy=spinner]').should('be.visible')
  })
})

A few details worth remembering:

  • Register the intercept before the action that triggers the request. A rule added afterwards cannot catch a request that has already gone out.
  • cy.wait('@alias') yields the intercepted request and response, so you can assert on them: cy.wait('@save').its('request.body').should('deep.equal', { title: 'Buy milk' }).
  • A function handler gives full control: cy.intercept('POST', '/api/todos', (req) => { req.reply({ statusCode: 201, body: { id: 1, ...req.body } }) }). Calling req.continue((res) => { ... }) lets the real request go out and lets you change the real response.
  • Intercepts are reset between tests, so every test registers its own.
  • When several rules match the same request, the most recently defined one runs first.

Intercepting in Playwright

Playwright uses page.route() with a handler that receives a route object. Every handler must end in exactly one of fulfill, abort, continue or fallback.

TypeScript
// Playwright (read-only)
import { test, expect } from '@playwright/test';

test('shows users from the API', async ({ page }) => {
  await page.route('**/api/users', (route) =>
    route.fulfill({ json: [{ name: 'Ada' }, { name: 'Linus' }] })
  );

  await page.goto('/users');
  await expect(page.getByTestId('user-row')).toHaveCount(2);
});

test('shows an error when the server fails', async ({ page }) => {
  await page.route('**/api/users', (route) =>
    route.fulfill({ status: 500, json: { error: 'boom' } })
  );
  await page.goto('/users');
  await expect(page.getByText('Something went wrong')).toBeVisible();
});

test('handles a network failure', async ({ page }) => {
  await page.route('**/api/users', (route) => route.abort('failed'));
  await page.goto('/users');
  await expect(page.getByText('You appear to be offline')).toBeVisible();
});

test('shows a spinner while the response is slow', async ({ page }) => {
  await page.route('**/api/users', async (route) => {
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await route.fulfill({ json: [] });
  });
  await page.goto('/users');
  await expect(page.getByTestId('spinner')).toBeVisible();
});

test('changes a real response', async ({ page }) => {
  await page.route('**/api/users', async (route) => {
    const response = await route.fetch();            // really send it
    const users = await response.json();
    await route.fulfill({ response, json: users.slice(0, 1) });
  });
  await page.goto('/users');
  await expect(page.getByTestId('user-row')).toHaveCount(1);
});

To check that the app sent the right request, or to wait for a response, use page.waitForRequest() and page.waitForResponse(). Start the wait first, then trigger it:

TypeScript
// Playwright (read-only)
const saving = page.waitForRequest((r) => r.url().endsWith('/api/todos') && r.method() === 'POST');
await page.getByRole('button', { name: 'Save' }).click();
const request = await saving;
expect(request.postDataJSON()).toEqual({ title: 'Buy milk' });

Playwright also tries routes in reverse order of registration, so the last page.route that matches wins. URL patterns are globs (**/api/users) or regular expressions, and they are matched against the whole URL, query string included. If your request is /api/users?page=2, the pattern **/api/users does not match it; use **/api/users* or a regular expression.

A request interceptor stand-in

The stand-in below builds the same idea in plain Node.js. A fake fetch goes through a list of routes. A route can fulfill with a made-up response, abort, or continue to the fake real server, optionally changing its answer. waitForResponse resolves at the next matching response, and it is created before the request is made, just as you would in a real test.

Node.js A fetch interceptor with fulfill, abort and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each new route for the same URL replaces the older ones, because the last one registered is checked first. That is why one network object can play five different servers one after another. The "modified real" line shows the useful middle path: the request reaches the (fake) real server, then the test edits the answer.

Checking what the app sent

Mocking works in both directions. You can also verify the request that your front end produced. The second stand-in shows two more ideas: several rules can match one request, so the newest wins, and the test can inspect the recorded requests afterwards, like cy.wait('@save').its('request.body').

Node.js Rule order and request spying

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The empty-title post is answered by badTitle (a 422), the normal post by anyPost (a 201), and the GET falls through to the "real network". Recording which rule handled which request is how real tools let you assert that a request really happened, how many times, and with which body.

Good habits

  • Use stubs for states you cannot easily create: errors, empty lists, slow replies, unusual data. Use a real test backend for the main journeys.
  • Keep stub data realistic. Copy a real response into a fixture, then trim it. A stub that no longer matches the real API gives false confidence (see Testing APIs Directly for a way to check the contract).
  • Register interception before the action, and wait for the specific request instead of sleeping.
  • Name aliases after the request (getUsers, saveTodo), not after the test.
  • Never stub the thing a test is meant to prove. A login test that stubs the login endpoint proves nothing about login.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Cypress, what must you do to be able to wait for an intercepted request with cy.wait('@getUsers')?

    cy.wait('@name') refers to an alias. Register the rule with cy.intercept(...).as('name') before the request happens.
  2. 2. In Playwright, a page.route handler must end by calling which kind of method?

    If the handler does none of these, the request stays pending. Each route must decide what happens to the request.
  3. 3. Why should you create a page.waitForResponse promise before clicking the button that triggers the request?

    Waiting starts when the promise is created. Creating it first guarantees that the response cannot slip past.
  4. 4. Which test is the best candidate for a stubbed network response?

    Errors, empty states and slow replies are hard to create with a real backend. Stub them. Do not stub what the test is supposed to verify.
  5. 5. Two page.route handlers match the same URL. Which one runs first in Playwright?

    Playwright tries routes in reverse order of registration, so the most recent matching route wins. Cypress works the same way for cy.intercept.

Summary

  • Interception lets a test control server responses: stub, fail, delay, modify or spy.
  • Cypress: cy.intercept(method, url, response).as('alias') and cy.wait('@alias'); { fixture }, { statusCode, body }, { forceNetworkError } and { delay } cover the common cases.
  • Playwright: page.route(pattern, handler) with route.fulfill, route.abort, route.continue or route.fetch; page.waitForRequest and page.waitForResponse for waiting.
  • Register rules before the triggering action; the newest matching rule wins in both tools.
  • Stub edge cases, not the thing under test, and keep stubs close to the real API.
  • The stand-ins reproduce routing and waiting in plain Node.js; they are not the tools' code.

Next: Test Data and Logging In Fast