| | |

Playwright 17 ๐ŸŽญ Network Interception โ€” route() and mocking API responses

โฑ๏ธ Estimated read: 15 min | |

Playwright can intercept every HTTP request a page makes and decide what happens to it: let it continue to the server, modify it, redirect it, fulfill it with a synthetic response, or abort it entirely. The page.route() API provides this control, enabling tests to mock API responses without a running backend, simulate failures and slow networks, inject edge-case data, and verify that the application handles each scenario correctly. Network interception turns tests from dependent on external services into self-contained scenarios with deterministic outcomes.

This chapter covers the route() API in depth: how to register and remove routes, how to fulfill responses with custom status codes, headers, and JSON bodies, how to modify outgoing requests and incoming responses, how to simulate failures and timeouts, and how to combine routing with waitForResponse for request verification. It also covers common patterns such as mocking REST endpoints, throttling responses, and recording real responses for replay. By the end, you will be able to replace any network dependency with a controlled mock and test the application’s behavior under every condition you can imagine.

Key point: page.route() intercepts requests before they leave the browser, letting you fulfill them with synthetic responses, modify real ones, or abort them. Every dependency on a live server becomes a controllable input to your test.


Why network interception exists

The external dependency problem. A test that depends on a live backend inherits every problem the backend has: downtime, slow responses, rate limits, data that changes between runs, and environments that differ from production. When the staging API returns a 500, the test failsโ€”not because the frontend broke, but because the dependency did. Network interception severs this coupling: the test supplies the response, so the frontend’s behavior is the only variable.

The unreachable state problem. Applications handle states that are difficult to reproduce against a real server: network timeouts, 500 errors, empty datasets, malformed JSON, expired tokens, and slow loading. Triggering these conditions organically requires either a special backend mode or manual intervention. With route(), a test can return a 500 for one endpoint, delay a response by five seconds, or deliver an empty arrayโ€”all in a few lines of code. Every error path becomes testable.

The observation problem. Verifying that the frontend sends the correct requestโ€”the right URL, the right headers, the right bodyโ€”requires seeing the outgoing request. Network interception exposes the request object before it is sent, letting tests assert on payloads, capture request counts, and confirm that debouncing or caching works. Without interception, this verification requires a proxy or a backend that logs requests, adding infrastructure that tests should not need.


a. Registering routes and fulfilling responses

The page.route() method accepts a URL pattern and a handler function. The handler receives a Route object and the Request, and must call exactly one of route.fulfill(), route.continue(), route.abort(), route.fallback(), or route.fetch(). A route that handles a request without resolving it leaves the request pending until the test times out.

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

test('mocking a successful API response', async ({ page }) => {
  // Intercept any request matching the pattern before the page navigates
  await page.route('**/api/users', async (route) => {
    // Fulfill with a synthetic response; no server is contacted
    await route.fulfill({
      status: 200,                              // HTTP status code
      contentType: 'application/json',          // response content type
      body: JSON.stringify([                    // serialized response body
        { id: 1, name: 'Alice', role: 'admin' },
        { id: 2, name: 'Bob', role: 'viewer' },
      ]),
    });
  });

  await page.goto('/users');

  // The application renders the mocked data as if it came from the server
  await expect(page.getByText('Alice')).toBeVisible();
  await expect(page.getByText('Bob')).toBeVisible();
});

