QA AND TEST AUTOMATION · PART 5 · UI WEB AUTOMATION · TECHNIQUE · 56 OF 112

Network Mocking in UI Tests: Routes and Intercepts

Controlling what the API returns to the browser so UI states are easy to test: Playwright page.route to fulfil, modify or abort requests, run for real on ShopRung (empty results, a 500 with its message, a 120-character product name, and an offline error that showed the raw text "Failed to fetch"), plus HAR replay, Cypress intercept and Selenium BiDi, and when not to mock.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • page.route
  • fulfil, modify, abort
  • route before goto
  • HAR replay
  • cy.intercept
  • do not mock everything

Notes

How it works

Here is how it works. When the page makes a request, the browser checks whether the test registered a route for that URL. If not, the request goes to the real API. If so, your handler decides: fulfil it with a fake response, continue it, perhaps with changes, fetch the real response and modify it, or abort it to simulate a network failure. The page cannot tell the difference.

Interception
  • the page calls fetch()
  • the browser asks Playwright: any route for this URL?
  • no → request goes to the API
  • yes → your handler decides: fulfill (fake response) continue (maybe changed) fetch + modify the real one abort (network failure)

Empty state

First, the empty state. Register a route for the products API that fulfils with a count of zero and no items. Register routes before the page loads, then go to the home page. ShopRung showed no products match your search, and zero products. With real data, the shop always has twelve products, so without mocking this state would never be tested until a real customer met it.

No products at all
await page.route(
  "**/api/products?*", route =>
  route.fulfill({ json:
    { count: 0, items: [] } }));
await page.goto("/");
await expect(page.getByTestId(
  "no-results")).toBeVisible();

saw: "No products match your
  search." and "0 products"

Server error

Next, a server error. Fulfil with status five hundred and an error body whose message says database unavailable. ShopRung showed that message in its error area, with no crash and no blank page. You can check every error your API documents this way: four oh one sends the user to log in, four oh nine shows the conflict, five hundred shows a friendly message.

Fake a 500
route.fulfill({
  status: 500,
  json: { error: "internal",
    message: "Database
      unavailable" } })

expect(getByTestId("error"))
  .toBeVisible()
saw: "Database unavailable"
no crash, no blank page

Modify the real one

Often you want real data with one odd value. Fetch the real response inside the route, change one field, here the first product's name becomes one hundred and twenty letters, and fulfil with the modified body. Everything else stays real. Now you can check the card layout with a very long name, prices with many digits, or a missing optional field, all without touching the database.

Edge-case data
await page.route("**/api/products?*",
  async route => {
  const response = await route.fetch();
  const body = await response.json();
  body.items[0].name = "A".repeat(120);
  await route.fulfill(
    { response, json: body });
});

checks layout with a 120-char
  name, all else real

Offline

Finally, abort the request as if the internet disconnected. ShopRung showed the text failed to fetch. That is the browser's raw technical error, shown directly to a shopper. It is not a crash, but it is a usability issue worth raising: a message like you seem to be offline, try again, with a retry button, would be better. Mocking found it in seconds.

Network failure
route.abort("internetdisconnected")

ShopRung showed:
  "Failed to fetch"

the raw browser error, shown
  to a shopper
→ worth raising: say "You
  seem to be offline. Try
  again." with a retry

Patterns

Routing details. URLs can be glob patterns, like any path containing api slash products with a query, or regular expressions. Page route covers one page; context route covers every page and popup in the context. Inside a handler, read the request's method, to mock only posts, for example. Unroute removes a route. And route from HAR replays a recorded HAR file of real traffic, a quick way to run UI tests without a backend.

Routing details
"**/api/products?*"  glob
/\/api\/orders\/\d+$/  regex
page.route(...)   this page
context.route(...) all pages
route.request().method()
  → mock only POSTs
page.unroute(url)
page.routeFromHAR("shop.har")
  replay recorded traffic

Other tools

Other tools. Cypress has intercept, which matches a method and URL and returns a fixture body, very similar in spirit. Selenium four is adding network interception through WebDriver BiDi, though the APIs are newer and vary by language. A common Selenium approach is still to point the app at a mock server, like WireMock from Part four, through a configurable API address.

Equivalents
// Cypress
cy.intercept("GET",
  "/api/products*",
  { body: { count: 0, items: [] } })

// Selenium 4 (BiDi network
//   interception, newer APIs)
// or a proxy / WireMock behind
//   a configurable API URL

When not to mock

Know when not to mock. Mock to test UI states: empty, errors, slowness and odd data. Do not mock the happy path of critical journeys like checkout, or you only test the front end against your own imagination. Keep fakes realistic by copying real responses and checking them with schemas or contract tests from Part four. And keep a few full end to end tests against the real API.

Balance
  • mock to test UI STATES: empty, errors, slow, odd data
  • do not mock the happy path of critical journeys
  • keep fakes realistic: copy real responses, use schemas or contract tests (Part 4)
  • a few full end-to-end tests must hit the real API

Common mistakes

Mocking mistakes. Registering a route after the page has already sent the request, so the mock never applies. URL patterns so broad they catch requests you did not mean to mock. Fake responses that drift away from the real API. Mocking the happy path of checkout so the real integration is never tested. And forgetting to set status codes, so an error body arrives with two hundred.

Avoid these
  • registering routes AFTER goto (request already sent)
  • patterns too broad (mock everything by accident)
  • fakes that drift from the real API
  • mocking the happy path of checkout
  • forgetting status codes

Say it like this

In the interview: I use network interception. With Playwright's page route I fulfil empty lists, server errors and odd data, modify real responses, or abort requests to simulate going offline, always registering routes before navigation. I keep fakes close to real responses, backed by schemas or contracts, and leave the main journeys unmocked in a small set of end to end tests.

In the interview
  • "With network interception: page.route fulfils empty lists, 500s and odd data, modifies
  • real responses, or aborts to simulate offline, registered
  • before navigation. I keep
  • fakes close to real responses
  • and leave critical journeys
  • unmocked in a few E2E tests."

Interview questions

Q1What is network mocking in UI tests?

Intercepting the browser's HTTP requests in the test and answering them with controlled responses, to reach UI states that real data rarely produces.

Q2How do you mock an API response in Playwright?

page.route(urlPattern, route => route.fulfill({ status, json })) registered before the page makes the request.

Q3How do you modify a real response in Playwright?

Inside the route handler, call route.fetch(), change the parsed body, then route.fulfill({ response, json: changedBody }).

Q4How do you simulate a network failure?

route.abort() with an error code such as "internetdisconnected" or "failed".

Q5What is the Cypress equivalent of page.route?

cy.intercept(method, url, response) to stub, or with a handler to inspect and modify requests and responses.

Q6What is HAR replay?

Recording real network traffic to a HAR file and serving responses from it in tests (page.routeFromHAR), so UI tests run without a live backend.

Q7When should you not mock the network?

For the happy path of critical end-to-end journeys, which must exercise the real API; keep some unmocked tests.

Q8Why must routes be registered before navigation?

Requests sent before the route exists go to the real network, so the mock never applies.