Skip to content

fix(mock): emit boolean enum literals instead of random datatype.boolean() - #3428

Merged
melloware merged 1 commit into
orval-labs:masterfrom
wadakatu:test/issue-1775-allof-oneof-boolean-literal
May 23, 2026
Merged

fix(mock): emit boolean enum literals instead of random datatype.boolean()#3428
melloware merged 1 commit into
orval-labs:masterfrom
wadakatu:test/issue-1775-allof-oneof-boolean-literal

Conversation

@wadakatu

@wadakatu wadakatu commented May 23, 2026

Copy link
Copy Markdown
Contributor

The MSW mock generator's boolean branch in packages/mock/src/faker/getters/scalar.ts ignored item.enum and unconditionally emitted faker.datatype.boolean(). For a schema shaped like

allOf:
  - type: object
    properties:
      orderId: { type: string }
  - oneOf:
      - type: object
        properties:
          success: { type: boolean, enum: [true] }
      - type: object
        properties:
          success: { type: boolean, enum: [false] }
          failReason: { type: string }

the generated mock picked a oneOf branch with faker.helpers.arrayElement and then set success to a random boolean inside that branch — so the value no longer matched the discriminated-union literal (success: true / success: false) its branch enforced.

Routing boolean through the same getEnum helper as number / string produces

{ success: faker.helpers.arrayElement([true] as const) }
{ success: faker.helpers.arrayElement([false] as const), failReason: ... }

so each branch's success stays pinned to its literal regardless of which one arrayElement selects.

Notes

  • The type-generation half of MSW: Generates Incorrect Schema with MSW + Faker #1775 (success: boolean instead of success: false) was already addressed by fix(core): boolean discriminated unions generate literal true/false instead of boolean #3159's boolean-enum branch in packages/core/src/getters/scalar.ts. The original report's third symptom — { … }, { … } bare object literals in the mock body — was likewise fixed in the meantime by combine.ts's spread handling. This PR closes the remaining mock-side gap.
  • Only one existing snapshot moved (tests/__snapshots__/default/nullable-oneof-enums/endpoints.ts):
    • enum: [true, false]arrayElement([true, false] as const) (cosmetic; semantically identical to faker.datatype.boolean()).
    • enum: [true]arrayElement([true] as const) (real fix; previously emitted a random boolean despite the single-value enum).
  • Adds tests/specifications/issue-1775.yaml + a focused test() in tests/api-generation.spec.ts that fails with a targeted message on regression rather than via a full-file snapshot diff (matching the style of the recent issue-1879 / issue-1935 regression tests).

Closes #1775

Summary by CodeRabbit

  • Bug Fixes

    • Improved mock data generation to properly support boolean enums in complex schema patterns.
  • Tests

    • Added regression test to ensure boolean enum values are correctly preserved in generated mock responses.

Review Change Stack

…ean()

The MSW mock generator's boolean branch in scalar.ts ignored `item.enum`
and unconditionally emitted `faker.datatype.boolean()`. For schemas like
`oneOf [{ success: enum [true] }, { success: enum [false], failReason }]`
this broke the discriminator: the randomly-picked union variant set
`success` to a random boolean, so the mock no longer matched the
TypeScript literal type its branch enforced (`success: true` /
`success: false`).

Route boolean through the same `getEnum` helper as number/string so
`enum: [true]` emits `faker.helpers.arrayElement([true] as const)` and
`enum: [false]` likewise, keeping the mock value pinned to the chosen
branch's literal.

The type-generation half of orval-labs#1775 was already addressed by orval-labs#3159's
boolean-enum branch in `packages/core/src/getters/scalar.ts`; this
change closes the mock-side gap and adds a focused regression covering
the exact orval-labs#1775 shape.

Closes orval-labs#1775
Copilot AI review requested due to automatic review settings May 23, 2026 11:18
@coderabbitai

coderabbitai Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b3b397ff-4b09-4b2c-a87d-2e02e01bbe48

📥 Commits

