Why your tests miss the race
A local test server usually answers in a few milliseconds and in the order the requests arrive, so an older response almost never lands after a newer one. In production a cold cache or a weak phone signal can make one request much slower than the next. A slow network setting adds delay to every request, but it does not let you choose which response lands last.
When timing does vary, on a busy CI runner for example, a test that depends on the order fails now and then and passes on a retry, which Playwright reports as flaky (test retries). Such a test can point to a real race in the app. Hold the requests in the test and the bad order happens on every run. To watch the orders play out first, try the race condition simulator.
Hold a request with page.route and release it later
page.route() runs your handler before a matching request goes out, and the request stalls until it is continued, fulfilled or aborted (page.route). A handler that only stores the route holds the request until your test lets it go, in one of three ways (Route):
route.continue()sends the request to the network at once. Other handlers that match it are skipped.route.fallback()passes it to the next matching handler first. Handlers run in the reverse order of registration, so a mock or a fixture registered earlier still sees the request.route.fetch()sends the request to the server now and returns the response without delivering it to the page. Pass that response toroute.fulfill()when you choose.
const answer = await route.fetch(); // the real response, not delivered yet
// later, when the test decides:
await route.fulfill({ response: answer });
In a URL glob, * stops at a slash and ? matches only a literal question mark, so "**/api/search?*" matches a search request that has a query string (glob patterns). page.route() also misses requests a service worker handles, such as those of Mock Service Worker (MSW) in the browser; Playwright's docs suggest serviceWorkers: "block" and mocks in page.route() instead (service workers).
A full test for a search box
Say your search box (an input of type search) sends GET /api/search?q=... on each input and writes the response into a list. The test assumes your test data returns React first for "react" and something else first for "re"; use names from your own data.
import { test, expect, type Route } from "@playwright/test";
test("shows results for the last query when an older answer lands last", async ({ page }) => {
// Hold every search request until the test lets it go.
const held = new Map<string, Route>();
await page.route("**/api/search?*", (route) => {
held.set(new URL(route.request().url()).searchParams.get("q") ?? "", route);
});
await page.goto("/"); // baseURL in playwright.config points at your app
const box = page.getByRole("searchbox");
const results = page.getByRole("listitem");
// Two queries. Wait until each request is held, so a debounce cannot merge them.
await box.fill("re");
await expect.poll(() => held.has("re")).toBe(true);
await box.fill("react");
await expect.poll(() => held.has("react")).toBe(true);
// The newer answer lands first.
await held.get("react")!.continue();
await expect(results.first()).toHaveText("React");
// The older answer lands last. Wait until the browser has all of it
// (there is no response when the page canceled the request).
const older = held.get("re")!;
await older.continue();
const late = await older.request().response();
await late?.finished();
// The list must still show the results for "react".
await expect(results.first()).toHaveText("React");
});
On a search box that writes every response, the last assertion fails: the list shows the results for "re". The test passes once the app ignores stale answers or aborts the previous request, the two fixes in the guide to out-of-order responses. A debounce alone does not make it pass, because the test waits for each request before it types the next query.
Make it deterministic: wait for events, not time
Each wait in the test is for an event:
expect.poll()waits until each request is held before the next query is typed (expect.poll). Without it, a debounce can merge both queries into one request, and there is nothing left to reorder.- The first
toHaveText()proves that the newer answer was on screen before the older one arrived. Web-first assertions retry until they pass or time out, after 5 seconds by default (auto-retrying assertions). - The last assertion checks that nothing changed, and a web-first assertion passes as soon as the list looks right. So the test first waits for the older response to arrive in full:
request.response(), thenresponse.finished().request.response()returns null when the request failed, as it does when the app aborts the previous request (Request);page.waitForResponse()would time out in that case.
If your app writes the response only after a timer or an animation, also wait for a signal it gives, such as a loading state going away. Leave out page.waitForTimeout(): Playwright's docs say tests that wait for time are inherently flaky and point to network events and web assertions instead (waitForTimeout). They also discourage waitUntil: "networkidle" in tests (page.goto).
Seeded chaos with @genclass/playwright
A test you write covers the order you thought of. @genclass/playwright (open source under Apache-2.0, 0.1.0 on npm) runs the tests you already have under orders you did not write. It puts the GenClass runtime on each test's page before the app's first script, in observe mode with telemetry off, so the runtime only reports. With chaos on, the fixture holds matched fetch and XHR requests (by default same-origin ones whose path starts with /api or whose Accept header asks for JSON) for a delay derived from a seed, then passes each on unchanged with route.fallback(). The same seed gives the same delays on every run, so each finding comes with the seed that produced it.
After each test it writes a race file (JSON, format genclass-races/1) to test-results/genclass/, and its reporter turns the files into genclass-report.md, one markdown report for the pull request. Without a model download it records two facts: overwrote-newer, a response that wrote a field over what a newer request or the user had written, and identical-in-flight, two identical requests in flight together from separate user actions, which is what a double submit looks like. A finding never changes a test's outcome.
Install it, add the genclass option and the reporter to your config, and import test and expect from the fixture instead of @playwright/test:
npm install -D @genclass/playwright @genclass/runtime
// playwright.config.ts
import { defineConfig } from "@playwright/test";
import type { GenClassFixtures } from "@genclass/playwright/fixture";
export default defineConfig<GenClassFixtures>({
use: { genclass: { chaos: { seed: 1, delayMs: [0, 600] } } },
reporter: [["list"], ["@genclass/playwright/reporter"]],
});
// tests/search.spec.ts
import { test, expect } from "@genclass/playwright/fixture";
Run npx playwright test --repeat-each 2 so the report can mark a finding flagged under both seeds as reproducible. For a suite you would rather not edit, npx genclass-playwright-run does the same with no change to specs or config. With chaos on, a suite that passes today can fail when answers come back in another order, so give it a CI job of its own.
Measured on one search page (from the MCP server's end-to-end test, its store on the fixture's runtime), with the model off, in headless Chromium: the overwrote-newer witness appeared in 30 of 30 runs with reordering (five seeds, six runs each), in 0 of 30 on the fixed version of the page, and in 0 of 30 with latency but no reordering (the measurement). One page is not a benchmark: what you get depends on the state the runtime can see in your app.
Where GenClass fits
In a test run, look for the overwrote-newer and identical-in-flight witnesses in genclass-report.md. They are facts for you to judge; your own assertion still says what the user should see. The witnesses need state the runtime can see: React component state, Redux stores set up for Redux DevTools and Zustand stores with devtools enabled, which it finds on its own, and stores your app registers on the script-tag runtime (window.GenClass). Pinia, Svelte stores and signals are not found on their own, and stores registered on your app's own ESM import of the runtime are not seen. Chaos never holds WebSocket messages, and nothing here watches your live site; for that, see how to detect race conditions in production.
With a coding agent, the GenClass MCP server does this on your development build: while the agent or a test repeats your steps, genclass_explore delivers the responses in seeded orders and reports which final page differs, and genclass_explain gives the finding with a Playwright test that fails while the bug is there. A clean explore run covers only the steps it ran.
Questions
How do I delay a response in Playwright?
Hold the request in a page.route handler and let it go when you are ready: call route.continue() later, or get the real answer with route.fetch() and deliver it with route.fulfill({ response }).
What is the difference between route.continue() and route.fallback()?
route.continue() sends the request to the network at once and skips other handlers. route.fallback() hands it to the next matching handler first, so a mock or a fixture registered earlier still sees it.
Why does my Playwright test pass locally but fail in CI?
One cause is timing: on a slower machine, responses can come back in another order, and code that assumes the sent order breaks. Hold the requests and set the order in the test, so the result no longer depends on the machine.
Should I use waitForTimeout or networkidle to wait for responses?
No. Playwright's docs call tests that wait for time inherently flaky and discourage networkidle in tests; wait for a network event or a web-first assertion instead.
Can I hold responses in Cypress or Mock Service Worker?
Yes. A cy.intercept handler that returns a promise holds the request until the promise resolves, and an MSW handler can await delay() or a promise of its own before it returns the response.
Related: race conditions in JavaScript and debugging races with the MCP server.