Skip to content
Logo

Faker

Fabricator generates arbitrary values, not realistic ones. @faker-js/faker generates realistic values, but with its own separate randomness. A schema that used both directly would have two sources of randomness, and only fabricator's could be replayed.

The extension removes faker's source. Faker draws from each field's own fabricator stream, so T.faker.person.fullName() replays exactly like a T.string does.

import { initialize, registry } from "@ghostry/fabricator";
import { fakerExtension } from "@ghostry/fabricator-extension-faker-v10";
 
const { T, Fabricator } = initialize({
  types: registry.extend(fakerExtension({ locale: ["base", "en"] })),
});
 
const User = T.object({
  name: T.faker.person.fullName(),
  email: T.faker.internet.email(),
  joined: T.faker.date.past(),
  id: T.string.whereby({ length: { max: 8 } }),
});
 
new Fabricator(User).fabricate();

It is added with registry.extend, the same way you add your own types, so T.faker.* sits alongside every core kind without replacing anything.

locale names faker's locales, the keys of its allLocales, in fallback order. A locale definition object (import { en } from "@faker-js/faker") works too, but it puts that locale's data in every bundle that imports the module passing it in.

When faker loads

Faker is loaded the first time a faker builder fabricates a value. Building schemas and converting them with an adapter never load it, so a browser app that reuses the same schemas only for TypeBox validation or Fabricated<> types bundles no faker at all.

That load is synchronous, and it works on Node 20.19 and later, Bun, and Deno. To fabricate faker values in a browser bundle, import faker yourself and pass create instead of locale:

import { base, en, Faker } from "@faker-js/faker";
 
fakerExtension({
  create: (randomizer) => new Faker({ locale: [base, en], randomizer }),
});

Without create, fabricating a faker field in a browser bundle throws FakerExtensionError.UnloadableError, and its message says to use create. An empty locale throws FakerExtensionError.EmptyLocaleError when you call fakerExtension. A locale name faker doesn't have throws FakerExtensionError.UnknownLocaleError on the first draw, because resolving the name is what loads faker.

Every builder is a real kind, never opaque

The tempting way to wrap a faker method is T.opaque(() => faker.person.fullName()), and this package deliberately doesn't do that. Fabricator knows nothing about an opaque value: it converts to Type.Unknown() in any adapter, and combinatorial/coverage treat it as a single outcome.

Instead, each builder returns the core kind that matches the method's declared return type:

faker returnsbuilder returnsvia the TypeBox adapter
stringT.stringType.String()
DateT.dateType.Date()
a record shapeT.object({ ... })Type.Object({ ... })
a literal unionT.enum.uniform([...])Type.Union([Type.Literal(), …])
numberT.numberType.Number()
booleanT.booleanType.Boolean()
bigintT.bigintType.BigInt()
[number, number]T.tuple([T.number, T.number])Type.Tuple([Type.Number(), Type.Number()])
Date[]T.array(T.date)Type.Array(Type.Date())

So a schema built with faker validates, enumerates, and converts exactly like a hand-written one:

import { toTypeBox } from "@ghostry/fabricator-adapter-typebox-v0";
 
toTypeBox(T.faker.person.sexType());
// Type.Union([Type.Literal('female'), Type.Literal('generic'), Type.Literal('male')])

Some string methods always produce output in a known JSON Schema format, whatever options you pass. Those carry the format as a hint, which ends up in the converted schema:

toTypeBox(T.faker.internet.email()); // Type.String({ format: 'email' })
toTypeBox(T.faker.database.mongodbObjectId()); // Type.String({ pattern: '^[0-9a-fA-F]{24}$' })

The list is chosen by hand, not exhaustive. A method whose output shape depends on its options, such as git.commitSha's length, gets no hint.

Keeping the mapping honest

Every builder's kind is checked at compile time against faker's declared return type. If a faker release changes a return type, this package fails to build, instead of shipping a schema that disagrees with the data.

Modules

The extension mirrors these faker data modules, with faker's own method names in each:

airline, animal, book, color, commerce, company, database, datatype, date, finance, food, git, hacker, image, internet, location, lorem, music, number, person, phone, science, string, system, vehicle, word

Each builder takes the same options as its faker method, so what you already know about faker still applies:

T.faker.lorem.paragraphs({ min: 2, max: 4 });
T.faker.number.int({ min: 1, max: 100 });
T.faker.date.past({ years: 3 });

Some faker methods overlap with core, such as datatype.boolean, number.int, and string.alphanumeric. Both versions stay available. Faker's follow its locale and API, while core's are more configurable and can be enumerated. Pick whichever suits the field.

Where the mirror differs from faker

The mirror deliberately differs from faker in the places below. Each difference is what lets every builder return a real kind, and they may surprise you if you know faker well.

helpers is absent

