PLAYWRIGHT UIADVANCED

Playwright Network Interception & API Mocking: Complete Guide with Real-World Examples

Learn Playwright Network Interception and API Mocking with real-world examples. Master route(), fulfill(), continue(), abort(), request modification, response mocking, and enterprise testing best practices.

iff Solution Academy July 15, 2026 32 min read Updated July 15, 2026
Playwright Network Interception API Mocking route() fulfill() continue() abort() Enterprise Testing SDET

What is Network Interception?

Modern web applications constantly communicate with backend services through REST APIs, GraphQL APIs, authentication endpoints, analytics services, payment gateways, and third-party integrations.

Playwright Network Interception allows automation engineers to intercept these network requests before they reach the server.

Instead of depending on a live backend, your tests can inspect, modify, block, or replace requests and responses. This capability makes automated tests faster, more reliable, and easier to execute in CI/CD environments.

Network Interception is one of the main reasons Playwright is widely adopted for enterprise automation because it enables complete control over application behavior during testing.

Why Network Interception Matters

Without interception, automated tests depend on:

  • API availability
  • Database state
  • Network speed
  • Third-party services
  • Authentication servers

If any of these systems fail, UI tests may fail even though the application's frontend works correctly.

Network interception allows engineers to isolate the frontend and verify its behavior independently.

Benefits include:

  • Faster execution
  • Stable automation
  • Independent frontend testing
  • Easier debugging
  • Better negative testing
  • Reduced flaky tests

Understanding route()

Playwright intercepts requests using page.route().

ts
await page.route('**/api/products', async route => {
  await route.continue();
});

This intercepts every request matching the specified URL pattern.

Continuing Requests

Sometimes you simply want to observe traffic without modifying it.

ts
await page.route('**/api/users', async route => {
  console.log(route.request().url());
  await route.continue();
});

The request proceeds normally.

Blocking Requests

You can simulate network failures.

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

This blocks image downloads.

This technique speeds up UI automation because unnecessary resources are never downloaded.

Mocking API Responses

Instead of calling the real backend:

ts
await page.route('**/api/products', async route => {
  await route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify({
      products: [
        {
          id: 1,
          name: 'Playwright Book'
        }
      ]
    })
  });
});

The application believes the server returned this response.

Modifying Requests

Modify Request Headers

ts
await page.route('**/api/orders', async route => {
  const headers = {
    ...route.request().headers(),
    Authorization: 'Bearer TEST_TOKEN'
  };
  await route.continue({
    headers
  });
});

Useful for testing authorization scenarios.

Modify POST Data

ts
await page.route('**/api/login', async route => {
  const request = route.request();
  console.log(request.postData());
  await route.continue();
});

Engineers often inspect request payloads before allowing them to continue.

Modifying Responses

You can also alter real responses before they reach the browser.

ts
await page.route('**/api/products', async route => {
  const response = await route.fetch();
  const json = await response.json();
  json.products[0].name = 'Mocked Product Name';

  await route.fulfill({
    response,
    body: JSON.stringify(json)
  });
});

This is powerful for testing edge cases that are hard to reproduce on a real backend.

Simulating Server Errors

Testing error handling is critical.

ts
await page.route('**/api/products', async route => {
  await route.fulfill({
    status: 500,
    body: 'Internal Server Error'
  });
});

Now you can verify that the UI displays proper error messages.

Simulate Slow Networks

ts
await page.route('**/api/orders', async route => {
  await new Promise(resolve =>
    setTimeout(resolve, 3000)
  );
  await route.continue();
});

Useful for loading indicator validation.

Mocking Authentication APIs

Authentication APIs can also be mocked.

ts
await page.route('**/login', async route => {
  await route.fulfill({
    status: 200,
    body: JSON.stringify({
      token: 'mock-token'
    })
  });
});

Tests become independent of authentication servers.

Testing Offline Scenarios

You can simulate complete network failures.

ts
await page.context().setOffline(true);

Verify:

  • Offline messages
  • Retry buttons
  • Cached data
  • Error handling

Enterprise Framework Examples