The URL pattern supports glob syntax (**/api/*), regular expressions (/\/api\/users\/\d+/), and predicate functions. Glob patterns are anchored: **/api/users matches any URL ending in that path regardless of protocol or host. A pattern without a wildcard prefix, such as 'api/users', matches relative to the base URL. Routes are matched in reverse registration order, so the most recently registered route winsโ€”useful for overriding a general mock with a specific one inside a single test.

test('overriding a general mock with a specific one', async ({ page }) => {
  // Register the general handler first
  await page.route('**/api/**', (route) =>
    route.fulfill({ status: 200, body: '{"data":[]}' })
  );

  // Register the specific handler second; it takes precedence for /api/orders
  await page.route('**/api/orders', (route) =>
    route.fulfill({
      status: 200,
      body: JSON.stringify([{ orderId: 'A-100', total: 42.5 }]),
    })
  );

  await page.goto('/dashboard');
  // Requests to /api/orders hit the specific mock; all others hit the general one
});

b. Modifying requests and responses with continue() and fetch()

Not every test wants to replace the response entirely. Sometimes the goal is to observe a real request, modify one header, or alter the response body after the server has produced it. The route.continue() method forwards the request to the server, optionally with overrides. The route.fetch() method performs the request programmatically and returns the response, which the handler can then modify and fulfill.

test('adding an authentication header to outgoing requests', async ({ page }) => {
  await page.route('**/api/**', async (route) => {
    // Forward the request to the server with a modified header
    await route.continue({
      headers: {
        ...route.request().headers(),          // preserve existing headers
        authorization: 'Bearer test-token-123', // inject the test token
      },
    });
  });

  await page.goto('/profile');
  // The server receives the injected token; the app behaves as authenticated
});

test('modifying a real response before it reaches the app', async ({ page }) => {
  await page.route('**/api/products', async (route) => {
    // Fetch the real response from the server
    const response = await route.fetch();

    // Parse the real body and alter one field
    const body = await response.json();
    body.products[0].price = 0;                 // force the first product to be free

    // Fulfill with the modified body, preserving the original status and headers
    await route.fulfill({ response, json: body });
  });

  await page.goto('/products');
  await expect(page.getByText('$0.00').first()).toBeVisible();
});

The route.fulfill({ response }) shorthand reuses the original response’s status, headers, and content type, overriding only the fields provided. This patternโ€”fetch the real response, mutate it, fulfill with the mutationโ€”preserves server correctness for everything except the field under test, which is often exactly what a test wants. It also lets you inspect real payloads while developing mocks, since the fetched response is available in the handler.


c. Simulating failures, delays, and aborts

The route.abort() method cancels the request as if the network failed. The error code passed to abort() determines the browser’s view of the failure: 'failed' for a generic network error, 'timedout' for a timeout, 'connectionrefused', 'internetdisconnected', and others. To simulate a slow server, the handler can delay before fulfilling; the delay suspends the response while the page’s loading state remains visible.

test('rendering an error state when the API returns 500', async ({ page }) => {
  await page.route('**/api/orders', (route) =>
    route.fulfill({ status: 500, body: 'Internal Server Error' })
  );

  await page.goto('/orders');
  // The app's error boundary or fallback UI should appear
  await expect(page.getByText('Something went wrong')).toBeVisible();
});

test('simulating a network failure', async ({ page }) => {
  await page.route('**/api/orders', (route) => route.abort('failed'));

  await page.goto('/orders');
  await expect(page.getByText('Network error')).toBeVisible();
});

test('simulating a slow response to test loading states', async ({ page }) => {
  await page.route('**/api/orders', async (route) => {
    // Wait 3 seconds before fulfilling
    await new Promise((resolve) => setTimeout(resolve, 3000));
    await route.fulfill({
      status: 200,
      body: JSON.stringify([{ orderId: 'A-100', total: 42.5 }]),
    });
  });

  await page.goto('/orders');

  // The loading spinner is visible while the response is pending
  await expect(page.getByRole('progressbar')).toBeVisible();

  // After the delay, the data appears and the spinner disappears
  await expect(page.getByText('A-100')).toBeVisible();
  await expect(page.getByRole('progressbar')).toBeHidden();
});

When a request is aborted, the application’s fetch or XMLHttpRequest rejects with a network error, which is the same code path a real offline scenario triggers. When a request is fulfilled with a 500 status, the application’s error handling for non-2xx responses runs. These are different branches of the frontend code, and testing both confirms that each has a user-visible outcome. Neither scenario requires any backend configuration.


Complete Example Session

// ============================================
// PART 1: IMPORT AND TEST SETUP
// ============================================
import { test, expect } from '@playwright/test';

// ============================================
// PART 2: MOCKING A SUCCESSFUL LIST RESPONSE
// ============================================
test('dashboard shows mocked orders', async ({ page }) => {
  // Intercept the orders endpoint and return a fixed payload
  await page.route('**/api/orders', (route) =>
    route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify([
        { id: 'ORD-001', status: 'shipped', total: 99.0 },
        { id: 'ORD-002', status: 'pending', total: 14.5 },
      ]),
    })
  );

  await page.goto('/dashboard');

  // ============================================
  // PART 3: ASSERTING ON THE MOCKED DATA
  // ============================================
  await expect(page.getByText('ORD-001')).toBeVisible();
  await expect(page.getByText('ORD-002')).toBeVisible();
  await expect(page.getByText('shipped')).toBeVisible();

  // ============================================
  // PART 4: CAPTURING THE OUTGOING REQUEST
  // ============================================
  let requestUrl = '';
  await page.route('**/api/orders', (route) => {
    requestUrl = route.request().url();          // record the URL
    return route.continue();                     // let it reach the server
  });

  // ============================================
  // PART 5: TRIGGERING THE REQUEST VIA UI
  // ============================================
  await page.getByRole('button', { name: 'Refresh' }).click();

  // ============================================
  // PART 6: VERIFYING THE REQUEST SHAPE
  // ============================================
  expect(requestUrl).toContain('/api/orders');

  // ============================================
  // PART 7: MOCKING A DIFFERENT STATUS CODE
  // ============================================
  await page.route('**/api/orders', (route) =>
    route.fulfill({ status: 403, body: 'Forbidden' })
  );

  // ============================================
  // PART 8: RELOADING TO TRIGGER THE ERROR PATH
  // ============================================
  await page.reload();
  await expect(page.getByText('Access denied')).toBeVisible();

  // ============================================
  // PART 9: SIMULATING A DELAYED RESPONSE
  // ============================================
  await page.route('**/api/orders', async (route) => {
    await new Promise((resolve) => setTimeout(resolve, 2000)); // 2s delay
    await route.fulfill({ status: 200, body: '[]' });          // empty list
  });

  // ============================================
  // PART 10: ASSERTING ON THE EMPTY STATE
  // ============================================
  await page.reload();
  await expect(page.getByText('No orders yet')).toBeVisible();
});

