Skip to content

Network Mocking Interview Questions for Playwright Testing

34 Network Mocking questions with answers for playwright testing roles — 6 easy, 21 medium, 7 hard.

About Network Mocking

Covers intercepting traffic with page.route and context.route, fulfilling, modifying and aborting requests, HAR replay, waiting for requests and responses, WebSocket mocking and offline testing. Interviewers ask how you test error states, slow APIs and third-party services, and how you balance mocked tests against real end-to-end coverage.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What does page.route do?

Save to ▾
Show answer
page.route registers a handler for requests whose URL matches a pattern. Inside the handler you can let the request continue, change it, return a fake response or abort it. It lets you test the UI against controlled data without depending on a real backend. Register routes before the action that triggers the request, usually before page.goto.
02

What is the difference between route.fulfill, route.continue and route.abort?

Save to ▾
Show answer
route.fulfill returns a response you define, such as a status, headers and JSON body, without contacting the server. route.continue sends the request on, optionally with changed URL, method, headers or body. route.abort fails the request with a network error such as 'failed' or 'blockedbyclient'. route.fallback passes it to the next matching handler.
03

How do you block images and fonts to speed up tests?

Save to ▾
Show answer
await page.route(/\.(png|jpe?g|webp|woff2?)$/, route => route.abort()); // or by resource type await page.route('**/*', route => route.request().resourceType() === 'image' ? route.abort() : route.continue() );
04

Why mock the network in UI tests at all?

Save to ▾
Show answer
Mocking makes tests fast, stable and independent of backend data or third-party outages. It also lets you test states that are hard to create for real, such as empty lists, errors or huge responses. The trade-off is lower confidence that frontend and backend work together, so keep some unmocked end-to-end tests for critical journeys.
05

Describe a time you argued against mocking every API in the suite.

Save to ▾
Show answer
Situation: a teammate proposed mocking all APIs to make the suite fast. Task: keep speed without losing integration coverage. Action: I showed two recent bugs caused by API changes that mocks would have hidden and proposed mocking only third parties and error states, keeping ten real end-to-end journeys. Result: the team agreed and the next contract change was caught before release.
06

What is a HAR file?

Save to ▾
Show answer
HAR stands for HTTP Archive. It is a JSON file that records the requests and responses a browser made, including URLs, headers, bodies and timings. Browsers can export one from DevTools, and Playwright can record and replay them. In testing it is used for mocking whole sets of API calls and for sharing network evidence in bug reports.
07

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
08

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
09

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
10

How do you change part of a real API response?

Save to ▾
Show answer
await page.route('**/api/profile', async route => { const response = await route.fetch(); const json = await response.json(); json.plan = 'premium'; await route.fulfill({ response, json }); }); await page.goto('/account'); await expect(page.getByText('Premium plan')).toBeVisible();
11

What is the difference between page.route and context.route?

Save to ▾
Show answer
page.route applies only to requests from that page. context.route applies to every page in the browser context, including pop-ups and new tabs opened later. Use context.route when a flow opens new windows, such as a payment pop-up, or when you set up mocks in a fixture before the page exists. Page routes take priority over context routes.
12

How do you mock network traffic using a HAR file?

Save to ▾
Show answer
Record once with page.routeFromHAR('data/orders.har', { url: '**/api/**', update: true }) while running against a real server. Later runs replay the saved responses from the HAR instead of hitting the backend. You can edit the stored JSON to create edge cases. Re-record when the API changes, otherwise the replay drifts from reality.
13

Why should you start waitForResponse before the action that triggers it?

Save to ▾
Show answer
If you click first and then wait, the response may already have arrived, so the wait misses it and times out. Create the promise first, then act, then await it: const resp = page.waitForResponse('**/api/cart'); await addButton.click(); await resp. waitForRequest works the same way for outgoing requests.
14

Your mocked route never fires. What do you check?

