Playwright + JS · Lesson 30 of 35

0/35 done

Module 30: Network Mocking

30. Simulating Backends with Network Interception

17 minlesson

Try it yourself

Implement buildMockPayload:

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

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

Mocking with page.route()

javascript
test("simulate 500 server error toast", async ({ page }) => {
  await page.route("**/api/checkout", (route) => {
    route.fulfill({
      status: 500,
      contentType: "application/json",
      body: JSON.stringify({ error: "Payment server timeout" })
    });
  });

  await page.goto("/checkout");
  await page.getByRole("button", { name: "Pay Now" }).click();
  await expect(page.getByRole("alert")).toHaveText("Payment server timeout");
});

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 + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

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

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

Finished reading?

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

JavaScript
Skip