The API that ruins my test runs is never mine. It is the payment provider that returns 402 on a card that expired in 2019, the map SDK that rate-limits the third request, the auth service that hands out a token with exp ten seconds in the future. I cannot add a ?fail=true flag to any of them, and I cannot ask a vendor to freeze a response body for me.

So the failure has to be produced somewhere I control, and there are three places people usually try:

  1. A DevTools override, which disappears with the tab and cannot be committed.
  2. A mock in the test runner (MSW), which is great for the suite but useless when I am clicking through the app by hand.
  3. A feature flag in the backend, which is the most expensive of the three and usually belongs to someone else.

The annoying part is the handoff between 1 and 2. You prove a mock in the browser, then retype it as a handler, and the retyped version is never quite the same — the retry that returned 500 first, the 250 ms latency, the GraphQL operation filter. That gap is what MockReplay is built around, and this post is the three layers it had to get right: intercept inside the page, decide the response synchronously, and generate a test file that reproduces the decisions.

Traffic captured from a real page in the side panel

Layer 1: the interception has to happen in the page's own JavaScript world

The obvious Chrome extension approach is chrome.webRequest, and in Manifest V3 it does not work for this. webRequest lets you observe a request and its headers; it does not let you hand a response body back to the page without the debugger permission and a Fetch domain session. A debugger session per tab is a permission prompt and a yellow banner in every tab the developer opens.

Patching fetch and XMLHttpRequest has the opposite trade-off: it costs a content script and no scary permission, and it produces a real Response object the page can consume, with real headers and a real body.

There is one catch that decides the whole architecture: a content script runs in an isolated world. It shares the DOM with the page but has its own JavaScript globals, so window.fetch inside a default content script is not the fetch the application calls. Patching it there changes nothing.

The fix is a small file registered with "world": "MAIN", which runs in the page's world:

{ "matches": ["http://*/*", "https://*/*"], "js": ["content/interceptor-main.js"], "run_at": "document_start", "world": "MAIN" } 

document_start matters for the same reason: the app's first request usually fires before DOMContentLoaded, and a patch installed after it misses the request that actually matters. The page can still capture a reference to window.fetch before you get there — no extension can fix that — so the panel tells the user to reload after installing. That is a real limitation, stated as one.

The interceptor keeps the original function and decides per request:

