# How to choose between a network mock and an in-process mock

> Decide where a test's mock sits by listing which layers still run beneath it: a fake object, an SDK's mock mode, a fetch interceptor, or a server on a port.

Source: https://voxgig.com/howto/choose-between-network-and-in-process-mocks

- Audience: api-consumer
- Level: beginner
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

Mock as close to the wire as the test's subject requires. A fake client object runs only your code, and an SDK mock mode such as the sdkgen test feature adds the client's own logic. Neither shows the test the serialized request. A fetch interceptor such as MSW sees that request inside the process, and a mock server on a port sees it over a socket. List the layers each test runs, and keep one wire-level test per write path.

---
## You will need

Node 22 or later and an app that calls an HTTP API through a client. Verified 2026-11-19
against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3, and MSW 3.0.7. The
client on this page is a TypeScript SDK that sdkgen generated from `openapi.json`, a bookmarks API
with three operations. Its compiled JavaScript is committed under `generated/`, so the commands
generate nothing when they run.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Fern mock server tests](https://buildwithfern.com/learn/sdks/current/deep-dives/testing) | You publish an SDK with Fern and want wire-level tests generated for every endpoint | An Enterprise feature of a hosted product, and it tests the SDK, not your app | You consume the SDK and need a mock for your own code |
| [MSW](https://mswjs.io/guides/integrations/node) | Tests in one Node process that must see the request as the server would | Handlers to write and keep, and a client that captured `fetch` before `listen()` escapes them | The code under test runs in another process |
| [`ogen` Invoker and Handler interfaces](https://ogen.dev/docs/features/) | A Go client, where one typed fake can be the client object or sit behind a socket | Go only, and each method the fake needs is yours to write | The client is not Go |
| [Prism](https://github.com/stoplightio/prism/blob/master/docs/guides/01-mocking.md) | A mock on a port that validates each request against the document, with no code | A process to start and a port to wait for in every run | The test needs state that survives between calls |
| [sdkgen test feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md#test) | An sdkgen SDK, when the test is about your own logic and not the request | Its transport ignores the request the SDK built, so a body that cannot survive JSON passes | The bug you fear is in the request itself |
| [WireMock](https://wiremock.org/docs/stubbing/) | One mock on a port, shared by clients in several languages | A JVM or a container to run, and stubs that check only what you script | One process and one language are under test |

Voxgig maintains sdkgen. It is one of six options here, not the recommendation.

The rows sit at three distances from the wire. Prism and WireMock answer on a port, so every
layer of the client runs and every test waits on a process. MSW answers inside the process: the
request is serialized, but it never reaches a listening socket.
[nock](https://github.com/nock/nock#how-does-it-work) also answers inside the process, by overriding
Node's `http.request`, so it reaches a client that calls that function. The sdkgen test feature answers inside the client, where serialization no longer
matters. `ogen` is the odd row, because its two generated interfaces let one Go fake sit at
either end.

## Run one function against four mocks

The client is generated once, with the `ts` target, and compiled:

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 marks --def openapi.json --target ts
(cd marks-sdk/.sdk && npm run generate)
(cd marks-sdk/ts && npm install --no-audit --no-fund && npm run build)
```

The code under test is one function of your own. It keeps tags in a `Set` to drop repeats, then
hands the `Set` to the client:

```js title="app.mjs"
export async function saveBookmark(client, { url, title, tags }) {
  const saved = await client.Bookmark().create({ url, title, tags: normalize(tags) })
  return saved.data()
}
```

JSON has no set, and `JSON.stringify` writes a `Set` as `{}`.[^1] Type-checked TypeScript would
have refused the call, because the generated declarations type `tags` as an array, but `app.mjs`
is JavaScript.

`mocks.mjs` builds four stand-ins for the API, ordered from furthest from the wire to nearest.[^2]
They are a hand-written fake with the client's shape, the SDK's own test mode,
[MSW](https://mswjs.io/guides/integrations/node), and a `node:http` server on a loopback port. The
second is one line:

```js title="mocks.mjs"
export function sdkTestMode(trace) {
  const client = MarksSDK.test({ entity: { bookmark: {} } }, observed(trace))
```

The two nearest the wire answer through one function that holds the document's rules, so they
refuse a body whose `tags` is not an array. `layers.mjs` runs `saveBookmark` against each mock
and counts what ran beneath it: SDK operations, calls to `fetch`, and connections a server in the
process accepted, which Node reports on its
[`net.server.socket` channel](https://nodejs.org/api/diagnostics_channel.html#event-netserversocket).

```bash
node layers.mjs
```

```text output
saveBookmark(), which hands the client a Set of tags
  mock layer                 SDK ops  fetch  sockets  tags, as the mock got them  outcome
  fake client object               0      0        0  Set(2) { 'go', 'cli' }      saved
  sdkgen test mode                 1      0        0  Set(2) { 'go', 'cli' }      saved
  fetch interceptor (MSW)          1      1        0  JSON {}                     refused: MarksSDK: create: request: 400: Bad Request
  mock server on a port            1      1        1  JSON {}                     refused: MarksSDK: create: request: 400: Bad Request

saveBookmarkFixed(), which spreads the Set into an array first
  mock layer                 SDK ops  fetch  sockets  tags, as the mock got them  outcome
  fake client object               0      0        0  [ 'go', 'cli' ]             saved
  sdkgen test mode                 1      0        0  [ 'go', 'cli' ]             saved
  fetch interceptor (MSW)          1      1        0  JSON ["go","cli"]           saved
  mock server on a port            1      1        1  JSON ["go","cli"]           saved
```

The top two rows are the pitfall. Each was handed a live `Set` holding both tags, so any assertion
written against it passes. The test mode did run the SDK: one operation went through its
pipeline, and the SDK built the request. Its in-memory transport then answered from the object
and never read what was built. The bottom two rows received the bytes, and the bytes were wrong.

## Pick the layer by what the test is about

Read the three count columns as a list of what the test still executes, then match it to the
test's subject.

A test of your own logic, such as which bookmark gets saved and what the user is told, belongs in
the top two rows. They open no port and wait on no process, so they stay fast and steady. Prefer
the SDK's test mode to a hand-written fake when the SDK has one, because the client's own entity
code and error mapping then run too.

A test of the request your code causes belongs at the interceptor: the field names, the headers,
and what your values turn into as JSON. Every function that assembles a write payload needs one.

A test of the connection belongs on a port: timeouts, retries after a dropped socket, proxies,
and any client that runs in another process.

## Make the same choice in a generated Go client or a Fern SDK

`ogen` generates a typed Go client and server, and its documentation lists no mock. What it does
generate is the seam at both ends. `ogen-seams.mjs` reads the two interfaces out of the generated files:

```bash
node ogen-seams.mjs
```

```text output
Invoker, the client-side interface in oas_client_gen.go
  CreateBookmark(ctx context.Context, request *Bookmark) (CreateBookmarkRes, error)
  GetBookmark(ctx context.Context, params GetBookmarkParams) (GetBookmarkRes, error)
  ListBookmarks(ctx context.Context) ([]Bookmark, error)
Handler, the server-side interface in oas_server_gen.go
  CreateBookmark(ctx context.Context, req *Bookmark) (CreateBookmarkRes, error)
  GetBookmark(ctx context.Context, params GetBookmarkParams) (GetBookmarkRes, error)
  ListBookmarks(ctx context.Context) ([]Bookmark, error)
same methods, parameter names aside: yes
```

One fake type therefore satisfies both:

```go title="ogen/fake.go"
var (
	_ api.Invoker = (*Fake)(nil)
	_ api.Handler = (*Fake)(nil)
)
```

Pass the fake where your code expects an `Invoker` and it is the client object. Give it to
`api.NewServer` under [`httptest.NewServer`](https://pkg.go.dev/net/http/httptest#NewServer) and
the generated client reaches it over a socket, through the generated encoders. The request type
carries `Tags []string`, so the `Set` mistake does not compile.

Fern answers the question for whoever publishes the SDK. Its
[testing page](https://buildwithfern.com/learn/sdks/current/deep-dives/testing) describes
generated unit tests that make no network calls, and mock server tests that run the SDK against a
mock generated from the API definition. The second kind is an Enterprise feature, switched by
`generation.wireTests.enabled` in `sdk-config.yml`, the current configuration format. A consumer
of a Fern SDK [sets the base URL](https://buildwithfern.com/learn/sdks/current/deep-dives/sdk-user-features)
when constructing the client, which is how a mock on a port gets in. In a TypeScript SDK, a custom
[`fetcher`](https://buildwithfern.com/learn/sdks/current/generators/typescript/dynamic-authentication)
exists only where the publisher set `allowCustomFetcher`.

## Check it worked

Run the suite:

```bash
node --test layers.test.mjs
```

```text output
1..9
# tests 9
# suites 0
# pass 9
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 9` is the line to read. Four tests pin one row of the table each, so a release of the SDK
whose test mode starts reading the serialized body turns the second one red.

## When it goes wrong

A request leaves the process although the interceptor is listening. The generated SDK takes
hold of `fetch` when the client is constructed, so a client built before `server.listen()` keeps
the original. Construct the client after `listen()`, or pass
`system: { fetch: (url, init) => globalThis.fetch(url, init) }`, which looks the function up on
every call. The suite pins both.

The port mock passes locally and fails in CI with `EADDRINUSE`. The test asked for a fixed port.
Listen on port 0 and read the port back, as `mocks.mjs` does.

The first production write is refused although every test passed. All the write tests sit in the top
two rows of the table. Move one test per write path down to the interceptor.

## When not to do this

Do not put every test at the wire. A port and a process per test buy nothing when the subject is
a branch in your own code, and they cost the suite its speed and its steadiness.

Do not trust sdkgen's test mode, or any fake that replaces the transport, with a payload you
assemble. It handed the `Set` back intact while the wire carried `{}`.

Do not hand-write what a generator gives you. For a Go client, `ogen` is the better choice:
one fake serves both ends, and the typed request refuses the mistake at compile time. For a
publisher who has to prove the wire format, Fern's mock server tests are the better choice, because
they run every endpoint against a mock. sdkgen's generated suite runs on its in-memory test
feature unless a live run points it at the real API, and this page shows that feature cannot see
the wire.

Do not mock what you can type. A request type that has no room for a `Set` beats any test that
would have caught one.

## Related how-tos

- [Run an in-memory mock of your API inside SDK tests](/howto/run-an-in-memory-mock-inside-sdk-tests)

- [Mock a generated SDK in your application tests](/howto/mock-a-generated-sdk-in-application-tests)

- [Stub outbound HTTP calls in Node tests with nock](/howto/stub-outbound-node-http-calls-with-nock)

- [Serve your OpenAPI examples as mock responses](/howto/serve-openapi-examples-as-mock-responses)

- [Layer unit, integration, and live tests for an SDK](/howto/layer-unit-integration-and-live-sdk-tests)

## Last verified

Verified 2026-11-19 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3,
MSW 3.0.7, and `ogen` v1.25.0. Every output block is what the command preceding it printed. The
sdkgen SDK was generated and compiled once, with TypeScript 5.9.3, and its JavaScript is
committed. `ogen` ran once on the same document. Its output is committed as written, and the Go
fake beside it was compiled and tested once with Go 1.26.11, which the checks do not repeat. The
TypeScript refusal was seen once, as error TS2740 from `tsc`. Fern was not run; its paragraph
describes its documentation. Prism and WireMock were not run for this
page. No request left the loopback interface.

[^1]: The grammar is short enough to check. [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259.html)
allows a JSON value to be an object, an array, a number, a string, or one of three literal names,
which leaves a set with nowhere to go. The MDN page on
[`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
says only enumerable own properties are visited, so a `Map` or a `Set` becomes `{}`. The function
raises no error on the way.

[^2]: All four are called mocks here, which the literature would correct. Martin Fowler's
[Mocks Aren't Stubs](https://martinfowler.com/articles/mocksArentStubs.html), dated 2 January
2007, follows Gerard Meszaros in using test double as the general term and counting five kinds:
dummies, fakes, stubs, spies, and mocks. A fake has a working implementation that takes a
shortcut. A mock is pre-programmed with expectations. By that count every stand-in on this page is
a fake, because none of them is told in advance which calls to expect.