Skip to content
Logo

Why Fabricator?

Tests need data. The usual ways to get it all have problems. Fabricator exists to fix them.

The trouble with hand-written fixtures

const product = {
  name: "Test Product",
  price: 30,
  inStock: true,
  createdAt: new Date("2024-01-01"),
  tags: ["widget", "sale"],
};

This is easy to read, but it stops working well as soon as you need variations.

A fixture defines a shape a second time. When the real type gains a field, every fixture needs a manual update. TypeScript only flags the fixtures that were annotated.

A fixture also fixes every value forever. The object above has only ever been tested with price: 30. It has never seen price: 0, a 25-character name, empty tags, or a missing optional field. Covering those means writing many variants by hand, and nothing tells you when you've missed one.

The trouble with factories

A factory defines the model once, and each variation as a change to it. That fixes the upkeep, but the values are still constants, and now the whole suite shares them.

Ruby's factory_bot is the classic example. A variation is a child factory that redefines part of its parent:

FactoryBot.define do
  factory :user do
    name { "Jane Doe" }
    age { 30 }
    role { "member" }
    created_at { Time.utc(2024, 1, 1) }
 
    factory :admin do
      role { "admin" }
    end
  end
end

JavaScript factory libraries work the same way.

:admin is meant to say one thing: this user is an admin. It also inherits name, age, and created_at, the same values every other user gets. Anything a variation doesn't override becomes a constant shared across the suite.

Tests come to depend on those constants without saying so. A test expecting the name "Jane Doe" passes because of a line in a factory file. A sort looks stable because every record has the same created_at. An age boundary bug is never hit because the age is always 30.

Nothing records these dependencies, and nothing fails while they hold. When someone edits the factory, unrelated tests break, and the failures don't point back at the factory.

The trouble with plain random data

Random values from faker, Math.random(), or your own helper solve the fixed-value problem. They create a new one: you can't repeat the run that failed. A test that fails once in CI and passes everywhere else leaves you a failure with no way back to it.

Seeding the generator globally doesn't fix this. Most generators draw from one shared sequence. Add a field in the middle of a schema and every draw after it shifts, so unrelated fixtures and snapshots change.

A shared sequence also ties a test's data to the tests that ran before it. Run the test alone, in a different order, or in a different shard, and it gets different data from the same seed.

So reproducing a failure means reproducing the whole run: same tests, same order, same shards. Running the failing test by itself, the obvious first step, is guaranteed to give it different data.

What fabricator does instead

Define the shape once, as a Schema. Build it into a Fabricator. Call .fabricate() to get a value. Mental model explains the three layers. The rest of this page covers what you get.

The type comes from the schema

import {  } from "@ghostry/fabricator";
 
const { ,  } = ();
 
const  = .({
  : ..({ : { : 1, : 25 } }),
  : ..({ : 1, : 500 }),
  : .,
});
 
const productArrow
= new ().();

There is no second definition and no annotation. Change the schema and everything that uses the value is checked against the new shape.

If the type already exists somewhere else, such as an API response or a generated client, .satisfies<T>() checks that the schema still produces it. Drift fails at the schema, not in a fixture. This is an optional check, not a second definition.

Every value can be replayed

An instance's data depends on its clock, the instant initialize() ran, and an optional salt. You don't need a salt. The clock changes every run, so runs vary by that alone. You can read it afterward, so a failing run can be repeated:

const { , ,  } = ();
 
const  = new (..({ : { : 12 } }));
.();
 
.; // the instant this run resolved "now" against
.; // where this specific fabricator's randomness came from

Without a salt, the clock is all you need. Log context.clock and pass it back to replay the run. Only add a salt for a specific reason. For example, clock: "derived" with FABRICATOR_SALT=repro-1234 bun test removes the wall-clock dependency and pins the whole suite from outside.

.trace goes finer. It records where one field's randomness came from. Pass it to new Fabricator(schema, trace) to replay that field alone, which helps when you want to look at one leaf of a large object. See .trace.

Construction order still matters. An instance counts its constructions, so adding or removing one shifts the ones after it. fork and wrap start fresh counts, which lets a test integration keep each test separate from its neighbors. See Construction order.

A test depends on what it pins, and nothing else

Every field you don't pin varies. A variation is an override on top of changing data, not a new set of constants:

const  = .({ : "admin" });

The override is everything the test depends on. A test that secretly relied on the name being "Jane Doe" fails the first time it runs. That is the point. The dependency was already there. Varying everything else exposes it now, in the test that has it, instead of by accident from an unrelated change.

The usual objection is flakiness. That's fair for unseeded randomness. It doesn't apply here: a failing run replays from its clock, so you get a reproducible failure, not a mystery.

A schema edit doesn't disturb unrelated data

Each field draws from its own stream. The stream is keyed by the field's position in the schema, such as its name or tuple index, not by how many fields came before it.

So adding, removing, renaming, or reordering a field changes that field's data and nothing else. The diff from a schema change stays the size of the change. See Which field gets which randomness.

Absence is not one thing

Code can treat a missing key, a key set to undefined, and a key set to null differently. Most generators lump all three into "sometimes missing."

T.object({
  nickname: T.omittable(T.string.whereby({ length: { max: 12 } })), // key may be absent
  deletedAt: T.nullable(T.date.past), // value may be null
  note: T.optional(T.string.whereby({ length: { max: 40 } })), // omitted, undefined, or a present value
});

Separate primitives cover the combinations along two axes: whether the key exists, and what the value is when it does. The full table is in Absence. This matters because a bug often lives in just one of those cases. A generator that doesn't distinguish them can't find it.

Covering the output space

Random data samples the possible output space — it doesn't cover them. Two functions are available that do:

const  = .({
  : ..(["pending", "shipped", "delivered"]),
  : .,
  : .(..({ : { : 20 } })),
});
 
[...()].; // 3
[...()].; // 18

coverage(schema) gives the smallest set of values in which every option of every enumerable node appears at least once. Its size is the widest single axis, not the product of all of them. Here, three values cover all three statuses, both booleans, and all three optional outcomes.

combinatorial(schema) gives every combination: 3 × 2 × 3. It predictably throws before producing anything if the count would exceed limits.combinatorial (1024 by default).

Both are lazy and can be iterated multiple times. Each pass draws fresh randomness for anything not enumerated. See Instance.

Data distributed like production

Uniform draws rarely look like real data. Latencies cluster low with a long tail, and ages cluster in the middle. distribution shapes the draw within its bounds:

T.number.whereby({
  min: 0,
  max: 1000,
  distribution: { kind: "normal", mean: 500, spread: 100 },
});

Normal, skew, triangular, logarithmic, and weighted blends of those are available. See Distributions.

Next

Next is a comparison with other libraries.

To skip it, go to installation, then the quick start for the whole loop on one page. Mental model explains why Registry, Schema, and Fabricator are separate.