Save to ▾
Show answer
Check that the route is registered before the request is sent, usually before goto. Compare the pattern with the real URL in the trace network tab, including query strings and host. Make sure a service worker is not handling the request, and set serviceWorkers: 'block' if it is. Also check that another handler is not matching first or the route was not removed.
15

How do you test how the UI handles a 500 error from the orders API?

Save to ▾
Show answer
Mock the endpoint with route.fulfill({ status: 500, json: { message: 'Server error' } }), then open the page. Assert the user sees a friendly error message and a retry button, and that no broken half-rendered table appears. Then make the retry return 200 and check the data loads. This covers a path that is hard to trigger on a real server.
16

How do you simulate a slow API to test a loading spinner?

Save to ▾
Show answer
await page.route('**/api/report', async route => { await new Promise(r => setTimeout(r, 3000)); await route.continue(); }); await page.getByRole('button', { name: 'Generate' }).click(); await expect(page.getByRole('progressbar')).toBeVisible(); await expect(page.getByRole('progressbar')).toBeHidden();
17

How do you listen to all network requests on a page?

Save to ▾
Show answer
Subscribe to events: page.on('request', r => ...), page.on('response', r => ...) and page.on('requestfailed', r => ...). You can log URLs, collect API calls or count failures. Unlike route, listeners only observe and cannot change traffic. They are handy for checks like 'no request returned a 5xx status during this flow'.
18

How do you assert that a request was sent with the correct payload?

Save to ▾
Show answer
const reqPromise = page.waitForRequest(r => r.url().endsWith('/api/orders') && r.method() === 'POST' ); await page.getByRole('button', { name: 'Place order' }).click(); const req = await reqPromise; expect(req.postDataJSON()).toMatchObject({ qty: 2, sku: 'MOU-01' });
19

How do you test offline behaviour?

Save to ▾
Show answer
Call context.setOffline(true) to cut all network access for the context, then check that the app shows an offline banner or queues actions. Switch back with setOffline(false) and verify it syncs. You can also set offline: true in the context options. For a single failing endpoint, use route.abort instead of going fully offline.
20

How does URL matching work in page.route?

Save to ▾
Show answer
The first argument can be a glob string, a regular expression or a function that receives a URL object. Globs like '**/api/users*' are simple but * does not cross slashes and ** does. Regex gives precise control over query strings. A predicate function suits complex rules, for example matching host plus a specific search parameter.
21

A third-party analytics script makes tests slow and flaky. What do you do?

Save to ▾
Show answer
Block it in tests with context.route on its domain and route.abort, or fulfill it with an empty script. Analytics is not what you are testing, and blocking it removes delays and random network errors. If tracking events matter, write a few separate tests that capture the requests with waitForRequest and assert their parameters.
22

How do you mock one GraphQL query when all calls go to /graphql?

Save to ▾
Show answer
await page.route('**/graphql', async route => { const body = route.request().postDataJSON(); if (body.operationName === 'GetCart') { return route.fulfill({ json: { data: { cart: { items: [] } } } }); } return route.fallback(); });
23

How do you add or change request headers for only some requests?

Save to ▾
Show answer
Register a route for the matching URLs and call route.continue({ headers: { ...route.request().headers(), 'x-test-mode': 'true' } }). Other requests are untouched. For headers on every request, use extraHTTPHeaders in the config instead. This is useful for feature toggles, tenant ids or bypass tokens that only certain endpoints accept.
24

The app polls a status endpoint every few seconds. How do you test the change from Pending to Done?

Save to ▾
Show answer
Mock the endpoint with a counter: return Pending for the first two calls and Done after that. Then assert the UI shows Pending and later Done using web-first assertions with a suitable timeout. You can also use page.clock to speed up the polling interval instead of waiting real seconds. This makes a slow real-world process quick and deterministic.
25

Tell me about a time mocking helped you test a hard edge case.

