-
-
Notifications
You must be signed in to change notification settings - Fork 664
feat(mock): add arrayItems faker option for reusable array item mocks #3514
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 13 commits into
orval-labs:master
from
Hypenate:feat/faker-array-item-factories
Jun 2, 2026
Merged
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
412ed5e
feat(mock): add arrayItems faker option for reusable array item mocks
Hypenate ad803fd
fix(mock): address PR review and lint failures for arrayItems
Hypenate 2fbccfe
fix(mock): use full ContextSpec in scalar tests for arrayItems guard
Hypenate 262227c
Merge branch 'master' into feat/faker-array-item-factories
Hypenate 80c1218
fix(core): consolidate schema type imports in single-mode mock output
Hypenate 66d53ff
chore(tests): update snapshots for consolidated single-mode imports
Hypenate 68a05c8
chore(tests): remove stale petstore-url-matchers snapshots
Hypenate fbdacb5
fix(mock): dedupe shared array-item factories across operations
Hypenate 65e3a3c
style(mock): use nullish coalescing for array-item factory set
Hypenate b9a14cd
fix(mock): scope array-item factory dedup per output file
Hypenate 9816c59
fix(mock): widen test helper mode param to OutputMode
Hypenate 64954f8
fix(mock): guard arrayItems extraction for edge-case item shapes
Hypenate f18b2bf
Merge branch 'feat/faker-array-item-factories' of https://github.com/…
Hypenate 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
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
160 changes: 160 additions & 0 deletions
160
packages/mock/src/faker/getters/array-item-factory.test.ts
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,160 @@ | ||
| import type { ContextSpec } from '@orval/core'; | ||
| import { describe, expect, it } from 'vitest'; | ||
|
|
||
| import { | ||
| extractArrayItemMock, | ||
| shouldExtractArrayItemFactories, | ||
| } from './array-item-factory'; | ||
|
|
||
| const contextWithArrayItems = { | ||
| output: { | ||
| mock: { | ||
| generators: [{ type: 'faker', arrayItems: true }], | ||
| }, | ||
| override: { | ||
| components: { schemas: { suffix: '', itemSuffix: 'Item' } }, | ||
| }, | ||
| }, | ||
| } as unknown as ContextSpec; | ||
|
|
||
| const contextWithoutArrayItems = { | ||
| output: { | ||
| mock: { | ||
| generators: [{ type: 'faker' }], | ||
| }, | ||
| override: { | ||
| components: { schemas: { suffix: '', itemSuffix: 'Item' } }, | ||
| }, | ||
| }, | ||
| } as unknown as ContextSpec; | ||
|
|
||
| describe('shouldExtractArrayItemFactories', () => { | ||
| it('returns true when arrayItems is enabled', () => { | ||
| expect(shouldExtractArrayItemFactories(contextWithArrayItems)).toBe(true); | ||
| }); | ||
|
|
||
| it('returns false when arrayItems is not enabled', () => { | ||
| expect(shouldExtractArrayItemFactories(contextWithoutArrayItems)).toBe( | ||
| false, | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('extractArrayItemMock', () => { | ||
| it('extracts a reusable factory for $ref array items', () => { | ||
| const splitMockImplementations: string[] = []; | ||
| const imports: Parameters<typeof extractArrayItemMock>[0]['imports'] = []; | ||
|
|
||
| const call = extractArrayItemMock({ | ||
| items: { $ref: '#/components/schemas/TenantResponseModelDto' }, | ||
| propertyName: 'value', | ||
| operationId: 'getTenantsByRef', | ||
| mapValue: | ||
| '{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 10, max: 20}})}', | ||
| context: contextWithArrayItems, | ||
| splitMockImplementations, | ||
| imports, | ||
| }); | ||
|
|
||
| expect(call).toBe('{...getTenantResponseModelDtoMock()}'); | ||
| expect(splitMockImplementations).toHaveLength(1); | ||
| expect(splitMockImplementations[0]).toContain( | ||
| 'export const getTenantResponseModelDtoMock', | ||
| ); | ||
| expect(splitMockImplementations[0]).toContain( | ||
| 'Partial<TenantResponseModelDto>', | ||
| ); | ||
| expect(imports).toEqual([{ name: 'TenantResponseModelDto' }]); | ||
| }); | ||
|
|
||
| it('extracts a reusable factory for inline object array items', () => { | ||
| const splitMockImplementations: string[] = []; | ||
|
|
||
| const call = extractArrayItemMock({ | ||
| items: { | ||
| type: 'object', | ||
| properties: { | ||
| id: { type: 'string' }, | ||
| name: { type: 'string' }, | ||
| }, | ||
| }, | ||
| propertyName: 'value', | ||
| parentName: 'GetTenants200', | ||
| operationId: 'getTenants', | ||
| mapValue: | ||
| '{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 10, max: 20}})}', | ||
| context: contextWithArrayItems, | ||
| splitMockImplementations, | ||
| imports: [], | ||
| }); | ||
|
|
||
| expect(call).toBe('{...getGetTenantsResponseValueItemMock()}'); | ||
| expect(splitMockImplementations[0]).toContain( | ||
| 'export const getGetTenantsResponseValueItemMock', | ||
| ); | ||
| expect(splitMockImplementations[0]).toContain( | ||
| 'Partial<GetTenants200ValueItem>', | ||
| ); | ||
| }); | ||
|
|
||
| it('deduplicates factories with the same name', () => { | ||
| const splitMockImplementations: string[] = []; | ||
| const mapValue = | ||
| '{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 10, max: 20}})}'; | ||
|
|
||
| extractArrayItemMock({ | ||
| items: { $ref: '#/components/schemas/TenantResponseModelDto' }, | ||
| propertyName: 'value', | ||
| operationId: 'getTenantsByRef', | ||
| mapValue, | ||
| context: contextWithArrayItems, | ||
| splitMockImplementations, | ||
| imports: [], | ||
| }); | ||
| extractArrayItemMock({ | ||
| items: { $ref: '#/components/schemas/TenantResponseModelDto' }, | ||
| propertyName: 'items', | ||
| operationId: 'getTenantsByRef', | ||
| mapValue, | ||
| context: contextWithArrayItems, | ||
| splitMockImplementations, | ||
| imports: [], | ||
| }); | ||
|
|
||
| expect(splitMockImplementations).toHaveLength(1); | ||
| }); | ||
|
|
||
| it('skips primitive array items', () => { | ||
| const splitMockImplementations: string[] = []; | ||
|
|
||
| const call = extractArrayItemMock({ | ||
| items: { type: 'string' }, | ||
| propertyName: 'tags', | ||
| operationId: 'getTenants', | ||
| mapValue: 'faker.string.alpha({length: {min: 10, max: 20}})', | ||
| context: contextWithArrayItems, | ||
| splitMockImplementations, | ||
| imports: [], | ||
| }); | ||
|
|
||
| expect(call).toBeUndefined(); | ||
| expect(splitMockImplementations).toHaveLength(0); | ||
| }); | ||
|
|
||
| it('skips when the value already delegates to a factory', () => { | ||
| const splitMockImplementations: string[] = []; | ||
|
|
||
| const call = extractArrayItemMock({ | ||
| items: { $ref: '#/components/schemas/TenantResponseModelDto' }, | ||
| propertyName: 'value', | ||
| operationId: 'getTenantsByRef', | ||
| mapValue: '{...getTenantResponseModelDtoMock()}', | ||
| context: contextWithArrayItems, | ||
| splitMockImplementations, | ||
| imports: [], | ||
| }); | ||
|
|
||
| expect(call).toBeUndefined(); | ||
| expect(splitMockImplementations).toHaveLength(0); | ||
| }); | ||
| }); |
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,160 @@ | ||
| import { | ||
| type ContextSpec, | ||
| type GeneratorImport, | ||
| getRefInfo, | ||
| isFunction, | ||
| isReference, | ||
| type OpenApiSchemaObject, | ||
| OutputMockType, | ||
| pascal, | ||
| } from '@orval/core'; | ||
|
|
||
| import type { MockSchema } from '../../types'; | ||
| import { overrideVarName } from './object'; | ||
| import { extractItemsRef } from './scalar'; | ||
|
|
||
| /** | ||
| * True when the active faker generator entry opts into reusable array-item | ||
| * mock factories for object-like array item schemas in operation responses. | ||
| */ | ||
| export function shouldExtractArrayItemFactories(context: ContextSpec): boolean { | ||
| const generators = context.output.mock?.generators; | ||
| if (!generators) { | ||
| return false; | ||
| } | ||
|
|
||
| const fakerEntry = generators.find( | ||
| (g) => | ||
| !isFunction(g) && | ||
| g.type === OutputMockType.FAKER && | ||
| g.arrayItems === true, | ||
| ); | ||
| return !!fakerEntry; | ||
| } | ||
|
|
||
| function isObjectLikeArrayItem(items: MockSchema): boolean { | ||
| if (isReference(items)) { | ||
| return true; | ||
| } | ||
|
|
||
| const schema = items as OpenApiSchemaObject; | ||
| if (schema.type === 'object' || schema.properties) { | ||
| return true; | ||
| } | ||
|
|
||
| if (schema.allOf || schema.oneOf || schema.anyOf) { | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| function isAlreadyFactoryCall(mapValue: string): boolean { | ||
| return /\bget\w+Mock\(\)/.test(mapValue); | ||
| } | ||
|
|
||
| interface ArrayItemFactoryNames { | ||
| factoryName: string; | ||
| typeName: string; | ||
| } | ||
|
|
||
| function getArrayItemFactoryNames({ | ||
| items, | ||
| propertyName, | ||
| parentName, | ||
| operationId, | ||
| context, | ||
| }: { | ||
| items: MockSchema; | ||
| propertyName: string; | ||
| parentName?: string; | ||
| operationId: string; | ||
| context: ContextSpec; | ||
| }): ArrayItemFactoryNames | undefined { | ||
| const itemsRef = extractItemsRef(items); | ||
| if (itemsRef) { | ||
| const { name } = getRefInfo(itemsRef, context); | ||
| const typeName = pascal(name); | ||
| return { | ||
| factoryName: `get${typeName}Mock`, | ||
| typeName, | ||
| }; | ||
| } | ||
|
|
||
| if (!isObjectLikeArrayItem(items)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const itemSuffix = context.output.override.components.schemas.itemSuffix; | ||
| const typeName = parentName | ||
| ? `${pascal(parentName)}${pascal(propertyName)}${itemSuffix}` | ||
| : `${pascal(operationId)}${pascal(propertyName)}${itemSuffix}`; | ||
| return { | ||
| factoryName: `get${pascal(operationId)}Response${pascal(propertyName)}ItemMock`, | ||
| typeName, | ||
| }; | ||
| } | ||
|
|
||
| interface ExtractArrayItemMockOptions { | ||
| items: MockSchema; | ||
| propertyName: string; | ||
| parentName?: string; | ||
| operationId: string; | ||
| mapValue: string; | ||
| context: ContextSpec; | ||
| splitMockImplementations: string[]; | ||
| imports: GeneratorImport[]; | ||
| } | ||
|
|
||
| /** | ||
| * When `arrayItems: true`, lift an object-like array item mock body into a | ||
| * reusable exported factory and return the call site expression for `.map()`. | ||
| */ | ||
| export function extractArrayItemMock({ | ||
| items, | ||
| propertyName, | ||
| parentName, | ||
| operationId, | ||
| mapValue, | ||
| context, | ||
| splitMockImplementations, | ||
| imports, | ||
| }: ExtractArrayItemMockOptions): string | undefined { | ||
| if (!shouldExtractArrayItemFactories(context)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| if (!mapValue || mapValue === '[]' || isAlreadyFactoryCall(mapValue)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const names = getArrayItemFactoryNames({ | ||
| items, | ||
| propertyName, | ||
| parentName, | ||
| operationId, | ||
| context, | ||
| }); | ||
| if (!names) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const { factoryName, typeName } = names; | ||
|
|
||
| if ( | ||
| !splitMockImplementations.some((f) => | ||
| f.includes(`export const ${factoryName}`), | ||
| ) | ||
| ) { | ||
| const args = `${overrideVarName}: Partial<${typeName}> = {}`; | ||
| const spreadPrefix = mapValue.startsWith('...') ? '' : '...'; | ||
| const func = | ||
| `export const ${factoryName} = (${args}): ${typeName} => ` + | ||
| `({${spreadPrefix}${mapValue}, ...${overrideVarName}});`; | ||
| splitMockImplementations.push(func); | ||
| } | ||
|
|
||
| imports.push({ name: typeName }); | ||
|
|
||
| return `{...${factoryName}()}`; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
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
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.