The type of objects this factory generates
The type of factory options
Protected
_Protected
afterReadonly
airlineReadonly
animalProtected
beforeReadonly
bookReadonly
colorReadonly
commerceReadonly
companyReadonly
databaseReadonly
datatypeReadonly
dateReadonly
definitionsProtected
Readonly
factoryReadonly
financeReadonly
foodReadonly
gitReadonly
hackerReadonly
helpersReadonly
imageReadonly
internetReadonly
locationReadonly
loremReadonly
musicReadonly
numberOptional
Readonly
optionsReadonly
personReadonly
phoneReadonly
rawReadonly
scienceReadonly
stringReadonly
systemReadonly
vehicleReadonly
wordUse Faker#location instead
Gets a new reference date used to generate relative dates.
Use Faker#person instead
Adds a hook that will be executed after building the instance. Hooks are executed in the order they were added and can be either synchronous or asynchronous. This method returns the factory instance for method chaining.
Function that receives the built instance and returns the modified instance
The current Factory instance for method chaining
Generates an array of instances using the factory's schema. Supports both uniform overrides (same for all instances) and individual overrides per instance.
Array of generated instances
Creates multiple instances asynchronously, allowing use of async factory functions. This method supports both synchronous and asynchronous factory functions and hooks.
Promise that resolves to an array of generated instances
Adds a hook that will be executed before building the instance. Hooks receive the partial parameters (kwargs) and can modify them before the instance is built. Multiple hooks are executed in the order they were added.
Function that receives partial parameters and returns modified parameters
The current Factory instance for method chaining
Generates a single instance of type T using the factory's schema. Properties can be overridden by passing a partial object. Synchronous hooks are automatically applied if registered. If async hooks are registered, a ConfigurationError is thrown.
A new instance with factory-generated values merged with any overrides
Builds an instance asynchronously with all registered hooks applied in sequence. This method supports both synchronous and asynchronous hooks. Hooks are executed in the order they were registered.
A promise that resolves to the built and processed instance
Protected
buildProtected
buildProtected
calculateCreates a new factory by merging this factory's schema with additional properties. Composed properties can be static values or other factory instances.
The composed type (must extend the base type T)
Object mapping property names to values or factories
A new factory that generates objects with combined properties
Creates and persists a single instance using the factory's schema. Uses the configured persistence adapter if available.
Optional
kwargs: Partial<T>Optional properties to override in the generated instance
Optional
options: CreateOptions<T>Options including an optional persistence adapter
Promise that resolves with the persisted instance
// With default adapter
const userFactory = new Factory<User>((faker) => ({
email: faker.internet.email(),
name: faker.person.fullName()
})).withAdapter(mongooseAdapter);
const user = await userFactory.create({ name: 'John' });
// With adapter in options
const user2 = await userFactory.create(
{ name: 'Jane' },
{ adapter: prismaAdapter }
);
Creates and persists multiple instances in a batch operation. Uses the configured persistence adapter if available.
Promise that resolves with the persisted instances
// Create 5 users with default adapter
const users = await userFactory.createMany(5);
// With individual overrides
const users2 = await userFactory.createMany(3, [
{ role: 'admin' },
{ role: 'user' },
{ role: 'guest' }
]);
// With adapter in options
const users3 = await userFactory.createMany(
10,
undefined,
{ adapter: typeormAdapter }
);
Creates a new factory that inherits from this factory's schema with modifications. Unlike compose(), extend() provides access to the factory instance for dynamic property generation.
The extended type (must extend the base type T)
Function that returns properties to merge with the base schema
A new factory with inherited and extended properties
Protected
getProtected
getReturns an object with metadata about the current locale.
import { faker, fakerES_MX } from '@faker-js/faker';
// const { faker, fakerES_MX } = require("@faker-js/faker")
faker.getMetadata(); // { title: 'English', code: 'en', language: 'en', endonym: 'English', dir: 'ltr', script: 'Latn' }
fakerES_MX.getMetadata(); // { title: 'Spanish (Mexico)', code: 'es_MX', language: 'es', endonym: 'Español (México)', dir: 'ltr', script: 'Latn', country: 'MX' }
Creates a generator that yields values from an iterable in sequential, cyclic order. Values must be explicitly requested via the generator's next() method. When all values have been yielded, the generator starts over from the beginning.
A generator that yields values in order, restarting after the last element
Protected
parseProtected
readCreates a generator that yields random values from an iterable without consecutive duplicates. Each value is randomly selected with replacement, but the generator ensures the same value is never returned twice in a row (unless the iterable contains only one element).
A generator that yields random values without consecutive repetition
Sets the seed or generates a new one.
Please note that generated values are dependent on both the seed and the number of calls that have been made since it was set.
This method is intended to allow for consistent values in tests, so you might want to use hardcoded values as the seed.
In addition to that it can be used for creating truly random tests (by passing no arguments), that still can be reproduced if needed, by logging the result and explicitly setting it if needed.
Optional
seed: numberThe seed to use. Defaults to a random number.
The seed that was set.
// Consistent values for tests:
faker.seed(42)
faker.number.int(10); // 4
faker.number.int(10); // 10
faker.seed(42)
faker.number.int(10); // 4
faker.number.int(10); // 10
// Random but reproducible tests:
// Simply log the seed, and if you need to reproduce it, insert the seed here
console.log('Running test with seed:', faker.seed());
Sets the seed array.
Please note that generated values are dependent on both the seed and the number of calls that have been made since it was set.
This method is intended to allow for consistent values in a tests, so you might want to use hardcoded values as the seed.
In addition to that it can be used for creating truly random tests (by passing no arguments), that still can be reproduced if needed, by logging the result and explicitly setting it if needed.
The seed array to use.
The seed array that was set.
// Consistent values for tests:
faker.seed([42, 13, 17])
faker.number.int(10); // 3
faker.number.int(10); // 10
faker.seed([42, 13, 17])
faker.number.int(10); // 3
faker.number.int(10); // 10
// Random but reproducible tests:
// Simply log the seed, and if you need to reproduce it, insert the seed here
console.log('Running test with seed:', faker.seed());
Sets the seed or generates a new one.
Please note that generated values are dependent on both the seed and the number of calls that have been made since it was set.
This method is intended to allow for consistent values in a tests, so you might want to use hardcoded values as the seed.
In addition to that it can be used for creating truly random tests (by passing no arguments), that still can be reproduced if needed, by logging the result and explicitly setting it if needed.
Optional
seed: number | number[]The seed or seed array to use.
The seed that was set.
// Consistent values for tests (using a number):
faker.seed(42)
faker.number.int(10); // 4
faker.number.int(10); // 10
faker.seed(42)
faker.number.int(10); // 4
faker.number.int(10); // 10
// Consistent values for tests (using an array):
faker.seed([42, 13, 17])
faker.number.int(10); // 3
faker.number.int(10); // 10
faker.seed([42, 13, 17])
faker.number.int(10); // 3
faker.number.int(10); // 10
// Random but reproducible tests:
// Simply log the seed, and if you need to reproduce it, insert the seed here
console.log('Running test with seed:', faker.seed());
Sets the refDate
source to use if no refDate
date is passed to the date methods.
Optional
dateOrSource: string | number | Date | (() => Date)The function or the static value used to generate the refDate
date instance.
The function must return a new valid Date
instance for every call.
Defaults to () => new Date()
.
faker.seed(1234);
// Default behavior
// faker.setDefaultRefDate();
faker.date.past(); // Changes based on the current date/time
// Use a static ref date
faker.setDefaultRefDate(new Date('2020-01-01'));
faker.date.past(); // Reproducible '2019-07-03T08:27:58.118Z'
// Use a ref date that changes every time it is used
let clock = new Date("2020-01-01").getTime();
faker.setDefaultRefDate(() => {
clock += 1000; // +1s
return new Date(clock);
});
faker.defaultRefDate() // 2020-01-01T00:00:01Z
faker.defaultRefDate() // 2020-01-01T00:00:02Z
Creates a reference to a function call for lazy evaluation within factory definitions. The function and its arguments are stored but not executed until the factory builds an object. Essential for creating relationships between factories without causing infinite recursion.
A reference that will execute the function during build
Protected
validateSets the default persistence adapter for this factory instance.
The persistence adapter to use as default
The current Factory instance for method chaining
import { MongooseAdapter } from './adapters/mongoose-adapter';
const userFactory = new Factory<User>((faker) => ({
id: faker.string.uuid(),
email: faker.internet.email(),
name: faker.person.fullName()
}));
// Set default adapter
const factoryWithDb = userFactory.withAdapter(
new MongooseAdapter(UserModel)
);
// Now all create/createMany calls will use this adapter
const user = await factoryWithDb.create();
const users = await factoryWithDb.createMany(5);
Protected
write
A factory class for generating type-safe mock data by extending Faker.js functionality. Provides methods for creating single instances, batches, and complex object compositions with support for circular references through depth control and persistence.