Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Playwright Network Interception and Mock

Playwright Network Interception and Mock

This chapter introduces how to use Playwright to intercept, modify, and simulate network requests, enabling independent testing that does not rely on a backend API.


What is network interception

Network interception allows you to intervene when the browser makes HTTP requests.

You can block requests, modify responses, and return simulated data, so tests do not depend on external APIs or network conditions.


page.route() intercept requests

page.route(url, handler) Used to intercept all network requests matching a specified URL pattern.

Basic interception

Example

test

(

'Intercept all image requests'

,

async

(

{

page

}

)

=>

{

 

// Intercept all PNG and JPEG images

  await page.

route

(

'**/*.{png,jpg,jpeg}'

,

route

=>

route.

abort

(

)

)

;

 

// Navigate to the page (images will not be loaded)

  await page.

goto

(

'https://www.runoob.com/'

)

;

 

// The page may load faster because images are not downloaded

}

)

;

URL matching patterns support the following formats:

Mode Example Description
Full URL 'https://api.example.com/users' Exact match
Glob wildcards '**/api/**' ** Match any path
Regular expressions /\/api\/v\d\/users/ Flexible matching
function url => url.includes('/api/') Programmatic logic matching

route.abort() block requests

Example

test

(

'Block third-party analytics scripts'

,

async

(

{

page

}

)

=>

{

 

// Block analytics scripts such as Google Analytics

  await page.

route

(

'**/analytics'

,

route

=>

route.

abort

(

)

)

;

 

// Block CSS files

  await page.

route

(

'**/*.css'

,

route

=>

route.

abort

(

)

)

;

  await page.

goto

(

'https://www.runoob.com/'

)

;

 

// The page loads without styles, but functional tests are unaffected

}

)

;


route.fulfill() simulate response

route.fulfill() is the most powerful mocking method, able to return any custom response.

Mock JSON data

Example

test

(

'Mock user list API'

,

async

(

{

page

}

)

=>

{

 

// Intercept the user list API and return simulated data

  await page.

route

(

'**/api/users'

,

async route

=>

{

    await route.

fulfill

(

{

      status

:

200

,

      contentType

:

'application/json'

,

      json

:

[

       

{

id

:

1

,

name

:

'runoob_user'

,

email

:

'user@runoob.com'

}

,

       

{

id

:

2

,

name

:

'test_user'

,

email

:

'test@runoob.com'

}

,

     

]

,

   

}

)

;

 

}

)

;

  await page.

goto

(

'https://www.runoob.com/users'

)

;

 

// The page displays mock data instead of real API data

}

)

;

Mock error response

Example

test

(

'Test API error handling'

,

async

(

{

page

}

)

=>

{

 

// Simulate a 500 server error

  await page.

route

(

'**/api/data'

,

async route

=>

{

    await route.

fulfill

(

{

      status

:

500

,

      contentType

:

'application/json'

,

      json

:

{

error

:

'Internal server error'

}

,

   

}

)

;

 

}

)

;

  await page.

goto

(

'https://www.runoob.com/dashboard'

)

;

 

// Verify the error message displays correctly

  await expect

(

page.

getByText

(

'Internal server error'

)

)

.

toBeVisible

(

)

;

}

)

;


route.continue() modify and continue

Instead of directly returning simulated data, it modifies the real request or response before continuing to send it to the server.

Example

test

(

'Modify request headers'

,

async

(

{

page

}

)

=>

{

  await page.

route

(

'/api/'

,

async

(

route

,

request

)

=>

{

   

// Modify request headers, add a custom header

   

const

headers

=

{

      ...

request

.

headers

(

)

,

     

'X-Custom-Header'

:

'RUNOOB-TEST'

,

   

}

;

    await route.

continue

(

{

headers

}

)

;

 

}

)

;

  await page.

goto

(

'https://www.runoob.com/'

)

;

}

)

;

test

(

'Modify POST data'

,

async

(

{

page

}

)

=>

{

  await page.

route

(

'**/api/login'

,

async

(

route

,

request

)

=>

{

   

// Override the body of the POST request

   

const

postData

=

JSON.

parse

(

request.

postData

(

)

||

'{}'

)

;

    postData.

mode

=

'test'

;

 

// Add a test marker

    await route.

continue

(

{

      postData

:

JSON.

stringify

(

postData

)

,

   

}

)

;

 

}

)

;

}

)

;


route.fetch() real request

In a mock handler, you can use route.fetch() to actually send the request and get the real response, then modify it.

Example

test

(

'Modify the real response'

,

async

(

{

page

}

)

=>

{

  await page.

route

(

'**/api/products'

,

async route

=>

{

   

// First get the real response

   

const

response

=

await route.

fetch

(

)

;

   

const

body

=

await response.

json

(

)

;

   

// Modify the response data

    body.

items

[

0

]

.

name

=

'RUNOOB modified product name'

;

   

// Return the modified data

    await route.

fulfill

(

{

      status

:

response.

status

(

)

,

      contentType

:

'application/json'

,

      json

:

body

,

   

}

)

;

 

}

)

;

}

)

;


Context-level interception vs Page-level interception

Method Scope Applicable scenarios
page.route() Current page only Network mock for a single page
context.route() All pages in the context Mock rules shared by multiple pages

Example

test.

beforeEach

(

async

(

{

context

}

)

=>

{

 

// Intercept at the context level, effective for all pages

  await context.

route

(

'**/*.css'

,

route

=>

route.

abort

(

)

)

;

}

)

;

test

(

'Test 1'

,

async

(

{

page

}

)

=>

{

/* No CSS */

}

)

;

test

(

'Test 2'

,

async

(

{

page

}

)

=>

{

/* No CSS */

}

)

;


HAR file recording and replay

HAR (HTTP Archive) files can record all network requests of a page, then replay the simulation.

Example

test

(

'Mock using a HAR file'

,

async

(

{

page

}

)

=>

{

 

// Load network records from a HAR file and replay

  await page.

routeFromHAR

(

'tests/hars/api-responses.har'

)

;

  await page.

goto

(

'https://www.runoob.com/'

)

;

 

// All matching requests will get responses from the HAR file

}

)

;



# Record HAR file

npx playwright open --save-har=tests/hars/api-responses.har https://www.runoob.com/

HAR files are suitable for mocking large or complex API responses. Record once, then all subsequent tests replay from the HAR, without relying on a real server.