The ten parts above progress from a simple static mock through request capture, status-code manipulation, and delayed responses. The same endpoint is mocked three times with different outcomesโ€”success, forbidden, and emptyโ€”demonstrating that the route handler can be re-registered inside a test to exercise multiple application states against a single page.


Quick Reference

The Route Handler Actions

MethodEffectReturns
route.fulfill()Return a synthetic responsePromise<void>
route.continue()Forward to server, optionally modifiedPromise<void>
route.abort()Cancel the requestPromise<void>
route.fetch()Fetch the real response for inspectionPromise<APIResponse>
route.fallback()Defer to the next matching routePromise<void>

The fulfill() Options

OptionPurposeExample
statusHTTP status codestatus: 404
bodyResponse body as stringbody: 'Not found'
jsonResponse body as JSONjson: { data: [] }
contentTypeContent-Type headercontentType: 'application/json'
headersAdditional headersheaders: { 'x-test': '1' }
responseReuse an APIResponseresponse: realResponse

The abort() Error Codes

CodeBrowser SeesTypical Use
'failed'Generic network failureOffline simulation
'timedout'Request timed outSlow network
'connectionrefused'Connection refusedServer down
'internetdisconnected'No internetAirplane mode

URL Pattern Types

PatternMatchesExample
Glob**/api/***/api/users
Regex/\/api\/users\/\d+/new RegExp('/api/users/\\d+')
Predicate(url) => url.endsWith('/api')Function returning boolean
Relative'api/users'Relative to base URL

Best Practices

โœ… Do This:

// Register routes before page.goto() so no request escapes
await page.route('**/api/**', handler);  // โœ…
await page.goto('/dashboard');

// Use json: for JSON bodies instead of manual JSON.stringify
await route.fulfill({ status: 200, json: { items: [] } });  // โœ…

// Use route.fetch() to modify real responses rather than reconstructing them
const response = await route.fetch();  // โœ…
await route.fulfill({ response, json: mutate(await response.json()) });

// Capture requests to verify outgoing payloads
let captured: Record<string, unknown>;
await page.route('**/api/orders', (route) => {
  captured = route.request().postDataJSON();  // โœ…
  return route.continue();
});

