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

Playwright

Network: route and mocks

Working with the network: page.route and mocks

With page.route a test decides what to answer to a request. Playwright sits between the page and the network, and the handler must call fulfill, continue, abort or fallback. A route intercepts only requests that start after it is registered, so it is declared before the action that triggers them. Mock errors, edge-case data and third-party services, and keep the happy path on the real backend.

Playwright · Network

The mock is registered, yet the page shows real backend data. What went wrong?

An "empty list" test registers a page.route that returns [], but the screen shows real cards from the backend. The backend is not to blame: the mock was registered after page.goto, and the request had already gone to the network. Below: how Playwright intercepts requests, what a handler must do, and where a mock hurts instead of helping.

How it works and why. The network is the best lever for controlling application state in an E2E test. Instead of preparing data on the backend and hoping it returns an empty list or an error, the test decides what to answer. Playwright sits between the page and the network: when the browser is about to send a request, it waits while Playwright asks the registered handlers in turn. Three things follow. A handler must make a decision, because the browser is waiting. Only requests that started after the registration are intercepted. And this is at browser level, so route sees any request of the page: fetch, XHR, images, scripts.

What happens to a request that route intercepted

the page sends a request page.route handler fulfill continue abort responsefrom the test the realbackend networkerror no call in the handler:the request hangs, the test times out
Figure 1. The browser waits for the handler to decide. fallback is not shown: it passes the request to the next handler in the chain, not to the network.

Four actions on a request. page.route takes a URL pattern (glob, regular expression or function) and a handler. The handler calls one of: route.fulfill (own status, headers and body; the json parameter is handy), route.continue (let it through, changing headers, method or body), route.abort (abort with an error code) or route.fallback (hand it to the next handler).

// a mock: our status and body, the request never reaches the backend
await page.route('**/api/accounts', (route) =>
  route.fulfill({ status: 200, json: [{ id: 1, name: 'Main', balance: 1200 }] }),
);

// an error response to see how the UI reacts
await page.route('**/api/transfers', (route) =>
  route.fulfill({ status: 500, json: { error: 'Internal error' } }),
);

// cut off what the test does not need: faster and more stable
await page.route('**/*.{png,jpg,jpeg}', (route) => route.abort());

// let the request through, but change it
await page.route('**/api/reports', (route) =>
  route.continue({ headers: { ...route.request().headers(), 'x-test-run': 'e2e' } }),
);

Example: the mock is there, but has no effect. The test has to show the empty state of the accounts list. It fails: the page shows accounts from the backend and there is no "No accounts yet" text. The mock looks right, so does the pattern. The cause is the order: by the time of the registration, page.goto had already waited for the load, and the request for accounts went out during it.

// before: the route comes after the navigation
await page.goto('/accounts');
await page.route('**/api/accounts', (route) => route.fulfill({ json: [] }));
await expect(page.getByText('No accounts yet')).toBeVisible();

The fix is the order of actions: first the route, then whatever triggers the request. The temptation to "add a wait" or a page.reload() after the mock also works, but it is a workaround: the test makes an extra request and hides the cause.

// after: first the route, then the action that triggers the request
await page.route('**/api/accounts', (route) => route.fulfill({ json: [] }));
await page.goto('/accounts');
await expect(page.getByText('No accounts yet')).toBeVisible();

route.fetch: change part of a real response. When you need not an invented response but a slightly spoiled real one, get it through route.fetch(), edit it and return it through fulfill({ response, json }). Status and headers stay real, while the UI is checked on edge data: an overdraft, a very long name.

await page.route('**/api/accounts', async (route) => {
  const response = await route.fetch(); // the real response of the backend
  const accounts = await response.json();
  accounts[0].balance = -50; // an edge case: overdraft
  accounts.push({ id: 99, name: 'A'.repeat(300), balance: 0 }); // a very long name
  await route.fulfill({ response, json: accounts });
});

await page.goto('/accounts');
await expect(page.getByTestId('balance-1')).toHaveClass(/negative/);

States that are hard to get. A mock solves three classes of tasks: errors and slow responses (500, connection drop, spinner), empty and extreme data, and isolation from third-party services (payment gateway, SMS, analytics). For GraphQL all requests go to one URL, so the handler branches on operationName. The times option limits the number of triggers: handy for "the first request fails, the retry passes".

// a slow response: the spinner stays visible
await page.route('**/api/transactions*', async (route) => {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  await route.fulfill({ json: [] });
});

// GraphQL: one URL for everything, so branch on the operation
await page.route('**/graphql', async (route) => {
  const { operationName } = route.request().postDataJSON() ?? {};
  if (operationName === 'Accounts') {
    return route.fulfill({ json: { data: { accounts: [] } } });
  }
  return route.fallback(); // everything else goes to earlier handlers
});

