Faker

repository·next·Indexed 12 days ago

https://github.com/faker-js/faker

A JavaScript library for generating massive amounts of realistic fake contextual data, such as names, addresses, and finance, for testing and development. Version 10.5.0 features support for over 70 locales, tree-shakeable module functions, and high-precision RNG. It integrates with testing frameworks like Vitest, Jest, Cypress, and Playwright.

Tokens
67.7K
Snippets
291
Records
316
Agent score
94%

What's inside Faker

  1. Overview of Faker modules

    next

    Faker organizes its data generation capabilities into three main types of modules:

    1. Basic Datatypes: Core modules for fundamental data types including datatype, date, number, and string.
    2. Topic Specific Modules: Modules focused on specific domains, such as animal, food, and many others.
    3. Helpers: The helpers module provides utility methods to work with your own data or data generated by other Faker methods.
  2. What is a Randomizer and when to use one

    next

    The Randomizer interface allows you to use a custom randomness source within Faker. While Faker's default Randomizer is sufficient for most use cases, you might want to implement or provide a custom one to:

    1. Re-use the same Randomizer across multiple Faker instances: This ensures that seeding one instance affects all others, which is critical for reproducibility when generating data in different locales (e.g., generating a Chinese identity and an English alias simultaneously).
    2. Use a third-party random number generator: This allows you to synchronize Faker's randomness with other libraries (like those that generate strings from RegExp) to ensure the entire execution context is reproducible.

    Note: A Randomizer must be provided during the construction of a Faker or SimpleFaker instance.

  3. Strategies for ensuring uniqueness in generated data

    next

    Since Faker methods do not inherently return unique values, you can use the following strategies to enforce uniqueness in your datasets:

    1. Batch Generation: Use faker.helpers.uniqueArray() to generate a specific number of unique items in a single array.
    2. Prefixing/Suffixing: If the Faker data set is too small to satisfy your uniqueness requirements, append or prepend sequential identifiers (e.g., 1.user@example.com, 2.user@example.com) to the generated values.
    3. Custom Tracking Logic: Implement a wrapper that maintains a Set of previously generated values and re-calls the Faker method if a duplicate is detected.
    4. Third-party Packages: Use external libraries designed for uniqueness enforcement, such as enforce-unique or @dpaskhin/unique.
  4. Create a custom Faker instance with locale fallbacks

    next

    If built-in instances do not meet your requirements, you can instantiate a new Faker class. You can provide an array of locales to the locale option to define a fallback chain. Faker will check each locale in the order provided and use the first one that contains the requested data.

    Common fallback patterns include:

    • Custom Overwrites: Providing a LocaleDefinition object to override specific fields in existing locales.
    • Regional Fallbacks: Using a specific regional locale (e.g., de_CH) before a generic one (e.g., de).
    • Language Fallbacks: Using a generic language (e.g., en) to fill gaps in other locales.
    • Base Locale: Including base at the end of the chain to provide universal data like emojis.
    import type { LocaleDefinition } from '@faker-js/faker';
    import { base, de, de_CH, en, Faker } from '@faker-js/faker';
    
    const customLocale: LocaleDefinition = {
      title: 'My custom locale',
      internet: {
        domainSuffix: ['test'],
      },
    };
    
    export const customFaker = new Faker({
      locale: [customLocale, de_CH, de, en, base],
    });
  5. Handle word module resolution strategy changes

    next

    In v10, the default resolution strategy for faker.word methods changed to 'fail'. If a word matching your criteria (e.g., specific length) cannot be found, Faker will now throw a FakerError instead of returning a random word of any length.

    To restore the v9 behavior (returning a random word regardless of constraints), pass { strategy: 'any-length' } to the method.

    Affected methods:

    • faker.word.adjective()
    • faker.word.adverb()
    • faker.word.conjunction()
    • faker.word.interjection()
    • faker.word.noun()
    • faker.word.preposition()
    • faker.word.sample()
    • faker.word.verb()
    // v10 default behavior: Throws error if no noun matches length
    faker.word.noun({ length: { min: 20, max: 25 } });
    
    // To restore v9 behavior (returns any noun):
    faker.word.noun({ strategy: 'any-length' });
  6. How to get reproducible results with seeding

    next

    By default, Faker generates different random values on every call. To produce consistent, reproducible results (e.g., for testing), use faker.seed(number).

    Note: Upgrading Faker versions may change the underlying data, which can result in different values even with the same seed.

    Handling Relative Dates: Methods like faker.date.past() or faker.date.soon() depend on the current date ("today"), making them non-reproducible with just a seed. To fix this, you must provide a fixed reference date using refDate in the method options or by setting a global default with faker.setDefaultRefDate().

    faker.seed(123);
    const firstRandom = faker.number.int();
    
    // Resetting the seed resets the sequence
    faker.seed(123);
    const secondRandom = faker.number.int();
    
    // For reproducible relative dates:
    faker.setDefaultRefDate('2023-01-01T00:00:00.000Z');
    faker.date.soon();
  7. Understand high precision RNG in v9

    next

    Starting with v9, FakerJS uses a 53-bit random value (via generateMersenne53Randomizer) by default instead of a 32-bit random value. This change provides:

    • Improved distribution: Reduces the likelihood of duplicate values in large datasets. For example, the chance of duplicates in faker.number.int() dropped from 1 / 10,000 to less than 1 / 8,000,000.
    • Subtle result differences: If you are using a fixed seed, the generated values will differ from v8 because the algorithm now consumes two seed values per step instead of one.

    You can manually control the precision by providing a specific randomizer to SimpleFaker.

    import {
      SimpleFaker,
      generateMersenne32Randomizer,
      generateMersenne53Randomizer,
    } from '@faker-js/faker';
    
    // < v9 default (32-bit)
    const oldFaker = new SimpleFaker({
      randomizer: generateMersenne32Randomizer(),
    });
    oldFaker.seed(123);
    const oldValue = oldFaker.helpers.multiple(() => oldFaker.number.int(10), {
      count: 10,
    });
    
    // > v9 default (53-bit)
    const newFaker = new SimpleFaker({
      randomizer: generateMersenne53Randomizer(),
    });
    newFaker.seed(123);
    const newValue = newFaker.helpers.multiple(() => newFaker.number.int(10), {
      count: 5,
    });
  8. Use different locales in Faker

    next

    The default faker instance uses the English locale. To use a specific locale, you can import a pre-made instance (e.g., fakerDE for German) or create a custom instance using the Faker class with a list of preferred locales. If a specific module is not available in the chosen locale, Faker will fall back to English.

    // Using a pre-made locale instance (ESM)
    import { fakerDE as faker } from '@faker-js/faker';
    
    // Using a pre-made locale instance (CJS)
    const { fakerDE: faker } = require('@faker-js/faker');
    
    // Creating a custom instance with multiple locales
    import { de, de_CH, Faker } from '@faker-js/faker';
    
    export const faker = new Faker({
      locale: [de_CH, de],
    });
  9. Understand Locale Code Formats

    next

    Faker uses a systematic naming convention for locales based on international standards:

    1. Language Code: The first two characters are a lowercase ISO 639-1 language code (e.g., ar for Arabic, en for English).
    2. Country Code (Optional): An underscore followed by a two-letter uppercase ISO 3166-1 alpha-2 country code (e.g., en_US for English (United States), en_AU for English (Australia)).
    3. Variant (Optional): An additional underscore followed by a variant for specific dialects or scripts (e.g., en_AU_ocker for Australian Ocker dialect, sr_RS_latin for Serbian in Latin script).

    You can access prebuilt Faker instances or raw locale definitions using the allFakers and allLocales objects, where the locale codes serve as keys.

    import { allFakers, allLocales } from '@faker-js/faker';
    
    console.dir(allFakers['de_AT']); // the prebuilt Faker instance for de_AT
    console.dir(allLocales['de_AT']); // the raw locale definitions for de_AT
    
    // Example: Enumerating all locales
    for (let key of Object.keys(allFakers)) {
      try {
        console.log(`In locale ${key}, a sample name is ${allFakers[key].person.fullName()}`);
      } catch (e) {
        console.log(`In locale ${key}, an error occurred: ${e}`);
      }
    }
  10. Optimize bundle size with tree-shaking in v9

    next
    FakerJS v9 includes optimizations to support better tree-shaking by bundlers. The package now specifies "sideEffects": false in its package.json, and the allLocales variable has been refactored from a named wildcard export to a named variable export. This allows bundlers to exclude unused modules and locales, significantly reducing the final bundle size (e.g., from ~2.77 MiB in v8.4.1 to ~438 KiB in v9.0.0).
  11. Use Faker with Vitest or Jest

    next

    Faker integrates seamlessly with Vitest and Jest. For Vitest, ensure you import testing methods (like describe, it, expect) from vitest. For Jest, these are typically available globally or imported from @jest/globals.

    To ensure deterministic results for snapshot testing, use faker.seed(number) to provide a static value. It is a best practice to use an afterEach hook to call faker.seed() without arguments to re-seed the instance with a new random value after each test, preventing side effects in other tests.

    import { faker } from '@faker-js/faker/locale/en';
    import { afterEach, describe, expect, it } from 'vitest';
    
    // Re-seed after each test to ensure other tests remain random
    afterEach(() => {
      faker.seed();
    });
    
    describe('reverse array', () => {
      it('should reverse the array', () => {
        // Seed with a static number for deterministic snapshot testing
        faker.seed(1234);
        const title = faker.person.jobTitle();
        const name = faker.person.fullName();
        const animal = faker.animal.bear();
    
        const array = [title, name, animal];
    
        expect(array.reverse()).toStrictEqual([animal, name, title]);
        expect(array.reverse()).toMatchSnapshot();
      });
    });