Reviewing files that changed from the base of the PR and between 8f4ae4a and 4b36486.

📒 Files selected for processing (8)
  • packages/mock/src/faker/getters/scalar.ts
  • tests/__snapshots__/default/issue-1775/endpoints.ts
  • tests/__snapshots__/default/issue-1775/model/index.ts
  • tests/__snapshots__/default/issue-1775/model/putApiOrderLimit200Item.ts
  • tests/__snapshots__/default/nullable-oneof-enums/endpoints.ts
  • tests/api-generation.spec.ts
  • tests/configs/default.config.ts
  • tests/specifications/issue-1775.yaml

📝 Walkthrough

Walkthrough

This PR fixes boolean enum mock generation in MSW. The scalar Faker getter now detects and emits boolean enums via the widened getEnum helper, preserving literal true/false values in discriminated unions. The fix is validated through a new regression test case (issue-1775) and applied consistently across existing mock snapshots.

Changes

Boolean Enum Discriminator Fix

Layer / File(s) Summary
Boolean enum support in scalar getter
packages/mock/src/faker/getters/scalar.ts
Extended getMockScalar boolean branch to handle item.enum via getEnum, building dedicated imports and returning enums + imports fields. Widened getEnum type parameter to accept 'boolean'.
Test specification and configuration
tests/specifications/issue-1775.yaml, tests/configs/default.config.ts
Added OpenAPI spec for batch-result endpoint with discriminated union items (orderId combined with success: true or success: false + failReason), and Orval config targeting model and endpoints generation.
Generated type model for issue-1775
tests/__snapshots__/default/issue-1775/model/putApiOrderLimit200Item.ts, tests/__snapshots__/default/issue-1775/model/index.ts
Auto-generated PutApiOrderLimit200Item type as intersection of { orderId: string } with `{ success: true }
Generated MSW/axios endpoints for issue-1775
tests/__snapshots__/default/issue-1775/endpoints.ts
Auto-generated axios putApiOrderLimit wrapper, mock response builder using Faker for discriminated union fields, MSW http.put handler with optional override support, and aggregator function.
Boolean mock generation consistency updates
tests/__snapshots__/default/nullable-oneof-enums/endpoints.ts
Updated boolean mock expressions in nested arrays to use faker.helpers.arrayElement([true, false] as const) instead of faker.datatype.boolean(), ensuring deterministic literal-enum-compatible values.
Regression test for boolean enum discriminators
tests/api-generation.spec.ts
New Vitest case asserting boolean enum literals (success: true/false) are preserved in generated types and mocks use const-pinned arrayElement selections rather than random boolean generation.

Sequence Diagram

sequenceDiagram
  participant getMockScalar
  participant getEnum
  participant Faker
  participant MSWHandler
  participant TypeOutput
  
  getMockScalar->>getMockScalar: Detect item.enum on boolean
  getMockScalar->>getEnum: Call with type='boolean'
  getEnum->>getEnum: Generate enum import expression
  getEnum-->>getMockScalar: Return enum import list
  getMockScalar-->>TypeOutput: Return enums + imports
  
  MSWHandler->>Faker: faker.helpers.arrayElement
  Faker-->>MSWHandler: Select [true, false] as const
  MSWHandler-->>MSWHandler: Preserve literal boolean in mock
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related issues

  • #3223: Both touch boolean-enum import logic in scalar.ts; this PR extends getEnum to handle 'boolean' type, directly addressing enum import/type handling bugs.
  • #3151: This PR fixes scalar.ts boolean-enum handling by widening getEnum to accept 'boolean', matching root causes cited in the retrieved issue.

Possibly related PRs

  • orval-labs/orval#3159: Both PRs update boolean enum/discriminator generation to produce literal true/false enum types rather than plain boolean.
  • orval-labs/orval#3224: Both PRs adjust the enum-mock generation pipeline around getMockScalar and getEnum to properly handle boolean enum emission and typing.

Suggested labels

mock, msw, bug

Suggested reviewers

  • melloware

Poem

🐰 A boolean once random and wild,
Now wears enum clothes, carefully styled,
With true and false as const arrays bright,
MSW mocks now discriminate right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main fix: emitting boolean enum literals instead of random datatype.boolean() calls in mock generation.
Linked Issues check ✅ Passed The PR directly addresses issue #1775 by updating the getMockScalar boolean branch to emit faker.helpers.arrayElement() for boolean enums instead of random faker.datatype.boolean() calls, matching the discriminated union literals.
Out of Scope Changes check ✅ Passed All changes are in-scope: the core fix in packages/mock/src/faker/getters/scalar.ts, related snapshot updates, a regression test (issue-1775), test configuration, and OpenAPI specification are all directly tied to fixing boolean enum literal handling.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds a regression test + fixtures for issue-1775 and updates the mock faker scalar generation so boolean enum values are preserved (rather than random booleans), including for allOf + oneOf compositions.

Changes:

  • Introduces a new OpenAPI spec fixture for issue-1775 and wires it into the default test config.
  • Adds a generation test asserting boolean enum literal preservation in both models and mocks.
  • Updates mock scalar generation to route boolean enums through getEnum, updating snapshots accordingly.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/specifications/issue-1775.yaml Adds a spec reproducing the allOf + oneOf boolean-enum case.
tests/configs/default.config.ts Registers the new issue-1775 fixture for generation.
tests/api-generation.spec.ts Adds a regression test asserting model + mock output for issue-1775.
tests/snapshots/default/nullable-oneof-enums/endpoints.ts Updates snapshot reflecting boolean enums generated via arrayElement([...]).
tests/snapshots/default/issue-1775/model/putApiOrderLimit200Item.ts Adds snapshot for the generated model type for issue-1775.
tests/snapshots/default/issue-1775/model/index.ts Adds snapshot index for the new model folder.
tests/snapshots/default/issue-1775/endpoints.ts Adds snapshot for generated endpoint + mock handler for issue-1775.
packages/mock/src/faker/getters/scalar.ts Changes boolean scalar mock generation to honor enum via getEnum.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 241 to 261
case 'boolean': {
let value = 'faker.datatype.boolean()';
if ('const' in item) {
const booleanImports: GeneratorImport[] = [];
if (item.enum) {
value = getEnum(
item,
booleanImports,
context,
existingReferencedProperties,
'boolean',
);
} else if ('const' in item) {
value = JSON.stringify(item.const);
}
return {
value,
imports: [],
enums: item.enum,
imports: booleanImports,
name: item.name,
};
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This boolean branch deliberately mirrors the sibling number/integer (L221) and string (L362) cases, which also check item.enum before 'const' in item. So in the (very unusual) shape enum + const together, all primitive types behave the same way today — the change here doesn't introduce asymmetry, it preserves it.

If const should take precedence, that's a repo-wide invariant that belongs in a dedicated PR touching all three primitive branches at once (with snapshot churn across many specs), not a one-off flip on the boolean case. Marking out of scope for #1775 — keeping consistency with the established pattern.

let value = 'faker.datatype.boolean()';
if ('const' in item) {
const booleanImports: GeneratorImport[] = [];
if (item.enum) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sibling number/integer (L221) and string (L362) branches both use the same if (item.enum) truthiness check (not item.enum?.length), and getEnum itself has if (!item.enum) return '' rather than a length guard. So an enum: [] would degrade identically across all primitives today — boolean isn't a new outlier. (enum: [] is also a malformed schema that the OpenAPI validator should reject before reaching this getter.)

If empty-enum handling should fall back to the default generator, that belongs in getEnum (or as a coordinated change across all primitive branches), not as a one-off boolean tweak. Keeping the boolean branch symmetric with its siblings for #1775's scope.

@melloware melloware added mock Related to mock generation msw MSW related issues labels May 23, 2026
@melloware
melloware merged commit f95377d into orval-labs:master May 23, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mock Related to mock generation msw MSW related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MSW: Generates Incorrect Schema with MSW + Faker

3 participants