Network Interception & Mocking

Playwright can intercept, modify, and mock any network request.

Mock an API response

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

await page.goto('/users');
await expect(page.getByText('Mock User')).toBeVisible();

Intercept and modify

typescript
await page.route('**/api/products', async route => {
  const response = await route.fetch();
  const json = await response.json();
  json[0].price = 0; // modify first product price
  await route.fulfill({ response, json });
});

Wait for a specific request

typescript
const responsePromise = page.waitForResponse('**/api/login');
await page.getByRole('button', { name: 'Login' }).click();
const response = await responsePromise;
expect(response.status()).toBe(200);