PRACTICAL GUIDE / playwright network interview questions
20 Playwright Network Mocking and Routing Interview Scenarios
Practice 20 senior Playwright network scenarios on routing, HAR replay, service workers, WebSockets, pass-through traffic, and mock failure analysis.
In this guide9 sections
- Analyze the Traffic Before the Mock
- Routing Fundamentals
- 1. Why must a route usually be registered before navigation or the user action?
- 2. How would you mock one API response while allowing all other traffic through?
- 3. When would you use fallback instead of continue?
- 4. How would you modify a real response instead of replacing it completely?
- Request Matching and Observation
- 5. Why is a URL-only matcher sometimes too broad?
- 6. How would you wait for a specific response without racing the click?
- 7. Why are request and response event listeners not substitutes for route handlers?
- 8. How would you diagnose a mock that appears registered but never matches?
- HAR Capture and Replay
- 9. When is HAR replay a better fit than several handwritten handlers?
- 10. How would you keep HAR recording out of ordinary test execution?
- 11. What should happen when a request is missing from a replay fixture?
- 12. How would you sanitize a HAR before committing it?
- Service Workers and Browser Caches
- 13. Why can a service worker make network interception confusing?
- 14. How would you test an application that uses a service-worker mocking library?
- 15. How can browser cache produce a false conclusion about route call count?
- WebSockets and Streaming Traffic
- 16. How would you mock a WebSocket conversation instead of an HTTP endpoint?
- 17. How would you inspect or alter only some frames while keeping the real socket?
- 18. How would you test reconnect behavior deterministically?
- Failure Injection and Test Strategy
- 19. How would you test timeout and server-error handling without making the suite slow?
- 20. How would you decide which network tests remain real in CI?
- Network Review Checklist
- Conclusion: Make the Traffic Boundary Provable
What you will learn
- Analyze the Traffic Before the Mock
- Routing Fundamentals
- Request Matching and Observation
- HAR Capture and Replay
Network mocking interviews should expose whether a candidate understands the traffic path, not merely page.route. A senior SDET must decide which dependency is being replaced, register interception before the request, preserve useful pass-through behavior, and prove that a convenient fixture has not drifted away from the service contract.
The scenarios below move from simple HTTP routing to HAR replay, service workers, and WebSockets. In every answer, name the layer being tested, the layer being simulated, and the independent evidence that keeps the simulation honest.
Analyze the Traffic Before the Mock
The official Playwright network guide covers request observation, routing, modification, and response handling. Begin with the actual URL, initiator, timing, and service-worker path. Then choose interception, pass-through, or replay. A senior answer includes the failure mode because a mock that never matched can produce a dangerously convincing false pass.
Animated field map
Network Scenario Interview Flow
Trace the traffic, choose the interception layer, decide what remains real, and diagnose the specific mock failure before judging the answer.
01 / traffic scenario
Traffic scenario
Identify URL, method, initiator, protocol, and expected timing.
02 / interception layer
Interception layer
Choose page, context, HAR, socket, or service boundary.
03 / mock pass through
Mock or pass-through
Define replaced responses and traffic that remains real.
04 / failure mode
Failure mode
Detect misses, stale fixtures, ordering, and hidden workers.
05 / debugging answer
Candidate debugging answer
Defend assertions, contract checks, and cleanup.
Good candidates explicitly say when they would not mock. A critical real-service smoke path can be worth its environmental cost when contract confidence matters more than isolated UI diagnosis.
Routing Fundamentals
1. Why must a route usually be registered before navigation or the user action?
The request can begin as soon as navigation or the trigger runs. Registering afterward creates a race in which fast environments reach the real service and slow environments hit the mock. I would install routes in setup before the initiating action, then assert the mocked response's visible consequence. For a context-wide dependency, a context route may express ownership more clearly than repeating a page route.
2. How would you mock one API response while allowing all other traffic through?
I would match the narrow method and URL contract, fulfill only that request, and leave unrelated requests unhandled so normal traffic continues. The mock payload includes realistic schema fields needed by the UI and an explicit status and content type. I would avoid a broad **/* handler that accidentally replaces assets, analytics, or future endpoints.
await page.route('**/api/orders/ORD-42', async route => {
if (route.request().method() !== 'GET') {
await route.fallback()
return
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'ORD-42', status: 'ready' }),
})
})3. When would you use fallback instead of continue?
I would use fallback when another matching route handler may still need to process the request, such as layered authentication and scenario-specific mocks. Continue sends the request onward immediately and prevents later handlers from changing it. The design should keep handler order understandable; a stack of broad interceptors is difficult to review. I would test the final headers and response rather than assume each handler participated.
4. How would you modify a real response instead of replacing it completely?
I would fetch the original response through the route, parse only an approved content type, change the minimum field needed by the scenario, and fulfill with the original response plus the modified body. This preserves realistic headers and surrounding data while making the scenario deterministic. It still couples the test to a live service, so outages and contract changes remain possible and should be called out.
Request Matching and Observation
5. Why is a URL-only matcher sometimes too broad?
The same path may receive GET, POST, and retry requests with different bodies. A broad handler can fulfill a mutation with read data or hide duplicate submissions. I would inspect method, URL, and relevant payload inside the handler and fail or fall back for unexpected traffic. The test should assert call count or business outcome when duplicate requests are part of the risk.
6. How would you wait for a specific response without racing the click?
Create the response promise before triggering the action, then await both through a clear sequence. The predicate should include method, path, and status or another stable discriminator. Waiting after the click can miss a fast response. I would still assert the UI state because receiving HTTP success does not prove the application rendered or processed it correctly.
7. Why are request and response event listeners not substitutes for route handlers?
Listeners observe traffic and are useful for diagnostics or assertions, but they do not intercept or replace it. Route handlers control traffic. I would choose events when the real dependency should remain active and routing when the scenario needs deterministic behavior or failure injection. Mixing them is reasonable if the event assertion proves the expected request actually traversed the route.
8. How would you diagnose a mock that appears registered but never matches?
I would log safe request URLs and methods, inspect the trace, verify base URL and redirect behavior, and check whether registration preceded the trigger. Then I would test the glob or regular expression against the actual URL. If a service worker controls the page, I would inspect that path next. Making the glob broader before understanding the miss risks intercepting unrelated traffic.
HAR Capture and Replay
9. When is HAR replay a better fit than several handwritten handlers?
It fits a multi-request workflow whose captured responses form a coherent fixture, especially when hand-authoring every payload would be error-prone. The mocking guide supports recording and replay through routeFromHAR. I would still keep the captured scope narrow, sanitize it, and document the workflow and refresh process. Simple edge cases remain clearer as focused route handlers.
10. How would you keep HAR recording out of ordinary test execution?
Recording should be an explicit maintenance command or guarded mode, never an accidental result of running CI. Normal tests replay with updating disabled and a defined miss policy. I would review the diff after refresh, run schema or contract checks, and require approved credentials. Otherwise a routine run can silently rewrite expected data and turn a regression into the new fixture.
await page.routeFromHAR('tests/hars/catalog.har', {
url: '**/api/catalog/**',
update: false,
notFound: 'abort',
})11. What should happen when a request is missing from a replay fixture?
For a fully isolated scenario, aborting exposes fixture drift immediately. Falling back to live traffic may suit a partial mock, but it weakens determinism and must be intentional. I would select the behavior per test purpose and make unexpected live calls observable. A replay suite that silently reaches production or staging on misses no longer has a trustworthy dependency boundary.
12. How would you sanitize a HAR before committing it?
I would inspect request and response headers, cookies, authorization, query strings, bodies, identifiers, and personal data. Synthetic accounts reduce risk but do not remove the review. Sanitization should be repeatable and validated, not a one-time manual promise. If the file references external payload blobs, inspect those too. Any uncertain secret or customer data means the artifact is rejected and recaptured safely.
Service Workers and Browser Caches
13. Why can a service worker make network interception confusing?
A service worker can handle a request before page routing observes it, so the test may see no route event despite visible data. I would inspect worker registration and the request's service-worker origin. For tests whose purpose is Playwright routing, configure service workers to be blocked as described in the service-worker guide. For offline behavior, keep the worker and test that boundary directly.
14. How would you test an application that uses a service-worker mocking library?
First decide whether the test is validating application behavior with that library or Playwright's own interception. If Playwright must own routing, block service workers so requests reach its handlers. If the library is part of the test environment, configure and assert it deliberately. I would not layer both without clear ownership because a passing response would not reveal which mock supplied it.
15. How can browser cache produce a false conclusion about route call count?
A cached resource may not issue the network request expected by the test. I would distinguish API calls from cacheable static assets, use a fresh context for isolation, and inspect response provenance. Forcing reload or adding cache-busting parameters should match the scenario, not become a blanket fix. The assertion should focus on the application's required behavior unless request count itself is the contract.
WebSockets and Streaming Traffic
16. How would you mock a WebSocket conversation instead of an HTTP endpoint?
I would register routeWebSocket before the application opens the socket, handle page messages, and send deterministic server messages through the routed socket. If I do not connect to the server, the conversation is fully mocked. The test asserts both the expected outbound message and the resulting UI state. HTTP routing cannot substitute because WebSocket frames continue after the initial handshake.
await page.routeWebSocket('**/realtime', socket => {
socket.onMessage(message => {
if (message === JSON.stringify({ type: 'subscribe', room: 'ops' })) {
socket.send(JSON.stringify({ type: 'status', value: 'degraded' }))
}
})
})17. How would you inspect or alter only some frames while keeping the real socket?
Connect the route to the real server, then register message handlers only for directions that require inspection or modification. Once a handler takes ownership of a direction, it must forward allowed messages explicitly. I would keep transformations small and record safe frame types, not credentials or sensitive payloads. The scenario should state why a proxy is preferable to a complete mock.
18. How would you test reconnect behavior deterministically?
Use a routed socket to close the connection with a controlled reason, observe the UI's disconnected state, then provide the conditions for a new connection and send a recovery message. I would assert bounded reconnect behavior without relying on a long sleep. If backoff timing is central, combine controlled page time with connection counts. The test should ensure subscriptions are restored once, not duplicated after reconnect.
Failure Injection and Test Strategy
19. How would you test timeout and server-error handling without making the suite slow?
For server errors, fulfill the targeted request with the expected error status and structured body. For client timeout behavior, delay or withhold only the relevant response and control the application's timeout boundary when possible. I would assert the recovery UI, retry behavior, and absence of an invalid success state. Global network throttling adds noise and can obscure which dependency the scenario exercises.
20. How would you decide which network tests remain real in CI?
I would keep a small set of high-value integration paths against a controlled environment to verify contracts, authentication, and deployment wiring. Deterministic mocked tests cover UI branches, rare errors, and precise data states. Provider contract or API tests cover schemas outside the browser. The portfolio should identify an owner for fixture refresh and a signal for mock drift. No single layer can provide all three forms of confidence.
Network Review Checklist
- Register interception before the action that can issue traffic.
- Match method and business endpoint, not an overly broad URL alone.
- Make unexpected requests and HAR misses visible.
- Sanitize captured headers, bodies, cookies, and external payload files.
- Decide explicitly whether service workers are part of the scenario.
- Assert user-visible consequences as well as network activity.
- Preserve independent contract coverage for every mocked dependency.
Conclusion: Make the Traffic Boundary Provable
A network mock is trustworthy only when the test can prove which traffic it replaced and why. Trace the real path first, keep matchers narrow, fail visibly on fixture drift, and separate UI isolation from service compatibility. HAR, service-worker controls, and WebSocket routes are powerful because they model different boundaries; they are not interchangeable shortcuts. The senior choice is the one that leaves both determinism and contract risk explicit.
// LIVE COURSE / THE TESTING ACADEMY
Playwright Automation Mastery
Go beyond Selenium. Master Playwright with JS/TS in 90 days.
From the instructor behind this guide.
Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.
PRIMARY REFERENCES
Verify the details at the source
QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.
- 01Playwright documentation
Microsoft
Canonical API, locator, fixture, browser, and test-runner behavior.
- 02Playwright best practices
Microsoft
Official guidance for resilient tests, isolation, and user-facing locators.
- 03
FAQ / QUICK ANSWERS
Questions testers ask
What should a senior candidate explain before mocking a request?
They should identify the behavior under test, the owner of the real contract, why determinism is needed, what traffic remains real, and which assertion would detect a stale or incorrect mock.
When is HAR replay useful in Playwright?
HAR replay is useful for a stable captured interaction with many related requests. It can provide realistic deterministic responses, but the fixture must be reviewed, sanitized, updated deliberately, and backed by separate contract coverage.
Why might page.route not observe an expected request?
The route may have been registered after the request, the URL pattern may be wrong, or a service worker may be handling traffic before page routing sees it. Trace the request path before changing the matcher.
Should network mocks replace API integration tests?
No. Mocks isolate UI behavior and failure handling, while integration or contract tests verify compatibility with the real service. A balanced suite uses each layer for the evidence it can genuinely provide.
How should sensitive HAR data be handled?
Capture only approved environments and accounts, remove credentials and personal data, review headers and bodies, keep fixtures under controlled access, and fail closed if sanitization cannot be proven.
RELATED GUIDES
Continue the learning route
GUIDE 01
API Mocking with WireMock: Stubs, Tests, and Examples
API mocking with WireMock guide for QA teams covering stubs, request matching, delays, faults, recording, contracts, CI, and mistakes.
GUIDE 02
How to Test Microservices: A Practical QA Guide
Learn how to test microservices with service contracts, API checks, mocks, data strategy, resilience tests, and CI coverage for QA teams now.
GUIDE 03
Playwright API Testing: Validate APIs Inside Your E2E Suite
Playwright API testing guide covering request contexts, setup flows, assertions, authentication, fixtures, UI strategy, and CI-ready checks.
GUIDE 04
How to Test an API Without Documentation
Learn how to test an API without documentation: discover endpoints, reverse engineer contracts, design cases, validate auth, and avoid common blind spots.