Playwright · Test Automation · E2E Testing · TypeScript

Network Mocking in Playwright: page.route, HAR Files and API Tests

Mock, modify and block network calls in Playwright with page.route, record and replay HAR files, and use the request fixture for fast API tests and test setup.

Sander Yazıcıoğlu Published: 3 min read Türkçe oku

Network Mocking in Playwright: page.route, HAR Files and API Tests

The slowest and flakiest part of most end-to-end suites I have seen is not the browser, it is the backend behind it: shared test data that someone else changed, a third-party service that is down, an error state you cannot reproduce on demand. Coming from Testinium, where flaky tests are a daily topic, I lean heavily on Playwright's network layer to take that variable out. This post covers the techniques I use most.

Fulfilling a request with fixed data

page.route intercepts any request matching a glob, regex or predicate. route.fulfill answers it without touching the server:

test('shows an empty state when there are no runs', async ({ page }) => {
  await page.route('**/api/runs?*', (route) =>
    route.fulfill({ json: { items: [], total: 0 } }),
  );
  await page.goto('/runs');
  await expect(page.getByText('No test runs yet')).toBeVisible();
});

Register routes before page.goto, otherwise the first requests escape. Use context.route instead when popups or new tabs should be mocked too.

The json option sets the body and the Content-Type header for you. For error states, set status:

await page.route('**/api/runs?*', (route) =>
  route.fulfill({ status: 503, json: { message: 'Maintenance' } }),
);

Now the "service unavailable" banner, which nobody ever tests manually, has a regression test.

Modifying a real response

Sometimes you want the real backend but one field changed, for example to test a long name that breaks the layout. route.fetch() performs the real request and lets you edit the result:

await page.route('**/api/profile', async (route) => {
  const response = await route.fetch();
  const body = await response.json();
  body.displayName = 'A'.repeat(120);
  await route.fulfill({ response, json: body });
});

Passing response keeps the original status and headers. This is more honest than a full mock because the rest of the payload stays real.

Blocking what you don't need

Analytics, chat widgets and ad scripts slow tests down and occasionally fail. Abort them:

await context.route(/(google-analytics|hotjar|intercom)\./, (route) => route.abort());

You can also block by resource type to speed up data-heavy pages:

await page.route('**/*', (route) =>
  route.request().resourceType() === 'image' ? route.abort() : route.continue(),
);

Don't do this in visual regression tests, obviously, where the images are the point.

Record once, replay many times with HAR

Hand-writing mocks for a page that makes twenty calls is tedious. Record a HAR file from a real session and replay it:

// Record (run once, with update: true)
await page.routeFromHAR('tests/hars/dashboard.har', {
  url: '**/api/**',
  update: true,
});

// Replay (normal runs)
await page.routeFromHAR('tests/hars/dashboard.har', {
  url: '**/api/**',
  notFound: 'abort',
});

notFound: 'abort' fails loudly when the app makes a call the recording doesn't have, instead of silently going to the network. Commit the HAR files, review their diffs, and strip tokens and personal data before committing. Re-record when the API contract changes; a stale HAR is a mock that lies.

Waiting on the network, not on time

Instead of waitForTimeout, wait for the exact response you depend on and assert on it:

const saved = page.waitForResponse(
  (r) => r.url().endsWith('/api/settings') && r.request().method() === 'PUT',
);
await page.getByRole('button', { name: 'Save' }).click();
expect((await saved).status()).toBe(200);

Start waiting before the click, otherwise a fast response can arrive before the listener exists.

API tests with the request fixture

Playwright also ships an HTTP client, request, that shares config such as baseURL and extraHTTPHeaders. It is great for pure API tests:

test('creates a project', async ({ request }) => {
  const res = await request.post('/api/projects', { data: { name: 'smoke' } });
  await expect(res).toBeOK();
  expect(await res.json()).toMatchObject({ name: 'smoke' });
});

The bigger win is using it for setup. Creating test data through the UI costs seconds per test; through the API, milliseconds. A fixture that creates data via request and deletes it afterwards keeps tests independent:

export const test = base.extend<{ project: { id: string } }>({
  project: async ({ request }, use) => {
    const res = await request.post('/api/projects', { data: { name: `e2e-${Date.now()}` } });
    const project = await res.json();
    await use(project);
    await request.delete(`/api/projects/${project.id}`);
  },
});

When not to mock

Mocks test your frontend against your assumptions about the backend. If the assumptions are wrong, every test is green and production is broken. I keep a split: most UI tests mock the network for speed and determinism, and a small smoke suite runs against a real environment with no routes at all. That suite is what catches contract drift. How to balance the layers is covered in the tool comparison and the mobile test strategy posts.

Conclusion

Register routes before navigating, prefer route.fetch plus small edits over full fakes, block third-party noise, replay HAR files with notFound: 'abort', wait on responses instead of timers, and create test data through request. Keep one unmocked smoke suite so your mocks never drift away from reality unnoticed.

All articles →