-
-
Notifications
You must be signed in to change notification settings - Fork 664
feat(mock): add faker schema mock generation #3426
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
melloware
merged 7 commits into
orval-labs:master
from
jakiestfu:feat/faker-schema-mocks
May 23, 2026
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1bdbf51
feat(mock): add faker schema mock generation
jakiestfu 0e02d4f
fix(orval): narrow fakerEntry to FakerMockOptions for typecheck
jakiestfu 19a78fe
feat(mock): delegate operation responses to schema faker factories
jakiestfu 26ce0ee
test: snapshotzzz
jakiestfu 5eb8c32
fix(mock): emit value imports for runtime-used schemas in index.faker.ts
jakiestfu 0801597
test: snapshots
jakiestfu 4177de8
fix(mock): address CodeRabbit feedback on faker schemas PR
jakiestfu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,207 @@ | ||
| --- | ||
| title: Faker | ||
| description: Generate mock data factories with Faker.js from OpenAPI | ||
| --- | ||
|
|
||
| Generate mock data factories powered by [Faker.js](https://fakerjs.dev/) from your OpenAPI specification. Faker output has no `msw` dependency, so it's useful for unit tests, Storybook stories, seed scripts, and any test setup that doesn't go through a network mock. | ||
|
|
||
| For Mock Service Worker request handlers, see the [MSW guide](/docs/guides/msw). | ||
|
|
||
| ## Configuration | ||
|
|
||
| Add a `faker` generator entry to `output.mock.generators`: | ||
|
|
||
| ```ts title="orval.config.ts" | ||
| import { defineConfig } from 'orval'; | ||
|
|
||
| export default defineConfig({ | ||
| petstore: { | ||
| output: { | ||
| mode: 'single', | ||
| target: './src/api/petstore.ts', | ||
| schemas: './src/api/model', | ||
| mock: { | ||
| generators: [{ type: 'faker' }], | ||
| }, | ||
| }, | ||
| input: { | ||
| target: './petstore.yaml', | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| You can also combine `msw` and `faker` to emit both files in the same run: | ||
|
|
||
| ```ts | ||
| mock: { | ||
| generators: [{ type: 'msw' }, { type: 'faker' }], | ||
| } | ||
| ``` | ||
|
|
||
| The Faker output is written to `<filename>.faker.ts` and only depends on `@faker-js/faker`. | ||
|
|
||
| ## Generated Output | ||
|
|
||
| ### Response Factories | ||
|
|
||
| For each operation, Orval emits a `get<OperationId>ResponseMock` factory that returns a fully-populated response value: | ||
|
|
||
| ```ts | ||
| import { faker } from '@faker-js/faker'; | ||
|
|
||
| export const getShowPetByIdResponseMock = ( | ||
| overrideResponse: Partial<Pet> = {}, | ||
| ): Pet => ({ | ||
| id: faker.number.int({ min: undefined, max: undefined }), | ||
| name: faker.string.alpha(20), | ||
| tag: faker.string.alpha(20), | ||
| ...overrideResponse, | ||
| }); | ||
| ``` | ||
|
|
||
| Pass overrides for any subset of fields: | ||
|
|
||
| ```ts | ||
| const pet = getShowPetByIdResponseMock({ name: 'Buddy' }); | ||
| // => { id: 7272122785202176, name: "Buddy", tag: "..." } | ||
| ``` | ||
|
|
||
| ## Options | ||
|
|
||
| Set faker-specific options on the generator entry: | ||
|
|
||
| ```ts title="orval.config.ts" | ||
| mock: { | ||
| generators: [ | ||
| { | ||
| type: 'faker', | ||
| useExamples: true, | ||
| generateEachHttpStatus: true, | ||
| locale: 'en_GB', | ||
| preferredContentType: 'application/json', | ||
| }, | ||
| ], | ||
| } | ||
| ``` | ||
|
|
||
| | Option | Type | Default | Description | | ||
| |---|---|---|---| | ||
| | `useExamples` | `boolean` | `false` | Seed mock values from OpenAPI `example`/`examples` fields when present. | | ||
| | `generateEachHttpStatus` | `boolean` | `false` | Emit a separate factory per HTTP status code defined in the spec (not just the success response). | | ||
| | `locale` | `keyof typeof allLocales` | — | Faker locale. Switches the import to `@faker-js/faker/locale/<x>` (e.g. `'en_GB'`, `'fr'`, `'ja'`). | | ||
| | `preferredContentType` | `string` | — | When an operation has multiple response content types, mock the one matching this MIME type. | | ||
|
|
||
| ## Customizing Mock Values | ||
|
|
||
| Use `override.mock` to control how individual schemas, properties, and formats are mocked. These options apply to both `faker` and `msw` generators. | ||
|
|
||
| ```ts title="orval.config.ts" | ||
| override: { | ||
| mock: { | ||
| properties: { | ||
| // Match by property name (string or regex) | ||
| email: () => faker.internet.email(), | ||
| '/.*Id$/': () => faker.string.uuid(), | ||
| }, | ||
| format: { | ||
| // Match by OpenAPI `format` keyword | ||
| date: () => faker.date.past().toISOString(), | ||
| 'date-time': () => faker.date.recent().toISOString(), | ||
| }, | ||
| required: true, // Always populate optional fields | ||
| arrayMin: 3, | ||
| arrayMax: 5, | ||
| stringMin: 4, | ||
| stringMax: 20, | ||
| numberMin: 0, | ||
| numberMax: 100, | ||
| fractionDigits: 2, | ||
| }, | ||
| } | ||
| ``` | ||
|
|
||
| You can also scope overrides per-operation or per-tag via `override.operations` and `override.tags`. | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Unit Tests | ||
|
|
||
| ```ts | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { getShowPetByIdResponseMock } from './api/petstore.faker'; | ||
|
|
||
| describe('PetDetails', () => { | ||
| it('renders the pet name', () => { | ||
| const pet = getShowPetByIdResponseMock({ name: 'Buddy' }); | ||
| render(<PetDetails pet={pet} />); | ||
| expect(screen.getByText('Buddy')).toBeInTheDocument(); | ||
| }); | ||
| }); | ||
| ``` | ||
|
|
||
| ### Storybook | ||
|
|
||
| ```ts | ||
| import type { Meta, StoryObj } from '@storybook/react'; | ||
| import { getShowPetByIdResponseMock } from '../api/petstore.faker'; | ||
| import { PetDetails } from './PetDetails'; | ||
|
|
||
| const meta: Meta<typeof PetDetails> = { | ||
| component: PetDetails, | ||
| }; | ||
| export default meta; | ||
|
|
||
| export const Default: StoryObj<typeof PetDetails> = { | ||
| args: { pet: getShowPetByIdResponseMock() }, | ||
| }; | ||
|
|
||
| export const NamedPet: StoryObj<typeof PetDetails> = { | ||
| args: { pet: getShowPetByIdResponseMock({ name: 'Buddy' }) }, | ||
| }; | ||
| ``` | ||
|
|
||
| ### Seed Scripts | ||
|
|
||
| ```ts | ||
| import { writeFile } from 'node:fs/promises'; | ||
| import { getListPetsResponseMock } from './api/petstore.faker'; | ||
|
|
||
| const seed = Array.from({ length: 50 }, () => getListPetsResponseMock()); | ||
| await writeFile('seed/pets.json', JSON.stringify(seed, null, 2)); | ||
| ``` | ||
|
|
||
| ## Deterministic Output | ||
|
|
||
| Faker's PRNG is seedable. Set a seed before invoking factories to get reproducible output, which is helpful for snapshot testing: | ||
|
|
||
| ```ts | ||
| import { faker } from '@faker-js/faker'; | ||
| import { getShowPetByIdResponseMock } from './api/petstore.faker'; | ||
|
|
||
| beforeEach(() => { | ||
| faker.seed(42); | ||
| }); | ||
|
|
||
| it('matches snapshot', () => { | ||
| expect(getShowPetByIdResponseMock()).toMatchSnapshot(); | ||
| }); | ||
| ``` | ||
|
|
||
| ## Dynamic Imports | ||
|
|
||
| In `tags-split` mode, enable `mock.indexMockFiles` to emit an `index.faker.ts` aggregating all per-tag faker files: | ||
|
|
||
| ```ts title="orval.config.ts" | ||
| export default defineConfig({ | ||
| petstore: { | ||
| output: { | ||
| mode: 'tags-split', | ||
| mock: { | ||
| indexMockFiles: true, | ||
| generators: [{ type: 'faker' }], | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,6 +23,7 @@ | |
| "zod", | ||
| "client-with-zod", | ||
| "msw", | ||
| "faker", | ||
| "---Advanced---", | ||
| "enums", | ||
| "stream-ndjson", | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export * from './file'; | ||
| export * from './schemas'; | ||
| export * from './single-mode'; | ||
| export * from './split-mode'; | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.