Mental model
Extern has four parts: the instance initialize returns, the blocks that wrap external calls, the testing blocks that change what those blocks do, and the mocks and spies a test defines.
One instance
export const extern = initialize();Source code and tests import the same instance. initialize takes two options, both optional: scope, which decides how a testing block follows its body across await (see Installation), and extensions (see Extensions). An extension only affects the instance it was given to.
Blocks wrap external calls
A block is a chain that ends in will, which takes the function to run:
extern.typed.by(Forecast).named("today").given(city).will(fetchForecast);
extern.validated.by(ForecastSchema).will(() => fetchForecast(city));
extern.effect.named("track view").given(id).will(sendViewMetric);There are three kinds:
typedblocks produce a value, and their identity only names its type. See Values.validatedblocks produce a value and check it against a Standard Schema at runtime.effectblocks produce nothing, like sending a metric. They have no identity. See Effects.
named tells blocks with one identity apart, and given passes data to the function where a test can see it. See Given.
Identities connect blocks to mocks
A value block's identity is an object: a type-only extern.T<…>(), a Standard Schema, or an extension's schema. The block and its mock must use the same object. Two schemas that describe the same shape are two identities, so an identity is defined once and exported.
Outside a testing block, nothing changes
A block outside extern.testing runs its function and returns its value, as if extern weren't there. A validated block also checks the value. Wrapping a call doesn't change what any existing test sees.
Inside a testing block, nothing runs unless you say so
await extern.testing(async (mock) => {
// ...
});Inside the body, and in everything it calls:
- A value block with a mock returns the mock's value, and doesn't run its function.
- A value block with no mock throws
NotMockedError. - An effect block doesn't run.
extern.testing returns its body's value. A synchronous body stays synchronous, so await is only needed for an async body.
Mocks return spies
mock(identity) defines what blocks with that identity do in this testing block. Each terminal returns a spy:
| terminal | what the block does |
|---|---|
with(value) | returns value. substitute is the same terminal |
skip() | runs its function. passthrough is the same terminal |
produce() | returns a value its extension makes. See Extensions |
A spy's executions records each call the mock served: its given data, its name, and its outcome, either { kind: "returned", value } or { kind: "threw", error }.
A mock lasts for one testing block. When the block ends, a mock that served no call throws UnusedMocksError. See Mocking.
