Skip to content

Commit

Permalink
feat(msw): possible to overwrite value when creating an object with…
Browse files Browse the repository at this point in the history
… `msw` mock (#1165)

* feat: possible to overwrite value when creating an `object` with `msw` mock

* chore: changed determination of orverridability

* chore: refactoring to make override var name common
  • Loading branch information
soartec-lab authored Jan 27, 2024
1 parent 02161de commit c7ccb65
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
13 changes: 10 additions & 3 deletions packages/mock/src/faker/getters/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { MockDefinition, MockSchemaObject } from '../../types';
import { combineSchemasMock } from './combine';
import { DEFAULT_OBJECT_KEY_MOCK } from '../constants';

export const overrideVarName = 'overrideResponse';

export const getMockObject = ({
item,
mockOptions,
Expand Down Expand Up @@ -77,7 +79,8 @@ export const getMockObject = ({
: '';
let imports: GeneratorImport[] = [];
let includedProperties: string[] = [];
value += Object.entries(item.properties)

const properyScalars = Object.entries(item.properties)
.sort((a, b) => {
return a[0].localeCompare(b[0]);
})
Expand Down Expand Up @@ -123,14 +126,18 @@ export const getMockObject = ({

return `${keyDefinition}: ${resolvedValue.value}`;
})
.filter(Boolean)
.join(', ');
.filter(Boolean);

properyScalars.push(`...${overrideVarName}`);

value += properyScalars.join(', ');
value +=
!combine ||
combine?.separator === 'oneOf' ||
combine?.separator === 'anyOf'
? '}'
: '';

return {
value,
imports,
Expand Down
6 changes: 4 additions & 2 deletions packages/mock/src/msw/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
isFunction,
pascal,
} from '@orval/core';
import { getRouteMSW } from '../faker/getters';
import { getRouteMSW, overrideVarName } from '../faker/getters';
import { getMockDefinition, getMockOptionsDataOverride } from './mocks';
import { getDelay } from '../delay';

Expand Down Expand Up @@ -72,6 +72,8 @@ export const generateMSW = (
value = definitions[0];
}

const isResponseOverridable = value.includes(overrideVarName);

const isTextPlain = response.contentTypes.includes('text/plain');

const functionName = `get${pascal(operationId)}Mock`;
Expand Down Expand Up @@ -102,7 +104,7 @@ export const ${handlerName} = http.${verb}('${route}', async () => {
implementation: {
function:
value && value !== 'undefined'
? `export const ${functionName} = () => (${value})\n\n`
? `export const ${functionName} = (${isResponseOverridable ? `overrideResponse?: any` : ''}) => (${value})\n\n`
: '',
handlerName: handlerName,
handler: handlerImplementation,
Expand Down

0 comments on commit c7ccb65

Please sign in to comment.