Skip to content
Logo

Why Extern?

A unit test should check your code, not the payment provider, the database, or the metrics service it talks to. Most tests only need to know that a call was attempted, with the right data, and what your code does with the answer.

Bringing every system up for every test is slow, and it gets slower as the suite grows, since the same cross-system paths are exercised again and again. Traditional dependency injection avoids that, but it changes your code to do it: a client becomes a constructor parameter, a function takes an extra argument, and an abstraction appears only so a test can replace it.

Extern replaces the call where it happens instead.

Wrap the call, keep the signature

You wrap the code that reaches outside your system in an extern block:

export const loadUser = (id: number) =>
  extern.typed.by(User).will(() => api.users.get(id));

loadUser keeps its signature, and its callers don't change. Outside a test, the block runs its function as if extern weren't there, so existing tests keep passing until you choose to mock it.

Mocks are checked against the code they replace

The block's identity, User here, names the type it returns. A test mocks the block through the same identity, and TypeScript requires the mock to be a value of that type:

await extern.testing((mock) => {
  mock(User).with({ id: 1, name: "Ada" });
});

When the type changes, every mock of it that no longer fits fails to compile.

Nothing reaches out by accident

Inside extern.testing, an unmocked value block throws NotMockedError instead of running. A test can't make a real request by accident, and a test that depends on one fails rather than passing slowly or flakily. A mock that never runs fails the test too, so a test's setup lists only what it needs. See Mocking.

When not to use it

  • You want integration or end-to-end tests. Extern is for testing a system without the systems around it. To check the real conversation between them, run them.
  • The external call is already behind an interface you inject. Extern doesn't add much over a fake implementation you already pass in.
  • You can't wrap the call site. Extern replaces calls you wrap, and it can't intercept calls inside a library you don't control.