Network Interception (Mocking) in Playwright



Playwright Training
Playwright Training

Network Interception (Mocking) in Playwright

Network Interception in Playwright allows you to intercept, modify, block, or mock network requests and responses. This is extremely useful when testing applications without depending on real backend services.


Why Use Network Interception?

  • Test UI without backend availability
  • Simulate different API responses
  • Test error scenarios (500, 404, timeout)
  • Improve test execution speed
  • Eliminate dependency on external systems
  • Test edge cases that are difficult to reproduce

Playwright APIs

API Purpose
page.route() Intercept network requests
route.fulfill() Mock response
route.continue() Continue request with modifications
route.abort() Block request
page.unroute() Remove interception
browserContext.route() Intercept for all pages

Example Application

Suppose the application calls:

GET https://api.demo.com/users
Instead of calling the real API, we return mock data.

Example 1: Mock API Response

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

test('Mock API response', async ({ page }) => {

    await page.route('**/users', async route => {

        await route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify([
                {
                    id: 1,
                    name: 'Anand'
                },
                {
                    id: 2,
                    name: 'Ravi'
                }
            ])
        });

    });

    await page.goto('https://example.com');
});

Example 2: Mock Response from JSON File

Create

mockUsers.json
[
    {
        "id":1,
        "name":"Anand"
    },
    {
        "id":2,
        "name":"Techtutorialz"
    }
]
Playwright
import fs from 'fs';
await page.route('**/users', async route => {
    const data = fs.readFileSync('mockUsers.json','utf-8');
    await route.fulfill({
        body:data,
        contentType:'application/json'
    });

});
Example 3: Modify Request Before Sending
await page.route('**/login', async route => {
    const request = route.request();
    const headers = {
        ...request.headers(),
        Authorization: 'Bearer TEST_TOKEN'
    };

    await route.continue({
        headers
    });

});

Example 4: Modify POST Data

await page.route('**/login', async route => {
    const data = {
        username:'admin',
        password:'admin123'
    };
    await route.continue({
        postData: JSON.stringify(data)
    });

});
Example 5: Block Images

Improves execution speed.

await page.route('**/*.{png,jpg,jpeg,gif}', route => {
    route.abort();
});

Example 6: Block CSS Files

await page.route('**/*.css', route => {
    route.abort();
});
Example 7: Return 500 Error
await page.route('**/users', async route => {

    await route.fulfill({
        status:500,
        body:'Internal Server Error'
    });

});

Example 8: Return 404

await page.route('**/users', async route => {
    await route.fulfill({
        status:404,
        body:'Not Found'
    });

});

Example 9: Simulate Slow Network

await page.route('**/users', async route => {
    await new Promise(r => setTimeout(r,5000));
    await route.continue();
});

Example 10: Abort API Request

await page.route('**/users', route => {
    route.abort();
});
Example 11: Intercept All Requests
await page.route('**/*', route => {
    console.log(route.request().url());
    route.continue();
});
Useful for debugging.

Example 12: Mock Only One Request

await page.route('**/users', async route => {
    await route.fulfill({
        status:200,
        body:'[]'
    });
});

await page.goto('https://example.com');
await page.unroute('**/users');
Example 13: Browser Context Mocking

Applies to every page.

await context.route('**/users', async route => {

    await route.fulfill({
        status:200,
        body:'[]'
    });

});
Example 14: Mock GraphQL Request
await page.route('**/graphql', async route => {
    const request = route.request();
    const body = request.postDataJSON();
    if (body.operationName === 'GetUsers') {
        await route.fulfill({
            status:200,
            contentType:'application/json',
            body: JSON.stringify({
                data:{
                    users:[
                        { id:1,name:'Anand'}
                    ]
                }
            })
        });

    } else {

        await route.continue();
    }
});
Example 15: Mock Based on URL
await page.route('**/*', async route => {
    const url = route.request().url();
    if (url.includes('/users')) {
        await route.fulfill({
            body:'[]'
        });

    } else {

        await route.continue();

    }

});

Master Playwright from Scratch! Explore our complete Playwright Tutorial collection covering:

  • Playwright Basics
  • Locators
  • Assertions
  • Timeouts
  • Browser Context
  • Frames & iFrames
  • Auto Waiting & Timeouts
  • API Testing
  • Network Interception
  • Authentication
  • Fixtures
  • Parallel Execution
  • CI/CD
  • AI in Playwright

👉 Browse all Playwright tutorials: Playwright Tutorial

Techtutotialz Training, Job support, Interview support
Techtutotialz Training, Job support, Interview support
 
Tags: , , ,
Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!