How to mock an API response without touching the backend
Four ways to hand an app your own JSON: Chrome Local Overrides, MSW, a client interceptor and a proxy, and when each one fits.
When you need it
To test a response the backend will not give you: an empty list, a 500, two hundred items, a field that does not exist yet. The four ways below differ in where the swap happens, and so in which traffic they reach.
Chrome DevTools: Local Overrides
- DevTools → Network → right-click the request → Override content.
- Pick a folder on disk and allow access to it.
- Edit the response in the editor and save with
Ctrl/Cmd+S. - Reload. The request now comes from your file.
The body and response headers can be overridden, the status code cannot. Works only in this browser, with DevTools open.
MSW: mocking inside the application
msw registers a Service Worker that answers the page's requests with your
handlers. Copy the worker file into the public folder first:
npx msw init ./public --save
// mocks/handlers.js
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('/api/orders', () =>
HttpResponse.json({ items: [] }), // an empty list
),
http.post('/api/orders', () =>
new HttpResponse(null, { status: 500 }), // a server error
),
];
// mocks/browser.js
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers';
export const worker = setupWorker(...handlers);
// main.jsx — development only
if (import.meta.env.DEV) {
const { worker } = await import('./mocks/browser');
await worker.start();
}
// render the app after this point
Requests sent before start() resolves reach the real backend.
The mock lives in the repository; tests reuse the handlers via setupServer
from msw/node. It covers only JavaScript you control.
An interceptor in the mobile client
If the source is yours, mock in the HTTP client.
// Android, OkHttp
val mockInterceptor = Interceptor { chain ->
val request = chain.request()
if (BuildConfig.DEBUG && request.url.encodedPath == "/api/orders") {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(500)
.message("Mocked")
.body("""{"error":"boom"}""".toResponseBody("application/json".toMediaType()))
.build()
} else {
chain.proceed(request)
}
}
val client = OkHttpClient.Builder()
.addInterceptor(mockInterceptor)
.build()
Without the BuildConfig.DEBUG check the mock ships to users. Every change
needs a rebuild.
A proxy: mocking outside the application
A debugging proxy swaps the response on the wire, whatever the client: a web page, a mobile app, a CLI tool, a binary with no source. A matching request never reaches the server.
Only a proxy works when:
- the app is not yours and cannot be rebuilt, on a desktop or on a phone;
- a tester needs the mock without setting up an environment.
An app that pins its certificate rejects the proxy:
its traffic can be neither seen nor changed. An Android 7+ app trusts a
user-installed CA only if its
network_security_config allows it.
In Solpuga
- Map Local answers in place of the server. Rules window: Tools menu (
Cmd/Ctrl + Shift + M). A rule sets the URL pattern, status, headers, body and an optional delay of up to 60 seconds. A rule created from a captured request is pre-filled with the real response. Map Local. - Rewrite changes the outgoing request or the server's response. Tools → Rewrite (Beta)…, a set with a host and path location, a response rule Response Status: a 200 becomes a 503, the body stays the server's. A Body rule replaces part of the response, e.g.
"premium":falsewith"premium":true. Rewrite. - Breakpoints pause a request (method, headers, body) or a response (status, headers, body) for hand editing. Add a rule that pauses on the response, trigger the request, edit it in the queue (
Cmd/Ctrl + Shift + B), forward it. The client may time out meanwhile. Breakpoints.
HTTPS traffic is changed only on decrypted hosts. Saving a rule adds its host to the SSL Proxying list if the rule names a specific host (in Rewrite, a mask like *.example.com also counts).
Which to use
| What you need | What to use |
|---|---|
| A one-off look in your own browser | Local Overrides |
| A scenario the whole team and the tests share | MSW |
| Mocking inside your own mobile client | an interceptor in code |
| Somebody else's app, or a phone, without a rebuild | a proxy |
See it on your own traffic
A request answered by Map Local or changed by Rewrite carries an R badge in the list. No badge means the rule did not match: the path or query string does not fit the pattern (a wildcard pattern must match the whole URL), or the app showed cached data and sent no request. Test a pattern against a sample URL before saving the rule.
Related
- How to see the traffic from an iPhone or an Android phonePhone and computer on one Wi-Fi, a proxy in the network settings, a root certificate with full trust. Four steps, and the five things that break them.
- SSE arrives in one chunk: nginx bufferingServer-Sent Events land all at once instead of streaming. Three layers act on them: proxy_buffering, gzip and the app itself. How to test each.