QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Network: route and mocks

HAR: recording and replaying traffic

A HAR is a JSON file recording HTTP traffic, which Playwright records and replays as a mock through routeFromHAR. It works as automatically generated mocks that need no backend. The downside is that the recording goes stale with the API while the test stays green, so a HAR is re-recorded regularly and cleaned of tokens. Replay is limited to API URLs with url, and edge cases get a manual page.route.

Playwright · Network

The API changed, yet the HAR-based tests are still green. What do they check then?

A HAR (HTTP Archive) is a JSON file with a recording of HTTP traffic: requests, responses, headers, bodies, timings. Playwright can both record it and replay it as a mock. This is useful when the backend is unstable, expensive or depends on third-party services, while the frontend is what needs testing. It is "automatically generated mocks": instead of a manual fulfill for every endpoint, the test takes a real response recorded earlier. The price is that the recording goes stale together with the API while the test stays green.

How it works and why. routeFromHAR has two modes. With update: true requests go to the real network and the file is rewritten. Without it, the page request is looked up in the file by URL, method and body, and on a match the response comes from the file. The url option limits what is handled: usually only the API, while static files load as usual. notFound decides the fate of requests with no match: 'abort' (the default) drops them, 'fallback' lets them through to the network. A typical scheme is a switch through an environment variable, so the file is refreshed with one command.

Recording and replaying a HAR

record (update: true) page backend .har file replay (no update) page HAR lookup: URL, method, body match: responsefrom the file none: abort orfallback to network
Figure 1. One method works in both modes. What happens without a match is decided by notFound.
test('catalog from HAR', async ({ page }) => {
  await page.routeFromHAR('hars/catalog.har', {
    url: '**/api/**', // only the API; static files load as usual
    update: process.env.UPDATE_HAR === '1', // true: real network, file rewritten
    notFound: 'fallback', // missing in the HAR: go to the network (default: abort)
  });
  await page.goto('/catalog');
  await expect(page.getByRole('listitem')).toHaveCount(12);
});

Example: a HAR exists, yet the page is "broken". A test replays a HAR with no options. The page loads empty, with errors for scripts and styles in the console. The cause: by default any request is looked up in the file, and there is no static content in it (only the API was recorded), so notFound: 'abort' drops those too.

// before: no url filter, the default notFound is 'abort'
await page.routeFromHAR('hars/catalog.har');
await page.goto('/catalog'); // scripts, styles and fonts are not in the file

The fix is to limit the replay to API addresses: everything else passes as usual.

// after: only the API comes from the file, the rest loads as usual
await page.routeFromHAR('hars/catalog.har', { url: '**/api/**' });
await page.goto('/catalog');

How to record. The context option recordHar records the traffic of the whole context; urlFilter keeps only what is needed. The file is written only on context.close(), so without closing the context there is no HAR. Another way: click through the scenario by hand under codegen.

// recording with a context option: the file is written when the context closes
const context = await browser.newContext({
  recordHar: { path: 'hars/checkout.har', urlFilter: '**/api/**' },
});
const page = await context.newPage();
await page.goto('/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
await context.close(); // without close() there is no file
npx playwright codegen --save-har=hars/checkout.har --save-har-glob="**/api/**" https://app.test

The recording mode can be tuned: updateContent chooses whether to embed bodies into the HAR ('embed') or store them as separate files ('attach'; for a path with the .zip extension the files are collected into an archive), and updateMode chooses a full ('full') or minimal ('minimal') recording: minimal keeps only what is needed for replay.

HAR and manual mocks together. Replay does not exclude point substitutions. For an edge case, one endpoint is overridden with an ordinary page.route registered later: as everywhere, the last registered handler runs first.

await page.routeFromHAR('hars/catalog.har', { url: '**/api/**', notFound: 'fallback' });

// one endpoint is overridden by hand: the route registered later runs first
await page.route('**/api/catalog/stock', (route) => route.fulfill({ json: { inStock: 0 } }));

await page.goto('/catalog');
await expect(page.getByRole('button', { name: 'Add to cart' }).first()).toBeDisabled();

Limits worth mentioning. First, a HAR goes stale together with the API: the contract changed and the test stays green, so the files are refreshed regularly (for example by a separate CI job with update). Second, tokens, cookies and personal data end up in the file, so it is reviewed and cleaned before committing. Third, a request is matched by URL, method and body, so dynamic parameters such as a timestamp or a random id in the query break the matching: the request either fails or goes to the network through fallback. Finally, a large HAR bloats the repository.

When a HAR and when a manual route:

CriterionHARManual route
Effort at the startminimal: record and donedescribe every response
Data realismhigh, it is real trafficdepends on the author
Edge stateshard: the file has to be editedeasy: write the needed state
Maintenancegoing stale, re-recordingchanges to mock code
Readability in reviewa huge JSON diffa short function in the test

Common mistakes.

  • Not closing the context after recordHar: the file is never written.
  • Replaying a HAR without url: static files and third-party scripts are dropped too.
  • Committing a HAR with live tokens.
  • Never refreshing the HAR: the test checks a stale contract.
  • notFound: 'fallback' on CI with no marker: the test quietly goes to the real network and becomes unstable.

Check yourself

The backend renamed a field in a response, yet the HAR-based suite stayed green. Why, and how would you detect it?

Answer

The test replays the old recording and the backend is never called, so it cannot see the contract change. It is caught by regular re-recording of the HAR (a separate CI job with update) and reviewing the diff of the file, as well as by contract or API tests against the real backend.

A request has a dynamic parameter ?_=1731000000. How does it affect the replay, and what do you do?

Answer

A request is matched by URL, method and body, so one with a new parameter value does not match the recorded one: it is dropped by notFound: 'abort' or let through to the network by 'fallback'. The fix: remove the unstable parameter from the request, and when that is impossible, replace that endpoint with a manual page.route.

In an interview. Junior: A HAR is a recording of traffic that Playwright replays through routeFromHAR, so the test does not depend on the backend. Middle/Senior: I record with update, limit the replay to the API with the url option, refresh the file regularly so the test does not check a stale contract, and watch that no tokens end up in it. I add edge states with a separate page.route, because they are hard to get from a HAR.

More articles in this chapter