Playwright + TS · Lesson 30 of 36
Module 30: Network Mocking & Interception
Try it yourself
Implement buildMockResponse:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
page.route() APIPlaywright allows you to intercept any network request matching a URL or glob pattern:
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();
});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.");
});await context.setOffline(true);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.
Yes! Call 'const response = await route.fetch();' then modify its JSON before calling 'route.fulfill({ response, json: modified })'.
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.