Skip to content

Commit

Permalink
fix(generator): do not use example values if the useExampleValues opt…
Browse files Browse the repository at this point in the history
…ion is set to false
  • Loading branch information
aleksandryackovlev committed Mar 10, 2024
1 parent b769694 commit 953af41
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/utils/generator.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import jsf, { JSF, JSFOptions } from 'json-schema-faker';
import { cloneDeep } from 'lodash';

export { JSONSchema, JSFOptions, JSF } from 'json-schema-faker';

export type JSFCallback = (jsfInstance: JSF) => void;

const defaultOptions = {
optionalsProbability: 0.5,
useExamplesValue: true,
};

/* eslint-disable @typescript-eslint/no-explicit-any */
Expand All @@ -24,19 +26,21 @@ export const createGenerator: (options?: Partial<JSFOptions>, callback?: JSFCall
options = defaultOptions,
callback = <JSFCallback>(() => {})
) => {
jsf.option({
const applyedOptions = {
...defaultOptions,
...options,
});
};

jsf.define('example', (value) => {
return value;
});
const generator = cloneDeep(jsf);
generator.option(applyedOptions);

jsf.define('examples', handleExamples);
if (applyedOptions.useExamplesValue) {
generator.define('example', (value: any) => value);
generator.define('examples', handleExamples);
}

callback(jsf);
callback(generator);

return jsf;
return generator;
};
/* eslint-enable @typescript-eslint/no-empty-function */
18 changes: 18 additions & 0 deletions test/helpers/app-no-examples.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import path from 'path';

import express from 'express';

import { createMockMiddleware } from '../../src';

const app = express();

const middleware = createMockMiddleware({
spec: path.resolve(__dirname, '../fixtures/petstore.yaml'),
options: {
useExamplesValue: false,
},
});

app.use('/api', middleware);

export default app;
18 changes: 18 additions & 0 deletions test/integration-no-example.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import supertest from 'supertest';

import app from './helpers/app-no-examples';

const request = supertest(app);

describe('middleware', () => {
it('should not use example values if useExamplesValue is set to false', async () => {
const response = await request.get('/api/pet/2').set('api_key', 'someKey');

expect(response.status).toBe(200);
expect(response.body).not.toHaveProperty('name', 'doggie');
expect(response.body).not.toHaveProperty('photoUrls', [
'http://test.test',
'http://test1.test1',
]);
});
});

0 comments on commit 953af41

Please sign in to comment.