Many enterprise frameworks centralize network mocks.

text
src/
  mocks/
    product.mock.ts
    order.mock.ts
    user.mock.ts
    payment.mock.ts
    auth.mock.ts

Tests remain clean.

ts
test('Checkout', async ({
  checkoutPage,
  productMock
}) => {
  // Test logic only
});

Best Practices

  • Mock only when necessary.
  • Test real APIs separately.
  • Keep mock data realistic.
  • Store mock JSON in dedicated files.
  • Reuse mocks across tests.
  • Verify both success and failure scenarios.

Common Mistakes

Mocking everything.

Some tests should always call the real backend.

Hardcoding mock data inside test files.

Store reusable mock responses separately.

Ignoring negative scenarios.

Always test:

  • 404
  • 401
  • 403
  • 500
  • Network timeout

Interview Questions

What is Network Interception?

The ability to inspect, modify, block, or replace HTTP requests and responses during automation.

Difference between continue() and fulfill()?

continue() sends the original request. fulfill() returns a mocked response without contacting the server.

When should API Mocking be used?

  • UI testing
  • Offline testing
  • Third-party integrations
  • Error scenarios
  • Faster execution

Why do enterprise teams use Network Interception?

To create stable, repeatable automation independent of backend availability.

Summary

Network Interception is one of Playwright's most powerful enterprise features.

By controlling HTTP requests and responses, automation engineers can isolate frontend behavior, simulate failures, improve execution speed, and build highly reliable test suites.

Mastering Network Interception is essential for advanced Playwright automation and is frequently discussed in senior SDET interviews.

Get Playwright tutorials in your inbox

Weekly tips, real-world examples, and framework patterns – no spam, unsubscribe anytime.

Playwright Framework Series

View all →
  1. 1Getting Started with Playwright: Installation, Setup, and Your First Test
  2. 2Playwright Locators: The Complete Guide with Real-World Examples
  3. 3Playwright Actions: Complete Guide to Click, Fill, Hover, Keyboard, Mouse & File Upload
  4. 4Playwright Assertions: The Complete Guide with Real-World Examples
  5. 5Playwright Auto Waiting: The Complete Guide with Real-World Examples
  6. 6Playwright Fixtures: The Complete Guide with Real-World Examples
  7. 7Playwright Browser Context & Multiple Tabs: The Complete Guide with Real-World Examples
  8. 8Playwright Authentication & Session Management: Complete Guide with Enterprise Examples
  9. 9Playwright Network Interception & API Mocking: Complete Guide with Real-World Examples
  10. 10Playwright Page Object Model (POM): The Complete Guide with Enterprise Examples
  11. 11Page Object Model with Playwright: A Practical Guide
  12. 12How to Build a Robust Professional Playwright Framework from Scratch (Step-by-Step)
  13. 13Building an Enterprise Playwright Framework from Scratch

API Testing Series

View all →
  1. 1Playwright API Testing: The Complete Guide with Real-World Examples
  2. 2Part 1 : Playwright API Testing Tutorial: Build Enterprise-Level API Automation Framework
  3. 3Part 2: Playwright API Testing Tutorial: Setting Up Project & Sending Your First API Request
  4. 4Part 3: Mastering CRUD Operations in Playwright API Testing
  5. 5Part 4: Authentication in Playwright API Testing (Bearer Token, JWT, API Key & Reusable Fixtures)
  6. 6Part 5: Building an Enterprise-Level Playwright API Automation Framework
  7. 7Part 6: API Models, Schema Validation & Test Data Management in Playwright
  8. 8Part 7: Custom Fixtures, Hooks, Logging & Parallel Execution in Playwright API Testing
  9. 9Part 8: Building a Production-Ready Playwright API Framework (Environment Management, CI/CD, Reporting & Best Practices)
  10. 10Part 9: Advanced Playwright API Testing Techniques for Enterprise Automation
  11. 11Part 10: Building a Complete Enterprise Playwright API Automation Framework (Final Part)
  12. 12API Testing with Playwright: Request Context, Auth, and Assertions

Recommended Next Articles