B8.19 Substitute an owned module by injection: examples

Rule: B8.19 in the code standards.

Why

The suite uses no test framework (B8.1), so there is no module mocking, and a stand-in has to enter through the code’s own interface. An injected deps parameter keeps that seam in the signature: when the module is refactored, the compiler checks the fake against the same type production uses. Swapping a collaborator by setting module state makes the substitution invisible in the signature, and it leaks into later blocks unless every block resets it (B8.13).

B8.15 decides whether a stand-in is allowed: only for a module that wraps a real boundary, such as a socket, the filesystem or the clock. This rule decides how it enters.

The rule also bars a production export that exists only so a test can reach a private function. A test reaches module-private code through the export that uses it (B8.5).

Good: an optional deps parameter with real defaults

src/transport/runtimeConnection.ts:60-72:

export function createRuntimeConnection(
  opts: { projectPath?: string; explicitRuntimePort?: string | undefined },
  deps?: RuntimeConnectionDeps,
): RuntimeConnection {
  // ...
  const { createChannel, createHeartbeat, registry }: RuntimeConnectionDeps = deps ?? {
    createChannel: realCreateChannel,
    createHeartbeat: realCreateHeartbeat,
    registry: realRegistry,
  };

Production passes nothing (src/transport/bridge.ts:281). The test builds fakes typed by the same interface (test/unit/runtimeConnection.test.ts:99) and passes them in (line 122):

const deps: RuntimeConnectionDeps = { createChannel, createHeartbeat, registry };
const rc = createRuntimeConnection({ explicitRuntimePort: "9999" }, t.deps);

Bad: a stand-in set as module state

test/unit/discoverLsp.test.ts:518 swaps the version getter by filling a module slot, and line 563 has to undo it by hand:

setGodotVersionGetter(() => [4, 5]);
setGodotVersionGetter(() => undefined); // reset module-level state

The slot itself is a §6.11 case listed in B7. An existing test like this keeps its shape until a change edits it (the B8 preamble).

Source

  • Vitest, Mocking modules: making the application testable is not the test runner’s job; prefer dependency injection.
  • Martin Fowler, Mocks Aren’t Stubs: tests coupled to how a unit calls its collaborators break when that changes.

This site uses Just the Docs, a documentation theme for Jekyll.