const realFetch = window.fetch; window.fetch = async function (input, init = {}) { const request = requestFrom(input, init); // url, method, body const decision = matchRequest(request); // rule / scenario / null if (!decision) { const response = await realFetch.call(this, input, init); reportCapture(request, response); // for the traffic list return response; } return syntheticResponse(decision, request); // no socket opened }; 

Two details in syntheticResponse are less obvious than they look:

  • A body on 204, 205 or 304 makes the constructor throw. The Fetch spec forbids it, so the status is checked before the body is attached. A mock that returns 204 with JSON is a mock that crashes the page, which is a confusing bug to chase in a generated fixture.
  • Headers go through the Response constructor in a plain object. Codes the app reads (content-type most of all) then behave the way they do in production, including the res.json() path that only runs when the header says JSON.

Synthetic responses never see a CORS preflight — nothing leaves the browser — so an app that would fail cross-origin in production can look fine in the mock. That is worth knowing before you trust a green run.

Layer 2: the response has to be chosen synchronously, with the state in the page

The panel is a side panel. The rules live in chrome.storage.local and the source of truth is the extension service worker. Both of those are asynchronous, and fetch is not: the patched function must return a promise that resolves with a response, and a XMLHttpRequest must fire its events in order.

So the page holds a reduced copy of the state — the enabled rules, the active scenario id, and three capture settings — pushed by the service worker and read from chrome.storage.local on the first request so a cold worker does not stall the page. The licence key never enters that copy; the page only learns whether it is licensed.

Rules themselves are plain JSON, and the matching order is something you can reason about without opening the extension:

{ "name": "Cart retry — fail once, then load", "enabled": true, "match": { "url": "*/api/cart*", "urlType": "glob", "method": "GET" }, "responses": [ { "status": 500, "headers": { "content-type": "application/json" }, "body": "{\"error\":\"cart_unavailable\"}", "delayMs": 250 }, { "status": 200, "headers": { "content-type": "application/json" }, "body": "{\"items\":[]}", "delayMs": 0 } ], "sequence": "hold", "scenarioIds": [] } 

The precedence is a three-step fallthrough, and it is the same in the browser and in the generated code:

  1. Active scenario fault. If a scenario is on and the URL matches its filter, every request gets the fault — 401, 500, or +2 s — including requests that have their own rule. This is the switch that lets me test "what does the app do when auth expires" without touching fifty rules.
  2. First matching enabled rule. URL pattern (exact, glob, regex, contains), method, optional GraphQL operation and optional JSON body condition.
  3. The real network.

Sequence state is the part I would design differently in a different product. The cursor for hold / cycle / once lives in a Map inside the interceptor, keyed by rule id, per document. A reload resets it. That is not laziness: a sequence is about this page load — "the first call fails, the second succeeds" — and a test that replays the same flow should start from index 0 every time. Persisting the cursor would make the second run of a test behave differently from the first, which is the single worst property a test can have.

GraphQL is worth a paragraph because URL matching fails there completely. Every operation posts to /graphql, so the URL tells you nothing. The rule can match on operationName, a substring of query, and a path into the request body:

"match": { "url": "*/graphql", "method": "POST", "graphql": { "operationName": "Viewer", "queryContains": "" }, "body": { "path": "variables.id", "op": "equals", "value": "42" } } 

Only the request that asks for viewer 42 gets the mocked viewer; the rest fall through to the server.

Scenarios switch the whole app's mood in one click

Layer 3: export has to reproduce the decisions, not the JSON

This is the layer that makes the tool worth keeping, and the one where a naive generator produces code that looks right and behaves differently.

Playwright's page.route() matches routes in the reverse order they were registered: the most recently added route is checked first. MockReplay rules are evaluated top to bottom, so the generator registers them bottom to top. Get that wrong and every rule that would have lost to an earlier one now wins, and the test asserts a response the app never saw:

// Rules are registered lowest priority first, because Playwright checks the // most recently registered route first — MockReplay order is preserved. // 2. POST GraphQL viewer await page.route(new RegExp("^.*/graphql$"), async (route, request) => { if (request.method() !== "POST") return route.fallback(); const body = request.postData() || ""; if (!graphqlMatches(body, "Viewer", "")) return route.fallback(); if (!bodyMatches(body, { path: "variables.id", op: "equals", value: "42" })) return route.fallback(); await wait(0); await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: "…" }); }); 
// 1. GET Cart retry — fail once, then load await page.route(new RegExp("^.*/api/cart.*$"), async (route, request) => { if (request.method() !== "GET") return route.fallback(); const response = pick("rule1", "hold"); if (!response) return route.fallback(); await wait(response.delayMs); await route.fulfill({ status: response.status, headers: response.headers, body: response.body }); }); 

route.fallback() rather than route.continue() is deliberate: it hands the request to the next registered handler, which is how a rule that does not match lets an earlier-checked route or the network answer. fallback() is also what makes the sequence work — when once is exhausted, pick() returns null and the request goes to the server as it would in production.

The MSW export has the same structure with the idiom of that library:

http.get(new RegExp("^.*/api/cart.*$"), async ({ request }) => { const response = pick("rule1", responses, "hold"); if (!response) return passthrough(); await delay(response.delayMs); return new HttpResponse(response.body || null, { status: response.status, headers: response.headers }); }), 

Latency is not decoration. A "Slow 3G" scenario adds two seconds to every response, and the exported file waits two seconds too, because the loading state that the test is trying not to assert on only exists if the request is slow. The generated file imports nothing from the extension: copy it into tests/, keep the headers, and it stands alone.

The export view: same rules, ready to commit

The boring engineering that makes it survive a browser

A few things bit me during development and are worth passing on if you are building anything similar:

  • Service workers get killed. Every mutation persists before the response is sent; the traffic log lives in chrome.storage.session, not in worker memory, because memory does not survive the idle timeout. Traffic writes go through a promise queue so a burst of requests cannot lose entries.

  • No build step. The library files attach one namespace, globalThis.MockReplay, and are loaded by the page, the worker (importScripts) and the panel alike. The test suite loads those exact bytes into a Node vm with fake fetch, XMLHttpRequest and timers — 166 tests, no browser required. A bundler would have added a build artifact whose shipped contents the tests could not vouch for.

  • The page can see the rules. It has to, to answer its own requests. So the interceptor deletes window.MockReplay after installing, and the documentation says plainly: do not put real secrets in a mock body.

  • Only fetch and XMLHttpRequest. EventSource, WebSockets, sendBeacon and browser-internal requests are not intercepted. If your app streams, this tool will not cover it, and pretending otherwise would be worse than the limit.

Free and Pro

The free build is the part I use daily: live capture of fetch and XHR per tab, unlimited rules, "save as mock" from any captured request, URL patterns (exact / glob / regex / contains) with method matching, custom status, headers, body and latency, per-rule toggles and order, and JSON import/export of the whole rule set. Nothing leaves the browser: the only outbound request the extension can make is the Gumroad licence check, when you press Verify.

Pro adds the three layers above the free core — scenario presets (Happy Path, Auth Expired 401, Server Outage 500, Slow 3G, plus your own), sequential responses, GraphQL and request-body matching, and the Playwright/MSW export. It is a one-time $29 Personal / $79 Team, verified once and cached for 14 days offline.

If you take one idea from this post, take the ordering one. Whether the mock lives in the page, in MSW or in a Playwright route, first match wins is the only rule that keeps a mock set understandable at twenty rules — and the place where the browser and the test runner disagree about that order is exactly where a green suite starts lying to you.