Skip to content

Commit

Permalink
feat(helpers): add support and tests for complex intermediate return …
Browse files Browse the repository at this point in the history
…types in fake method
  • Loading branch information
Alexander committed Sep 10, 2023
1 parent c158b38 commit bc9e533
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,7 @@ export class HelpersModule {

// split the method into module and function
const parts = method.split('.');
const property = parts.length === 3 ? parts.pop() : undefined;

let currentModuleOrMethod: unknown = this.faker;
let currentDefinitions: unknown = this.faker.rawDefinitions;
Expand Down Expand Up @@ -1231,7 +1232,11 @@ export class HelpersModule {
params = [parameters];
}

const result = String(fn(...params));
const fnResult = fn(...params);
const result =
typeof fnResult === 'object' && property
? String(fnResult[property as keyof typeof fnResult])
: String(fnResult);

// Replace the found tag with the returned fake value
// We cannot use string.replace here because the result might contain evaluated characters
Expand Down
23 changes: 23 additions & 0 deletions test/modules/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,29 @@ describe('helpers', () => {
it('should not trim whitespace', () => {
expect(faker.helpers.fake(' --- ')).toBe(' --- ');
});

it('should be able to handle methods that return a complex object', () => {
expect(
faker.definitions.airline.airport.map((airport) => airport.iataCode)
).toContain(faker.helpers.fake('{{airline.airport.iataCode}}'));
});

it('should return undefined if a method returns a complex object but the property is undefined', () => {
expect(faker.helpers.fake('{{airline.airport.code}}')).toBe(
'undefined'
);
});

it('should be able to pass multiple dynamic templates with complex objects', () => {
expect(
faker.definitions.airline.airplane.map((airplane) => airplane.name)
).toContain(
faker.helpers.fake([
'{{airline.airplane.name}}',
'{{airline.airplane.name}}',
])
);
});
});

describe('rangeToNumber()', () => {
Expand Down

0 comments on commit bc9e533

Please sign in to comment.