Skip to content
Logo

Values

A block that produces a value starts with extern.typed or extern.validated, then by(identity). The identity names the value's type, and it's how a test finds the block to mock it.

typed

A typed block returns its function's value as is. The identity only gives it a type:

export const Forecast = extern.T<{ high: number; low: number }>();
 
export const forecast = (city: string) =>
  extern.typed.by(Forecast).will(() => fetchForecast(city));

extern.T<…>() is an identity with no runtime checks. A Standard Schema works here too, but typed never runs it, so its type is all that's used. Use typed when the function already validates what it returns, or when you don't need runtime checks.

The function may return the value or a promise of it. An async function makes the block return a promise.

validated

A validated block checks its function's value against a Standard Schema, such as one from Zod, Valibot, ArkType, or Sury:

import * as S from "sury";
 
export const ForecastSchema = S.schema({ high: S.number, low: S.number });
 
export const forecast = (city: string) =>
  extern.validated.by(ForecastSchema).will(() => fetchForecast(city));

A value that doesn't match throws InvalidDataTypeError, which carries the schema and its issues. A Standard Schema may validate asynchronously, so a validated block always returns a promise, even when its function doesn't.

A mock's value is not validated. TypeScript checks it against the schema's type instead.

Identities are compared by object

A block and its mock match only when they use the same object. Two schemas built from the same definition are still two identities:

// two blocks, two identities: a mock of one doesn't reach the other
extern.typed.by(extern.T<number>()).will(count);
extern.typed.by(extern.T<number>()).will(count);

Define each identity once, at module level, and export it for tests. One identity can serve many blocks, and one mock replaces them all, unless you tell them apart with named.

Watch out for empty object types

An identity whose type is {} accepts almost anything, a promise included. With an async function, the block's type can say it returns the value while it actually returns a promise of it, and TypeScript won't object. Give an identity a type with at least one property, or one that isn't an object.

named and given

Both go between by and will, named first:

extern.typed.by(Forecast).named("today").given(city).will(fetchForecast);

named tells blocks with one identity apart. See Named blocks. given passes data to the function, where a test can see it. See Given.