// Abort requests you don't care about to speed up tests
await page.route('**/analytics/**', (route) => route.abort());  // โœ…

// Test each error path with its own route and assertion
await page.route('**/api/orders', (r) => r.fulfill({ status: 500 }));  // โœ…
await expect(page.getByText('Something went wrong')).toBeVisible();

โŒ Don’t Do This:

// Don't forget to handle the route; unresolved requests hang
await page.route('**/api/**', async () => {});  // โŒ request never resolves

// Don't call fulfill twice; only the first call takes effect
await route.fulfill({ status: 200 });  // โŒ
await route.fulfill({ status: 500 });  // โŒ unreachable, ignored

// Don't use route() for requests already made by the page
await page.goto('/dashboard');  // โŒ requests already sent
await page.route('**/api/orders', handler);  // โŒ too late

// Don't mock a response without asserting the app renders it
await page.route('**/api/orders', mockHandler);  // โŒ no verification
await page.goto('/dashboard');

// Don't use page.route() when you want browser-wide mocking
await page.route('**/api/**', handler);  // โŒ popups won't be intercepted
// use context.route() for popups and new pages

// Don't rely on the order of parallel requests
await page.route('**/api/a', ...);  // โŒ registration order decides precedence
await page.route('**/api/**', ...);  // โŒ this catches /api/a if registered first

Common Pitfalls

PitfallWhy It HappensFix
Mock not appliedRoute registered after navigationRegister before goto()
Request hangsHandler never resolves the routeCall fulfill, continue, or abort
Wrong mock winsMost recently registered route takes precedenceRegister general routes first, specific last
Popup not mockedpage.route() scopes to one pageUse context.route() for all pages
Request body unreadableReading body after continue()Read postDataJSON() before forwarding
Real server still calledPattern does not match URLTest pattern with a console.log(route.request().url())
CORS errors with mocksMissing access-control-allow-origin headerAdd CORS headers to the fulfilled response

Real-World Examples

1. Mocking a login endpoint

await page.route('**/api/login', (route) =>
  route.fulfill({ status: 200, json: { token: 'fake-jwt-token' } })
);

2. Simulating an expired session

await page.route('**/api/session', (route) =>
  route.fulfill({ status: 401, body: 'Unauthorized' })
);

3. Mocking a paginated list

await page.route('**/api/items?page=2', (route) =>
  route.fulfill({ json: { items: [{ id: 3 }], hasMore: false } })
);

4. Delaying one endpoint to test suspense

await page.route('**/api/slow', async (route) => {
  await new Promise((r) => setTimeout(r, 1500));
  await route.fulfill({ json: { ok: true } });
});

5. Injecting a server error on a form submit

await page.route('**/api/submit', (route) =>
  route.fulfill({ status: 500, json: { error: 'Server error' } })
);

6. Blocking third-party analytics requests

await page.route('**/analytics/**', (route) => route.abort());

7. Counting how many times an endpoint is called

let calls = 0;
await page.route('**/api/search', (route) => {
  calls++;
  return route.continue();
});

8. Overriding a single field in a real response

await page.route('**/api/profile', async (route) => {
  const response = await route.fetch();
  const body = await response.json();
  await route.fulfill({ response, json: { ...body, verified: true } });
});

9. Mocking a GraphQL endpoint

await page.route('**/graphql', (route) =>
  route.fulfill({ json: { data: { viewer: { name: 'Test' } } } })
);

10. Simulating a timeout

await page.route('**/api/orders', (route) => route.abort('timedout'));

Visual

