Faker
repository·next·Indexed 12 days ago
https://github.com/faker-js/fakerA 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.
What's inside Faker
- Faker is a library used to generate fake (but reasonable) mock data. It is primarily used for testing, development, and populating databases with realistic-looking information. While the concept originated in Perl, this repository is the official JavaScript port.
Overview of Faker modules
nextFaker organizes its data generation capabilities into three main types of modules:
- Basic Datatypes: Core modules for fundamental data types including
datatype,date,number, andstring. - Topic Specific Modules: Modules focused on specific domains, such as
animal,food, and many others. - Helpers: The
helpersmodule provides utility methods to work with your own data or data generated by other Faker methods.
- Basic Datatypes: Core modules for fundamental data types including
What is a Randomizer and when to use one
nextThe
Randomizerinterface allows you to use a custom randomness source within Faker. While Faker's defaultRandomizeris sufficient for most use cases, you might want to implement or provide a custom one to:- Re-use the same
Randomizeracross multipleFakerinstances: 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). - 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
Randomizermust be provided during the construction of aFakerorSimpleFakerinstance.- Re-use the same
Strategies for ensuring uniqueness in generated data
nextSince Faker methods do not inherently return unique values, you can use the following strategies to enforce uniqueness in your datasets:
- Batch Generation: Use
faker.helpers.uniqueArray()to generate a specific number of unique items in a single array. - 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. - Custom Tracking Logic: Implement a wrapper that maintains a
Setof previously generated values and re-calls the Faker method if a duplicate is detected. - Third-party Packages: Use external libraries designed for uniqueness enforcement, such as
enforce-uniqueor@dpaskhin/unique.
- Batch Generation: Use
Create a custom Faker instance with locale fallbacks
nextIf built-in instances do not meet your requirements, you can instantiate a new
Fakerclass. You can provide an array of locales to thelocaleoption 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
LocaleDefinitionobject 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
baseat 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], });- Custom Overwrites: Providing a
Handle word module resolution strategy changes
nextIn v10, the default resolution strategy for
faker.wordmethods changed to'fail'. If a word matching your criteria (e.g., specific length) cannot be found, Faker will now throw aFakerErrorinstead 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' });How to get reproducible results with seeding
nextBy 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()orfaker.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 usingrefDatein the method options or by setting a global default withfaker.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();Understand high precision RNG in v9
nextStarting 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 from1 / 10,000to less than1 / 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, });- Improved distribution: Reduces the likelihood of duplicate values in large datasets. For example, the chance of duplicates in
Use different locales in Faker
nextThe default
fakerinstance uses the English locale. To use a specific locale, you can import a pre-made instance (e.g.,fakerDEfor German) or create a custom instance using theFakerclass 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], });Understand Locale Code Formats
nextFaker uses a systematic naming convention for locales based on international standards:
- Language Code: The first two characters are a lowercase ISO 639-1 language code (e.g.,
arfor Arabic,enfor English). - Country Code (Optional): An underscore followed by a two-letter uppercase ISO 3166-1 alpha-2 country code (e.g.,
en_USfor English (United States),en_AUfor English (Australia)). - Variant (Optional): An additional underscore followed by a variant for specific dialects or scripts (e.g.,
en_AU_ockerfor Australian Ocker dialect,sr_RS_latinfor Serbian in Latin script).
You can access prebuilt Faker instances or raw locale definitions using the
allFakersandallLocalesobjects, 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}`); } }- Language Code: The first two characters are a lowercase ISO 639-1 language code (e.g.,
Optimize bundle size with tree-shaking in v9
nextFakerJS v9 includes optimizations to support better tree-shaking by bundlers. The package now specifies"sideEffects": falsein itspackage.json, and theallLocalesvariable 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).Use Faker with Vitest or Jest
nextFaker integrates seamlessly with Vitest and Jest. For Vitest, ensure you import testing methods (like
describe,it,expect) fromvitest. 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 anafterEachhook to callfaker.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(); }); });