Skip to content
Logo

Extensions

An extension lets one extern instance accept another library's schemas as block identities. A block built from such a schema can produce its own value in a test, instead of needing a mock.

The one published extension is @ghostry/extern-extension-fabricator-v0, which accepts fabricator schemas and fabricates their values. Its guide is Extern, in fabricator's docs.

Adding one

Pass extensions to initialize:

import { initialize } from "@ghostry/extern";
import { fabricatorExtension } from "@ghostry/extern-extension-fabricator-v0";
 
export const extern = initialize({
  extensions: [fabricatorExtension({ instance: fabricator })],
});

An extension only affects the instance it was passed to. Another initialize() in the same project, given no extensions, still rejects those schemas, at compile time. To use two extensions, list both.

Blocks that produce their own value

A block whose identity an extension accepts is written like any other:

const User = fabricator.T.object({
  id: fabricator.T.number,
  name: fabricator.T.string,
});
 
const loadUser = () => extern.typed.by(User).will(() => fetchUser());

Inside a testing block, with no mock, the extension produces a value for it instead of the block throwing NotMockedError. An extension can be configured to throw instead, and fabricator's takes unmocked: "error" for that.

with() and skip() work on these blocks as on any other.

produce()

produce() asks the extension for the value explicitly, and returns a spy, like any terminal:

await extern.testing(async (mock) => {
  const spy = mock(User).produce();
 
  await loadUser();
  expect(spy.executions).toHaveLength(1);
});

produce takes a callback when you want to shape the value. It receives via, the extension's own object for the identity, so you shape it with that library's API rather than extern's:

mock(User).produce(({ via }) => via.fabricate({ name: "Ada" }));
mock(User)
  .named("owner")
  .produce(({ via }) => via.fabricate({ id: 1 }));

For fabricator, via is a built Fabricator.

Both forms are cached by identity and name: the callback runs once, and reading a block twice in one test gives the same value.

produce exists only for identities an extension accepts. On an extern.T<…>() or a Standard Schema it isn't offered, and doesn't compile.

typed only

Extensions apply to typed blocks. A validated block takes a Standard Schema, and an effect block has no identity at all.

Two extensions, one schema

When more than one extension accepts the same identity, using it throws AmbiguousIdentityError, which names the extensions. Extern doesn't pick one by their order, since TypeScript doesn't either.

Writing your own

See Writing extensions.