Playwright Network Mocking
Playwright Network Mocking
Network mocking means your test answers the page's network requests itself, instead of letting them reach the real server.
This lets you test what the page does with any data, including errors that are hard to cause on a real server.
This chapter uses the Shop practice page.
When it opens, it loads its products from api/products.php with fetch, and shows one card per product.
Return Fake Data
Use page.route() to catch requests to a URL.
For each caught request, Playwright calls your function with a route object.
Call route.fulfill() to answer the request:
Example
tests/mock.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('shows mocked products', async ({ page }) => {
await page.route('**/api/products.php', async route => {
await route.fulfill({
json: {
products: [
{ id: 1, name: 'Test Phone', price: 100 },
{ id: 2, name: 'Test Tablet', price: 200 },
],
},
});
});
await page.goto('shop.html');
await expect(page.getByTestId('product')).toHaveCount(2);
await expect(page.getByRole('heading', { name: 'Test Phone' })).toBeVisible();
await expect(page.getByRole('status')).toHaveText('2 products');
});
Output:
Running 1 test using 1 worker
[1/1] [chromium] › tests/mock.spec.js:4:1 › shows mocked products
1 passed (1.1s)
Example Explained
'**/api/products.php'is a glob pattern: a URL pattern with wildcards.**matches any start of the URL- The route is set up before
page.goto(), so it is ready when the page sends the request route.fulfill({ json })answers with status 200 and the object as JSON- The real server never gets the request
- The page shows 2 products instead of the 5 real ones
Change a Real Response
Sometimes you want the real data, with one small change.
route.fetch() sends the request to the server and gives you the response.
Change it, and pass it on with route.fulfill():
Example
tests/modify.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('changes the real response', async ({ page }) => {
await page.route('**/api/products.php', async route => {
const response = await route.fetch();
const json = await response.json();
json.products[0].price = 0;
await route.fulfill({ response, json });
});
await page.goto('shop.html');
await expect(page.getByTestId('product')).toHaveCount(5);
await expect(page.getByTestId('product').first()).toContainText('$0.00');
});
All 5 real products are shown, but the first one now costs $0.00.
Passing response keeps the real status and headers, and json replaces the body.
Block Requests
route.abort() makes a request fail, as if the network was down.
Use it to test how the page handles a failed request:
Example
tests/abort.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('shows an error when the API is down', async ({ page }) => {
await page.route('**/api/products.php', route => route.abort());
await page.goto('shop.html');
await expect(page.getByRole('status')).toHaveText('Could not load products.');
await expect(page.getByTestId('product')).toHaveCount(0);
});
test('page works without images', async ({ page }) => {
await page.route('**/*.{png,jpg,jpeg,gif,webp}', route => route.abort());
await page.goto('shop.html');
await expect(page.getByTestId('product')).toHaveCount(5);
});
The second test blocks every image.
This is also a common way to make tests faster on pages with many large images.
Simulate a Server Error
Give route.fulfill() a status to send an error response:
Example
tests/error.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('handles a server error', async ({ page }) => {
await page.route('**/api/products.php', route => route.fulfill({
status: 500,
json: { error: 'Server error' },
}));
await page.goto('shop.html');
await expect(page.getByRole('status')).toHaveText('Could not load products.');
});
Run the error tests:
Example
npx playwright test tests/abort.spec.js tests/error.spec.js
Output:
Running 3 tests using 3 workers
[1/3] [chromium] › tests/abort.spec.js:4:1 › shows an error when the API is down
[2/3] [chromium] › tests/abort.spec.js:12:1 › page works without images
[3/3] [chromium] › tests/error.spec.js:4:1 › handles a server error
3 passed (1.5s)
You can test 404, 500 or any other status the same way, without breaking a real server.
Wait for a Response
You do not have to mock a request to check it.
page.waitForResponse() waits for a real response, and lets you look at it:
Example
tests/wait.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('waits for the products API', async ({ page }) => {
const responsePromise = page.waitForResponse('**/api/products.php');
await page.goto('shop.html');
const response = await responsePromise;
expect(response.status()).toBe(200);
const data = await response.json();
expect(data.products).toHaveLength(5);
await expect(page.getByTestId('product')).toHaveCount(5);
});
Start waiting before the action that sends the request, and await the promise after it.
If you start waiting after goto(), the response has probably arrived already, and the wait ends with a timeout error.
There is also page.waitForRequest(), which works the same way for requests.
Mock with a HAR File
A HAR file (HTTP Archive) is a recording of network requests and responses.
Playwright can save real responses to a HAR file once, and use them again in later runs:
Example
await page.routeFromHAR('./hars/products.har', {
url: '**/api/products.php',
update: true,
});
- With
update: true, the request goes to the real server, and the response is saved to the file - Remove
update(or set it tofalse), and the requests are answered from the file urllimits it to the matching requests. Other requests go to the network as normal
This is useful when an API returns a lot of data that you do not want to write by hand.
You can also edit the saved responses in the HAR file to test special cases.