Save to ▾
Show answer
Situation: we could not reproduce a bug where the cart broke when the stock API returned zero for one item. Task: cover it with a test. Action: I mocked only the stock endpoint with route.fetch and changed one item's quantity, then asserted the out-of-stock label. Result: the bug was fixed and the test now protects that case on every run.
26

How do you return a fake JSON response that depends on the request body?

Save to ▾
Show answer
await page.route('**/api/quote', async (route) => { const body = route.request().postDataJSON(); const price = body.plan === 'pro' ? 999 : 299; await route.fulfill({ status: 200, json: { plan: body.plan, price }, }); });
27

How do you test that the app retries a request that failed the first time?

Save to ▾
Show answer
Register a route with a counter: on the first call use route.fulfill with status 503, and on later calls fulfil with a success body. Perform the action, then assert the UI shows the final data and the counter equals 2. You can also check that no error message flashed. This proves the retry logic works without waiting for a real outage.
28

When should you avoid mocking, and how do you balance mocked and real tests?

Save to ▾
Show answer
Avoid mocking in a small set of critical end-to-end journeys, such as signup, payment and checkout, where integration matters most. Use mocks for UI states, error handling and third-party services. Back the mocks with API contract tests so they match reality. A healthy split is many fast mocked component-level tests and a thin layer of full-stack tests.
29

Mocked responses drift from the real API and tests pass while production breaks. How do you prevent this?

Save to ▾
Show answer
Generate mock data from the API schema or real recorded responses instead of hand-writing it. Validate mocks against the OpenAPI schema in a unit test. Add contract tests on the backend side and re-record HAR files on a schedule. Keep a few unmocked end-to-end tests that run after each deploy. Treat mock files as code with owners and reviews.
30

How do you mock WebSocket traffic in Playwright?

Save to ▾
Show answer
Use page.routeWebSocket with a URL pattern. The handler gets a WebSocketRoute: you can reply to messages with ws.onMessage and ws.send without any server, or call connectToServer() to sit in the middle and change messages in both directions. This lets you test live dashboards and chat apps, for example pushing a fake price update.
31

A feature is controlled by a flag served from a config API. How do you test both states?

Save to ▾
Show answer
Mock the config endpoint in a fixture option so each test chooses the flag value, for example featureFlags: { newCheckout: true }. Run the flow with the flag on and off and assert the different UI. Mocking avoids changing shared environment settings that would affect other testers. Also keep one test against the real config to catch wiring mistakes.
32

How do you mock a paginated endpoint that returns different data per page?

Save to ▾
Show answer
await page.route('**/api/products?*', route => { const url = new URL(route.request().url()); const p = Number(url.searchParams.get('page') ?? 1); const items = Array.from({ length: 10 }, (_, i) => ({ id: (p - 1) * 10 + i })); return route.fulfill({ json: { items, hasNext: p < 3 } }); });
33

How can service workers interfere with network mocking?

Save to ▾
Show answer
If the app registers a service worker, it may answer requests from its own cache, so page.route never sees them and mocks seem ignored. Set serviceWorkers: 'block' in the context or config options to turn them off when mocking. If you specifically test offline or PWA caching, keep them enabled and test that behaviour separately.
34

A fixture mocks every /api call, but one test needs a different response for /api/cart. How do you override it?

Save to ▾
Show answer
Register a new page.route for /api/cart inside that test. Handlers run in reverse order of registration, so the newer one runs first. Fulfil the cart request with the special data, and for anything else call route.fallback() so the request moves on to the fixture's general handler. This keeps the shared mock untouched and makes the override local and easy to read.

Frequently asked questions

How important is Network Mocking in Playwright Testing interviews?

Covers intercepting traffic with page.route and context.route, fulfilling, modifying and aborting requests, HAR replay, waiting for requests and responses, WebSocket mocking and offline testing. Interviewers ask how you test error states, slow APIs and third-party services, and how you balance mocked tests against real end-to-end coverage.

How should I use the Network Mocking sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.