Faker v10
此内容尚不支持你的语言。
Faker is a popular library that generates fake (but reasonable) data that can be used for things such as unit testing, performance testing, building demos, and working without a completed backend.
The Faker plugin for Hey API generates factory functions from your OpenAPI spec that return realistic mock data using @faker-js/faker.
Collaborators
Section titled “Collaborators”Features
Section titled “Features”- Faker v9 and v10 support
- seamless integration with
@hey-api/openapi-tsecosystem - factory functions for reusable schema definitions, operation requests, and operation responses
- smart property name inference for realistic data (e.g.
email→faker.internet.email()) - constraint and format awareness (min/max, string formats, array bounds)
- optional property and default value handling
- dependency injection for custom faker instances (locale, seed)
- minimal learning curve thanks to extending the underlying technology
Installation
Section titled “Installation”In your configuration, add @faker-js/faker to your plugins and you’ll be ready to generate faker factories. 🎉
export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins '@faker-js/faker', ],};Output
Section titled “Output”The Faker plugin will generate the following artifacts, depending on the input specification.
Definitions
Section titled “Definitions”A factory function is generated for every reusable definition from your input.
import { faker, type Faker } from '@faker-js/faker';
import type { Bar, Foo } from '../types.gen';
export const fakeFoo = (options?: Options): Foo => ({ name: ensureFaker(options).string.sample(), age: ensureFaker(options).number.int({ min: 1, max: 120 }),});
export const fakeBar = (options?: Options): Bar => ensureFaker(options).helpers.arrayElement(['baz', 'qux']);export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@faker-js/faker', definitions: true, }, ],};You can customize the naming and casing pattern for definitions factories using the .name and .case options.
Requests
Section titled “Requests”A single factory function is generated per operation for request data. It combines the request body, path parameters, query parameters, and headers into one object. Only keys with actual data are included.
// body + path + query combined into one factoryexport const fakeUpdatePetRequest = (options?: Options): Omit<UpdatePetData, 'url'> => { const f = options?.faker ?? faker; return { body: { name: f.string.sample(), tag: fakeTag(options), }, path: { id: f.string.uuid(), }, query: { dryRun: f.datatype.boolean(), }, };};
// body onlyexport const fakeCreatePetRequest = (options?: Options): Omit<CreatePetData, 'url'> => { const f = options?.faker ?? faker; return { body: { name: f.string.sample(), }, };};export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@faker-js/faker', requests: true, }, ],};You can customize the naming and casing pattern for requests factories using the .name and .case options.
Responses
Section titled “Responses”A factory function is generated for operation responses. When an operation has a single success response, the factory is unsuffixed. When multiple responses exist, each factory is suffixed with the status code.
// single success response — unsuffixedexport const fakeCreatePetResponse = (options?: Options): CreatePetResponse => fakePet(options);
// multiple responses — suffixed with status codeexport const fakeGetPetResponse200 = (options?: Options): GetPetResponses[200] => fakePet(options);
export const fakeGetPetResponse404 = (options?: Options): GetPetErrors[404] => fakeError(options);export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@faker-js/faker', responses: true, }, ],};You can customize the naming and casing pattern for responses factories using the .name and .case options.
Smart Inference
Section titled “Smart Inference”The plugin infers semantically appropriate faker methods from property names, producing more realistic mock data without requiring explicit schema formats or annotations.
// property name "email" → faker.internet.email()// property name "firstName" → faker.person.firstName()// property name "city" → faker.location.city()// property name "id" → faker.string.uuid()// property name "age" → faker.number.int({ min: 1, max: 120 })Ancestor context is also used for disambiguation. For example, name under a User schema produces faker.person.fullName(), while name under a Company schema produces faker.company.name().
Explicit schema annotations (format, pattern, constraints) always take priority over name-based inference.
Name Rules
Section titled “Name Rules”You can extend or override the built-in name inference with custom nameRules. Rules are defined per schema type (string or number) and map property names to specific faker methods.
export const fakeError = (options?: Options): Error => { const f = options?.faker ?? faker; return { code: f.number.int(), message: f.word.words({ count: 4 }), };};
export const fakeDocument = (options?: Options): Document => { const f = options?.faker ?? faker; return { id: f.database.mongodbObjectId(), _id: f.database.mongodbObjectId(), };};export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@faker-js/faker', nameRules: { string: { // compound rule: "message" inside an "error" schema 'error.message': { fakerPath: ['word', 'words'], defaultArgs: { count: 4 }, }, // suffix rule: any property ending with "id" id: { fakerPath: ['database', 'mongodbObjectId'], suffixMatch: true, }, }, }, }, ],};Each rule requires a fakerPath — a tuple of [module, method] corresponding to a faker method (e.g. ['database', 'mongodbObjectId'] for faker.database.mongodbObjectId()). You can optionally provide defaultArgs to pass default arguments to the faker method.
Matching strategies:
- Exact match —
'email'matches a property namedemail - Compound match —
'error.message'matches a property namedmessageinside an ancestor namederror - Suffix match —
'id'withsuffixMatch: truematches any property ending withid(e.g.userId,_id)
User-provided rules take priority over built-in rules. Property names are normalized (lowercased, separators removed) before matching.
Formats and Constraints
Section titled “Formats and Constraints”The plugin respects OpenAPI schema formats and constraints to generate appropriately bounded data.
String formats:
email→faker.internet.email()date-time→faker.date.recent().toISOString()date→faker.date.recent().toISOString().slice(0, 10)uuid→faker.string.uuid()uri/url→faker.internet.url()ipv4→faker.internet.ipv4()ipv6→faker.internet.ipv6()pattern→faker.helpers.fromRegExp(pattern)
Numeric constraints:
minimum/maximum→faker.number.int({ min, max })exclusiveMinimum/exclusiveMaximum→ adjusted bounds
String constraints:
minLength/maxLength→faker.string.alpha({ length: { min, max } })
Array constraints:
minItems/maxItems→ controls count infaker.helpers.multiple()
Optional Properties
Section titled “Optional Properties”Required properties are always included. Optional properties are controlled by the includeOptional option at runtime.
const user = fakeFoo(); // includes optional properties by defaultconst user = fakeFoo({ includeOptional: false }); // excludes optional propertiesconst user = fakeFoo({ includeOptional: 0.5 }); // 50% probability per optional propertyDefault Values
Section titled “Default Values”When a schema defines default values, you can control whether to use them instead of generating fake data via the useDefault option.
const data = fakeFoo(); // always generates fake dataconst data = fakeFoo({ useDefault: true }); // uses schema defaults when availableconst data = fakeFoo({ useDefault: 0.5 }); // 50% probability of using defaultsCircular References
Section titled “Circular References”Schemas with circular references are automatically detected, whether self-referencing (a schema that refers to itself) or mutually recursive (two or more schemas that refer to each other). The generated factories use a depth counter to prevent infinite recursion, returning empty arrays or omitting optional properties once the limit is reached.
The maximum depth defaults to 10 and can be configured via the maxCallDepth option.
Locale
Section titled “Locale”You can configure the locale for generated faker factories. When set, the generated code imports the faker instance from the locale-specific build of @faker-js/faker.
import { faker } from '@faker-js/faker/locale/de';import type { Faker } from '@faker-js/faker';export default { input: 'hey-api/backend', // sign up at app.heyapi.dev output: 'src/client', plugins: [ // ...other plugins { name: '@faker-js/faker', locale: 'de', }, ],};See the Faker localization guide for available locales.
Deterministic Results
Section titled “Deterministic Results”For snapshot testing or reproducible output, you can seed the faker instance and fix the reference date to ensure deterministic results.
import { faker } from '@faker-js/faker';
faker.seed(42);faker.setDefaultRefDate('2026-01-01T00:00:00.000Z');
const data = fakeFoo();// always returns the same outputCustom Faker Instance
Section titled “Custom Faker Instance”You can pass your own faker instance via the faker option for runtime locale switching or other customizations.
import { faker } from '@faker-js/faker/locale/de';
const data = fakeFoo({ faker });API
You can view the complete list of options in the UserConfig interface.
Examples
You can view live examples on StackBlitz or on GitHub.