Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/modules/helpers/eval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,15 +217,41 @@ function resolveProperty(entrypoint: unknown, key: string): unknown {
return undefined;
}

return entrypoint?.[key as keyof typeof entrypoint];
return getProperty(entrypoint, key);
}

case 'object': {
return entrypoint?.[key as keyof typeof entrypoint];
return getProperty(entrypoint, key);
}

case 'bigint':
case 'boolean':
case 'number':
case 'string': {
return getProperty(entrypoint, key);
}

default: {
return undefined;
}
}
}

type Callable = (this: unknown, ...args: unknown[]) => unknown;

/**
* Resolves the given property and binds methods to their source value.
*
* @param entrypoint The entrypoint to resolve the property on.
* @param key The property name to resolve.
*/
function getProperty(entrypoint: unknown, key: string): unknown {
if (entrypoint == null) {
return undefined;
}

const value = (new Object(entrypoint) as Record<string, unknown>)[key];
return typeof value === 'function'
? (value as Callable).bind(entrypoint)
: value;
}
11 changes: 11 additions & 0 deletions test/modules/helpers-eval.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,17 @@ describe('fakeEval()', () => {
).toContain(actual);
});

it('supports prototype methods after generated primitive values', () => {
const entrypoint = { value: () => 1234 };

expect(fakeEval('value.toPrecision(3)', faker, [entrypoint])).toBe(
'1.23e+3'
);
expect(fakeEval('value().toPrecision(3)', faker, [entrypoint])).toBe(
'1.23e+3'
);
});

it('requires a dot after a function call', () => {
expect(() => fakeEval('airline.airline()iataCode', faker)).toThrow(
new FakerError(
Expand Down
4 changes: 4 additions & 0 deletions test/modules/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,10 @@ describe('helpers', () => {
expect(faker.helpers.fake('{{string.alphanumeric(0)}}')).toBe('');
});

it('should resolve properties after generated primitive values', () => {
expect(faker.helpers.fake('{{string.alpha(10).length}}')).toBe('10');
});

it('should be able to return locale definition strings', () => {
expect(faker.definitions.cell_phone?.formats).toContain(
faker.helpers.fake('{{cell_phone.formats}}')
Expand Down
Loading