Skip to content
Logo

Quick start

This page wraps one external call, then mocks it in a test. It uses Bun's runner, but any runner works the same way.

1. Install

2. Initialize one instance

Call initialize once, in a module that both your source and your tests import:

// src/extern.ts
import { initialize } from "@ghostry/extern";
 
export const extern = initialize();

3. Wrap an external call

An extern block names its result type with an identity, and wraps the function that reaches outside your system. extern.T<…>() makes an identity that is only a type. Export it, since a test mocks the block through the same object:

// src/weather.ts
import { extern } from "./extern";
 
export const Forecast = extern.T<{ high: number; low: number }>();
 
export const forecast = (city: string) =>
  extern.typed
    .by(Forecast)
    .given(city)
    .will((city) => fetchForecast(city));
 
export const packFor = async (city: string) =>
  (await forecast(city)).low < 5 ? "a coat" : "a jacket";

given(city) passes the city to the function instead of capturing it in a closure, so a test can see what it was. Outside a test, forecast calls fetchForecast exactly as it would without extern.

4. Mock it in a test

extern.testing runs its body as a testing block. Inside it, mock(identity).with(value) replaces every block with that identity, and returns a spy:

// src/weather.test.ts
import { ,  } from "bun:test";
import {  } from "./extern";
import { ,  } from "./weather";
 
("packs a coat for the cold", async () => {
  await .(async () => {
    const  = ().({ : 3, : -2 });
 
    (await ("Oslo")).("a coat");
    (.).(1);
    (.[0]?.).("Oslo");
  });
});

No request is made. The mock must match the identity's type, so with({ high: 3 }) fails to compile.

5. See what it checks

Two mistakes fail the test instead of passing quietly:

  • A block with no mock. Remove the mock(Forecast) line and packFor throws NotMockedError, rather than calling the real service.
  • A mock that never runs. Mock Forecast in a test that never reaches forecast, and the testing block throws UnusedMocksError when it ends.

See Mocking for both, and the ways to opt out.

Next

  • Mental model: blocks, identities, testing blocks, and spies.
  • Harness: make every test a testing block, with no extern.testing in each one.