interface-forge - v2.5.0
    Preparing search index...

    Class Factory<T, O, F>

    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.

    Type Parameters

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    _defaultRefDate: () => Date
    afterBuildHooks: AfterBuildHook<T>[] = []
    airline: AirlineModule
    animal: AnimalModule
    beforeBuildHooks: BeforeBuildHook<T>[] = []
    commerce: CommerceModule
    company: CompanyModule
    database: DatabaseModule
    datatype: DatatypeModule
    definitions: LocaleProxy
    factory: F
    finance: FinanceModule
    hacker: HackerModule
    helpers: HelpersModule
    internet: InternetModule
    location: LocationModule
    number: NumberModule
    options?: { maxDepth: number } & Omit<O, "locale" | "maxDepth" | "randomizer">
    person: PersonModule
    rawDefinitions: LocaleDefinition
    science: ScienceModule
    string: StringModule
    system: SystemModule
    vehicle: VehicleModule

    Accessors

    • get address(): LocationModule

      Returns LocationModule

      Use Faker#location instead

    • get defaultRefDate(): () => Date

      Gets a new reference date used to generate relative dates.

      Returns () => Date

    • get name(): PersonModule

      Returns PersonModule

      Use Faker#person instead

    Methods

    • 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.

      Parameters

      • hook: AfterBuildHook<T>

        Function that receives the built instance and returns the modified instance

      Returns this

      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.

      Parameters

      • size: number

        Number of instances to generate (must be non-negative integer)

      • Optionalkwargs: Partial<T> | Partial<T>[]

        Either a single partial object (applied to all) or an array of partials (one per instance)

      Returns T[]

      Array of generated instances

      If size is negative or not an integer

    • Creates multiple instances asynchronously, allowing use of async factory functions. This method supports both synchronous and asynchronous factory functions and hooks.

      Parameters

      • size: number

        Number of instances to generate (must be non-negative integer)

      • Optionalkwargs: Partial<T> | Partial<T>[]

        Either a single partial object (applied to all) or an array of partials (one per instance)

      Returns Promise<F extends FactoryFunction<T> ? T[] : Partial<T>[]>

      Promise that resolves to an array of generated instances

      If size is negative or not an integer

      const UserFactory = new Factory<User>(async (factory) => ({
      id: factory.string.uuid(),
      email: factory.internet.email(),
      apiKey: await generateApiKey() // async operation
      }));

      const users = await UserFactory.batchAsync(5);
    • 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.

      Parameters

      • hook: BeforeBuildHook<T>

        Function that receives partial parameters and returns modified parameters

      Returns this

      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.

      Parameters

      • Optionalkwargs: Partial<T>

        Properties to override in the generated instance

      • Optionaloptions: Partial<O>

        Factory options including fixture generation

      Returns F extends FactoryFunction<T> ? T : Partial<T>

      A new instance with factory-generated values merged with any overrides

      If async hooks are registered

      If fixture operations fail

      If fixture validation fails

    • 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.

      Parameters

      • Optionalkwargs: Partial<T>

        Optional properties to override in the generated instance

      • Optionaloptions: Partial<O>

        Factory options including fixture generation

      Returns Promise<F extends FactoryFunction<T> ? T : Partial<T>>

      A promise that resolves to the built and processed instance

      If any hook throws an error during execution

      If fixture operations fail

      If fixture validation fails

    • Creates a new factory by merging this factory's schema with additional properties. Composed properties can be static values or other factory instances.

      Type Parameters

      • U

        The composed type (must extend the base type T)

      Parameters

      Returns Factory<U>

      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.

      Parameters

      • Optionalkwargs: Partial<T>

        Optional properties to override in the generated instance

      • Optionaloptions: CreateOptions<T>

        Options including an optional persistence adapter

      Returns Promise<T>

      Promise that resolves with the persisted instance

      If no persistence adapter is configured

      // 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.

      Parameters

      • size: number

        Number of instances to create and persist

      • Optionalkwargs: Partial<T> | Partial<T>[]

        Optional overrides for the instances

      • Optionaloptions: CreateManyOptions<T>

        Options including an optional persistence adapter

      Returns Promise<T[]>

      Promise that resolves with the persisted instances

      If no persistence adapter is configured

      // 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.

      Type Parameters

      • U

        The extended type (must extend the base type T)

      Parameters

      • factoryFn: FactoryFunction<U>

        Function that returns properties to merge with the base schema

      Returns Factory<U>

      A new factory with inherited and extended properties

    • Returns an object with metadata about the current locale.

      Returns MetadataDefinition

      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' }

      8.1.0

    • 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.

      Type Parameters

      • U

      Parameters

      • iterable: Iterable<U>

        An iterable containing values to cycle through (must not be empty)

      Returns Generator<U, U, U>

      A generator that yields values in order, restarting after the last element

      If the iterable is empty

    • Creates a new factory where all properties are optional (Partial). This is useful for creating test data where only specific fields need to be set.

      Returns Factory<Partial<T>>

      A new factory that produces Partial objects

    • Creates 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).

      Type Parameters

      • U

      Parameters

      • iterable: Iterable<U>

        An iterable containing values to sample from (must not be empty)

      Returns Generator<U, U, U>

      A generator that yields random values without consecutive repetition

      If the iterable is empty

    • 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.

      Parameters

      • Optionalseed: number

        The seed to use. Defaults to a random number.

      Returns 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());

      6.0.0

    • 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.

      Parameters

      • seedArray: number[]

        The seed array to use.

      Returns number[]

      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());

      6.0.0

    • 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.

      Parameters

      • Optionalseed: number | number[]

        The seed or seed array to use.

      Returns number | number[]

      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());

      6.0.0

    • Sets the refDate source to use if no refDate date is passed to the date methods.

      Parameters

      • OptionaldateOrSource: 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().

      Returns void

      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

      8.0.0

    • 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.

      Type Parameters

      • R
      • A extends unknown[]

      Parameters

      • handler: (...args: A) => R

        The function to call during object generation

      • ...args: A

        Arguments to pass to the function when called

      Returns R

      A reference that will execute the function during build

    • Sets the default persistence adapter for this factory instance.

      Parameters

      Returns this

      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);