Skip to content

Commit

Permalink
fix(msw): correctly generate integer enum mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Alfred Jonsson committed Jun 5, 2024
1 parent 4c9ed3e commit d8df191
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions packages/mock/src/faker/getters/scalar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,37 @@ export const getMockScalar = ({
switch (item.type) {
case 'number':
case 'integer': {
let value = getNullable(
`faker.number.int({min: ${item.minimum}, max: ${item.maximum}})`,
item.nullable,
);
if (item.enum) {
// By default the value isn't a reference, so we don't have the object explicitly defined.
// So we have to create an array with the enum values and force them to be a const.
const joindEnumValues = item.enum.filter(Boolean).join(',');

let enumValue = `[${joindEnumValues}] as const`;

// But if the value is a reference, we can use the object directly via the imports and using Object.values.
if (item.isRef) {
enumValue = `Object.values(${item.name})`;
imports = [
{
name: item.name,
values: true,
...(!isRootKey(context.specKey, context.target)
? { specKey: context.specKey }
: {}),
},
];
}

value = item.path?.endsWith('[]')
? `faker.helpers.arrayElements(${enumValue})`
: `faker.helpers.arrayElement(${enumValue})`;
}
return {
value: getNullable(
`faker.number.int({min: ${item.minimum}, max: ${item.maximum}})`,
item.nullable,
),
value,
imports: [],
name: item.name,
};
Expand Down

0 comments on commit d8df191

Please sign in to comment.