The Request Interception Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  REQUEST LIFECYCLE WITH route()                     โ”‚
โ”‚                                                     โ”‚
โ”‚  App calls fetch('/api/orders')                     โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
โ”‚  โ”‚  Playwright intercepts the request          โ”‚   โ”‚
โ”‚  โ”‚  Matches against registered route patterns  โ”‚   โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ”œโ”€โ”€โ–บ fulfill()  โ”€โ”€โ–บ synthetic response      โ”‚
โ”‚         โ”œโ”€โ”€โ–บ continue() โ”€โ”€โ–บ real server โ”€โ”€โ–บ responseโ”‚
โ”‚         โ”œโ”€โ”€โ–บ abort()    โ”€โ”€โ–บ network error           โ”‚
โ”‚         โ””โ”€โ”€โ–บ fetch()    โ”€โ”€โ–บ real server             โ”‚
โ”‚                              + inspect + mutate     โ”‚
โ”‚                              + fulfill modified     โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  Response reaches the application                   โ”‚
โ”‚  The app cannot tell whether it was mocked          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Route Registration Order

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  REVERSE REGISTRATION PRECEDENCE                    โ”‚
โ”‚                                                     โ”‚
โ”‚  Registered 1st:  '**/api/**'     โ”€โ”€โ–บ general       โ”‚
โ”‚  Registered 2nd:  '**/api/orders' โ”€โ”€โ–บ specific      โ”‚
โ”‚                                                     โ”‚
โ”‚  Request: /api/orders                               โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  Check 2nd route: matches '**/api/orders' โœ“         โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  Handler for specific route runs                    โ”‚
โ”‚  (The general route never fires)                    โ”‚
โ”‚                                                     โ”‚
โ”‚  Request: /api/users                                โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  Check 2nd route: no match โœ—                        โ”‚
โ”‚  Check 1st route: matches '**/api/**' โœ“             โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  Handler for general route runs                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Mocking Matrix

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WHAT TO MOCK FOR EACH SCENARIO                     โ”‚
โ”‚                                                     โ”‚
โ”‚  Scenario          Route Action        Assert       โ”‚
โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚
โ”‚  Happy path        fulfill(200, data)  data visible โ”‚
โ”‚  Empty state       fulfill(200, [])    empty messageโ”‚
โ”‚  Server error      fulfill(500)        error UI     โ”‚
โ”‚  Unauthorized      fulfill(401)        login screen โ”‚
โ”‚  Forbidden         fulfill(403)        access deniedโ”‚
โ”‚  Slow network      delay + fulfill     spinner      โ”‚
โ”‚  Offline           abort('failed')     retry UI     โ”‚
โ”‚  Timeout           abort('timedout')   timeout UI   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Primary methodpage.route(pattern, handler)
ScopePer page; context.route() for all pages
Handler actionsfulfill, continue, abort, fetch, fallback
PrecedenceLast registered route wins
URL patternsGlob, regex, predicate, relative
Fulfill bodybody (string) or json (object)
Response reusefulfill({ response }) from route.fetch()
Abort codes'failed', 'timedout', 'connectionrefused', 'internetdisconnected'
Unroutepage.unroute(pattern, handler?)
TimingRegister before navigation

Key takeaways:

  • Mock before navigation. A route registered after page.goto() misses the initial requests. Register every mock before the page loads, or use context.route() for tests that navigate across multiple pages.
  • Every handler must resolve the route. fulfill, continue, abort, or fetchโ€”one of them must be called. A handler that returns without resolving leaves the request pending and the test hanging until timeout.
  • Reverse registration order matters. The most recently registered matching route runs first. Register broad catch-all routes first and specific overrides later so the specific ones take precedence.
  • route.fetch() preserves realism. When only one field needs to change, fetch the real response and modify it. This keeps headers, status codes, and unaffected fields accurate without hardcoding a full payload.
  • Error paths are the highest-value mocks. A 500, a 401, a timeout, and an empty list are often the scenarios that break in production. They are also the easiest to test with route() because no backend setup is required.
  • Abort codes simulate distinct network conditions. 'failed', 'timedout', and 'connectionrefused' reach the application through different error paths. Choose the code that matches the scenario being tested.
  • Verify outgoing requests with captured data. Store route.request().postDataJSON() or route.request().headers() in a variable, then assert after the action. This confirms the frontend sends what the backend expects.

Remember: Network interception is the mechanism that makes frontend tests independent of backend availability and data. Every external call becomes a switch the test controls: return success, return failure, delay, abort, or mutate. The application code does not changeโ€”it still calls fetch, still parses JSON, still renders loading and error statesโ€”but the test decides what comes back and can therefore verify every branch of the frontend’s behavior. Register routes before navigation, always resolve them, and mock both the happy path and the failures; a test suite that only mocks success verifies only half the application.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!