helpers is a set of utilities, not a data module, and core already covers all of it. Core's versions are usually better, because they can be enumerated and converted by adapters:

faker.helpers.…core
arrayElement, objectKey, objectValue, enumValueT.enum.uniform([...])
weightedArrayElementT.enum.weighted([...])
arrayElements, multipleT.array(...).whereby({ length })
maybeT.optional / T.omittable / T.undefinable
rangeToNumberT.number.whereby({ min, max })

Most of its methods are generic, so mirrored builders would only type as unknown anyway. slugify, mustache, and replaceSymbols transform your own input instead of generating anything. The two with no core equivalent, fromRegExp and fake, are available through use.

Some color.* methods are split in two

color.rgb() returns a string or a number[] depending on options.format, and each method has a different default. No single kind can describe that, and choosing the kind from the arguments would make the schema's type depend on a runtime value. So each of these methods becomes two named builders:

T.faker.color.rgb.text(); // T.string
T.faker.color.rgb.text({ format: "css" });
T.faker.color.rgb.channels(); // T.array(T.number)
T.faker.color.rgb.channels({ includeAlpha: true });

There is deliberately no bare T.faker.color.rgb(). Every form is named. The same goes for cmyk, hsl, hwb, lab, lch, and colorByCSSColorSpace. color's other methods are ordinary builders.

Channels are T.array(T.number) rather than T.tuple because the number of channels depends on the options: includeAlpha adds one, and cmyk has four where the rest have three. A fixed-length tuple would be wrong for the options most likely to be passed.

A narrower declared type narrows the kind

Where faker declares a narrower return type than a plain string or array, the builder uses the narrower kind. A union of literals becomes an enum, not a string:

T.faker.person.sexType(); // T.enum.uniform(['female', 'generic', 'male'])

So combinatorial/coverage can enumerate the field, and it converts to a union of literals instead of an open string that happens to hold one of three values.

A fixed-length array becomes a tuple, not an array:

T.faker.location.nearbyGPSCoordinate(); // T.tuple([T.number, T.number])

No option can change the [latitude, longitude] length, which is what makes it different from the color channels above.

use — for what the mirror doesn't cover

use gives you the extension's Faker inside a producer, so anything you call on it still draws from that field's own stream. Each form names the kind it returns, so you say what comes back and keep a real kind.

T.faker.use.string((f) => f.helpers.fromRegExp("[A-Z]{3}-[0-9]{4}"));
T.faker.use.string((f) =>
  f.helpers.fake("{{person.firstName}} {{person.lastName}}"),
);
T.faker.use.number((f) => f.helpers.rangeToNumber({ min: 1, max: 10 }));
T.faker.use.opaque((f) => f.helpers.arrayElement(["free", "pro"] as const));

use.string, .number, .date, .boolean, and .bigint still convert through adapters. use.opaque is the only way to get an opaque schema from this package, because it is the one case where you haven't said what shape comes back.

What "now" means

Faker's relative-date methods use the same clock as T.date.past and T.date.future, so the two never disagree within one schema:

T.object({ core: T.date.past, faker: T.faker.date.past() });

That includes a wrap({ clock }, …) active when you fabricate, because the clock is read on every fabrication, not when the extension is set up. See Reproducibility for what the clock is and its default.

fakerExtension deliberately has no reference-date option. A second clock, set separately, could drift from T.date.past in the same object.

Reproducibility

Everything in Reproducibility applies as-is. The same clock (and salt, if any) gives the same faker output, and each field's stream depends on its position in the schema, so adding or reordering a field leaves the others alone.

As a result:

faker.seed(...) does nothing. Fabricator does the seeding here, and a second seed fighting over the same output is the problem this package exists to remove. Change the instance's clock (or its salt, if it has one) instead.

The global faker object is not touched. The extension builds its own Faker with its own randomizer, so using or seeding the global faker elsewhere in your tests can't change fabricated output, and the reverse is also true.

If you need a Faker built differently, pass create. It receives the extension's randomizer and returns the Faker to use, so output stays reproducible:

fakerExtension({
  create: (randomizer) => new Faker({ locale: [de, en], randomizer }),
});

You can't pass a Faker you already built. Its randomizer is fixed when it is created, so it can't draw from fabricator's streams.

Errors

Faker can only draw while a value is being fabricated. If you keep the Faker that use gives you and call it later, outside fabricate(), it throws FakerExtensionError.NoActiveScopeError, because there is no field whose stream it could draw from.

An error's .name starts with this package's name, as in "@ghostry/fabricator-extension-faker-v10:NoActiveScopeError", so it can't be mistaken for one of core's.

FakerExtensionError extends core's FabricatorError, so one catch covers both packages:

import { FabricatorError } from "@ghostry/fabricator";
 
try {
  /* ... */
} catch (e) {
  if (e instanceof FabricatorError) {
    /* both packages' failures land here */
  }
}