// a one-off failure: the first call fails, the retry in the UI succeeds
await page.route('**/api/payments', (route) => route.abort('failed'), { times: 1 });

Scope. page.route works for one page, context.route for all pages of the context, including new tabs; if both apply, page routes take precedence. WebSocket has its own page.routeWebSocket. Requests that go through a Service Worker are not seen by a route until it is disabled with serviceWorkers: 'block'. How to record the mocks as a whole file is described in the HAR lesson.

Limits: what not to mock. A mock is a snapshot of the contract at the time of writing, and it goes stale silently: the backend changed a field, while the test with the mock stays green. So mock what is missing (errors, edge data, external services) and keep the main happy path on the real backend.

Two approaches to mocks in a suite

Typical

Everything mocked

The suite is fast and stable, but it checks the frontend only against its own inventions. A contract change on the backend goes unnoticed.

Better

Mock only what is missing

The happy path hits the real backend and catches integration bugs. Mocks cover errors, empty and extreme states and third-party services.

Figure 2. A mock complements the real backend rather than replacing it.

Common mistakes.

  • page.route after page.goto: requests that already went out are not affected by the mock.
  • A handler with a branch that calls none of fulfill, continue, abort or fallback: the request hangs and the test times out.
  • A pattern that is too broad (**/api/**): things that should go to the network get mocked.
  • A mock with no UI check: the test is green and it is unknown whether the mock applied.
  • The whole E2E suite on mocks: contract changes go unnoticed.

Check yourself

A mock on **/api/accounts is registered in beforeEach, yet in one test the page still shows real data. What should you check first?

Answer

Whether that test has a page.goto or an action that triggers the request before the route is registered. Then: whether the pattern matches the full URL (a glob * does not cross /) and whether the request goes through a Service Worker.

A route handler has if (cond) route.fulfill(...) with no else. What happens when cond is false?

Answer

The request keeps waiting for a decision: the browser does not send it on its own. The test fails by timeout, not with an error about the mock. Every branch must call continue, fallback, fulfill or abort.

In an interview. Junior: page.route intercepts a request and lets me substitute the response with fulfill, abort it with abort or let it through with continue. I declare the route before the action that triggers the request. Middle/Senior: For edge states (an empty list, a 500, a slow response) I use fulfill, and when only part of the real response must change I take route.fetch. I do not mock everything: the happy path stays on the real backend so integration bugs stay visible, and I type the mocks from the same schemas as the backend.

Observe or replace: waitForResponse, waitForRequest, route

waitForRequest and waitForResponse only observe real traffic, while page.route controls it and can replace the response. An event that happened before the subscription is lost, so the wait promise is created before the click and awaited after it. When several route handlers match a URL, the last registered runs first; fallback() passes the request on, while continue() sends it to the network.

Playwright · Network

waitForResponse hangs until the timeout, although the response has already arrived. Why?

A test clicks "Place order", waits with waitForResponse and fails by timeout, although the network tab shows a 201 response. The listener started working after the response had arrived. This is part of a wider confusion: a test has two different network tasks, to observe real traffic and to control it. For the first there are waitForRequest and waitForResponse, for the second page.route.

How it works and why. Both waits subscribe to the stream of page events and resolve a promise when a request or response passing the predicate shows up. They change nothing: the request goes to the real backend, the test only watches. An event that happened before the subscription is lost, so the promise is created before the action and awaited after it. route, by contrast, puts a handler in the request's path and decides its fate. These are different roles: the first proves what the frontend did, the second creates conditions the backend will not give.

Observe or control

Observing

Observe: waitForRequest / waitForResponse

The request goes to the real backend. The test checks the request body, status and response data without interfering with the traffic.

Controlling

Control: page.route

The request is intercepted before the network. The test substitutes the response, simulates an error or delay, changes headers.

Figure 1. These are different tools, and a strong test often combines both: a mock on the way in, observation of the result.

Example: the response beat the listener. First the mistake everyone who wrote such tests knows.

// before: the listener starts after the click
await page.getByRole('button', { name: 'Place order' }).click();
const response = await page.waitForResponse('**/api/orders');
expect(response.status()).toBe(201);

The click sends the request, and if the backend answered quickly, the event had already happened when the waitForResponse line started listening. The promise never resolves and the test fails by timeout, and how often depends on who is faster in a given environment, the backend or the test process: a classic flake. The fix: the promise before the click, await after it. The Promise.all variant guarantees the order and is handy when you need the response itself:

// after: the promise before the click, the await after
const [response] = await Promise.all([
  page.waitForResponse((r) => r.url().endsWith('/api/orders') && r.request().method() === 'POST'),
  page.getByRole('button', { name: 'Place order' }).click(),
]);
expect(response.status()).toBe(201);
const { id } = await response.json();
await expect(page).toHaveURL('/orders/' + id);

The predicate also checks the method: otherwise the first response to a GET of the same URL would end the wait. There are two nuances. The waitForResponse promise resolves as soon as the headers arrive, and the body is read with a separate response.json(). And a request that must not go out is checked with a collected list, not a wait: waitForRequest would wait until the timeout.

// a request that must NOT happen: collect, check at the end of the scenario
const sent: string[] = [];
page.on('request', (r) => {
  if (r.url().includes('/api/analytics')) sent.push(r.url());
});
await page.getByRole('button', { name: 'Reject cookies' }).click();
expect(sent).toEqual([]);

The list is checked at the end of the scenario, after the next actions or a navigation, not right after the click: a request sent a few milliseconds after the click is otherwise not in the list yet.

Do not put a fixed waitForTimeout in place of observation: it either wastes time or is too short.

The request body. To prove the frontend sent the right data, take the request from the wait and look at its payload:

const reqPromise = page.waitForRequest(
  (r) => r.url().includes('/api/transfers') && r.method() === 'POST',
);
await page.getByRole('button', { name: 'Transfer' }).click();
const req = await reqPromise;
expect(req.postDataJSON()).toMatchObject({ amount: 500, currency: 'UAH' });

Controlling: page.route. Nuances that get asked in interviews:

  • The pattern: a glob (**/api/users*), a RegExp or a function of the URL. In a glob * does not cross /, while ** does.
  • If several handlers are registered for a URL, the last registered runs first. route.fallback() passes the request to the previous handler (and may change headers or the URL), while route.continue() sends it straight to the network, bypassing the rest.
  • page.unroute removes a handler. page.unrouteAll({ behavior: 'ignoreErrors' }) is useful at the end of a test when handlers are still running.
  • A Service Worker can handle a request before Playwright, and then route does not see it. The fix: serviceWorkers: 'block' in the context options or config.
// registered first: a mock for the users
await page.route('**/api/users*', (route) => route.fulfill({ json: [{ id: 1 }] }));

// registered last: runs FIRST, adds a header and passes the request down the chain
await page.route('**/api/**', (route) =>
  route.fallback({ headers: { ...route.request().headers(), 'x-run': '42' } }),
);

await page.goto('/users'); // route.continue() above would skip the mock

// remove the handlers; ignoreErrors does not fail the test on handlers still running
await page.unrouteAll({ behavior: 'ignoreErrors' });

Handler order: who gets the request first

route #3 (last) gets the requestfirst fallback() route #2 fallback() route #1 (first) the mock ishere: fulfill() response to the page any continue():straight to network
Figure 2. The chain runs from the last registered to the first. fallback() passes on, continue() leaves the chain.
NeedToolReal backend?
Check the payload the frontend sentwaitForRequestyes
Get an id or data from a real responsewaitForResponseyes
Substitute a response, simulate an error or delayroute.fulfill / abortno
Change part of a real responseroute.fetch + fulfillyes, with edits
Add a header to all requestsroute.fallback / continueyes

Limits. Observation proves that the request went out and the response came, not that the UI showed it: after the wait you still need an assertion on the screen. A predicate on a general URL without method and body matches foreign requests. And a mock on the way in removes the real backend from the check: it will not confirm the contract.

Common mistakes.

  • waitForResponse after the click: if the response managed to arrive, the promise never resolves.
  • A predicate without a method check: the first response to a GET of the same URL ends the wait.
  • Waiting for "no request" with waitForRequest and a short timeout: it either wastes time or gives a false success.
  • continue instead of fallback in an intermediate handler: the lower mock handlers do not run.
  • A mock does not work because requests go through a Service Worker.

Check yourself

A test with await click(); await waitForResponse() is steadily green locally but flaky in CI. Why this way round and not the opposite?

Answer

The faster side wins the race: the backend's response or the next line of the test. Locally the listener usually makes it. On CI the workers are loaded and the test process lags between the click and the subscription, while the backend in the same environment answers fast, so the response arrives before the subscription and the promise never resolves. The order must be guaranteed by code: the promise before the click, await after, or Promise.all.

A test has two page.route on **/api/users*: first a mock, then a handler that adds a header and calls route.continue(). Does the mock run?

Answer

No. The last registered handler gets the request first, and continue() sends it to the network, bypassing the mock. To pass it down the chain you need route.fallback().

In an interview. Junior: waitForResponse and waitForRequest observe real traffic, while route substitutes a response. I create the wait promise before the click. Middle/Senior: I know the last registered handler runs first, fallback passes the request down the chain and continue goes straight to the network. I check a request that must not happen by collecting through page.on('request'). Observation proves that the request went out, and I check that the UI showed it with a separate assertion.

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.