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

  1. DevTools → Network → right-click the request → Override content.
  2. Pick a folder on disk and allow access to it.
  3. Edit the response in the editor and save with Ctrl/Cmd+S.
  4. 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":false with "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.

View in Solpuga

Related