Playwright + TS · Lesson 30 of 36

0/36 done

Module 30: Network Mocking & Interception

30. Simulating Backends with Network Interception & Routing

19 minlesson

Try it yourself

Implement buildMockResponse:

  1. Accept data payload and optional status code (default 200).
  2. Return MockPayload { status, contentType: "application/json", body: JSON.stringify(data) }.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

The page.route() API

Playwright allows you to intercept any network request matching a URL or glob pattern:

typescript
import { test, expect } from "@playwright/test";

test("mock user profile API to test VIP badge", async ({ page }) => {
  // Intercept the API and fulfill with mock JSON:
  await page.route("**/api/user/profile", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        id: 101,
        name: "Samantha VIP",
        tier: "PLATINUM",
      }),
    });
  });

  await page.goto("/profile");
  await expect(page.getByTestId("vip-badge")).toBeVisible();
});

Simulating Server Failures (500 Error & Network Aborts)

typescript
test("test error toast when server crashes", async ({ page }) => {
  // Abort request or return 500:
  await page.route("**/api/checkout", (route) => {
    route.fulfill({
      status: 500,
      body: JSON.stringify({ error: "Internal Server Failure" }),
    });
  });

  await page.goto("/checkout");
  await page.getByRole("button", { name: "Pay Now" }).click();

  await expect(page.getByRole("alert")).toHaveText("Payment service unavailable. Please try again.");
});

Simulating Offline Mode

typescript
await context.setOffline(true);

Key Takeaways & Walkthrough Summary

With network mocking using page.route, you can intercept browser network traffic and return simulated API responses. In this lesson, you will learn how to test tricky edge cases like 500 server errors, empty states, and offline modes without touching real backend services. Let's start mocking network requests!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Can I inspect the real response before modifying it?

Yes! Call 'const response = await route.fetch();' then modify its JSON before calling 'route.fulfill({ response, json: modified })'.

How do I block third-party analytics scripts to speed up tests?

Use page.route('**/*google-analytics.com/**', route => route.abort()); to eliminate tracking overhead.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip