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
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.
Control: page.route
The request is intercepted before the network. The test substitutes the response, simulates an error or delay, changes headers.
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), whileroute.continue()sends it straight to the network, bypassing the rest. page.unrouteremoves 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
routedoes 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
| Need | Tool | Real backend? |
|---|---|---|
| Check the payload the frontend sent | waitForRequest | yes |
| Get an id or data from a real response | waitForResponse | yes |
| Substitute a response, simulate an error or delay | route.fulfill / abort | no |
| Change part of a real response | route.fetch + fulfill | yes, with edits |
| Add a header to all requests | route.fallback / continue | yes |
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.
waitForResponseafter 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
waitForRequestand a short timeout: it either wastes time or gives a false success. continueinstead offallbackin 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().
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.