Skip to content

Commit 8b545b4

Browse files
authored
chore: fix mustache type warning and add some tests (#753)
1 parent 9e03bcf commit 8b545b4

2 files changed

Lines changed: 51 additions & 15 deletions

File tree

src/helpers.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -477,22 +477,19 @@ export class Helpers {
477477
*/
478478
mustache(
479479
str: string | undefined,
480-
data: Record<
481-
string,
482-
string | ((substring: string, ...args: any[]) => string)
483-
>
480+
data: Record<string, string | Parameters<string['replace']>[1]>
484481
): string {
485482
if (str == null) {
486483
return '';
487484
}
488485
for (const p in data) {
489486
const re = new RegExp('{{' + p + '}}', 'g');
490-
str = str.replace(
491-
re,
492-
// TODO @Shinigami92 2022-01-14: Try to improve the type or maybe use `if`
493-
// @ts-expect-error
494-
data[p]
495-
);
487+
const value = data[p];
488+
if (typeof value === 'string') {
489+
str = str.replace(re, value);
490+
} else {
491+
str = str.replace(re, value);
492+
}
496493
}
497494
return str;
498495
}

test/helpers.spec.ts

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -724,11 +724,50 @@ describe('helpers', () => {
724724
});
725725

726726
describe('mustache()', () => {
727-
it('returns empty string with no arguments', () => {
728-
expect(
729-
// @ts-expect-error
730-
faker.helpers.mustache()
731-
).toBe('');
727+
it('returns empty string with no template input', () => {
728+
expect(faker.helpers.mustache(undefined, {})).toBe('');
729+
});
730+
731+
it('returns empty string with empty template input', () => {
732+
expect(faker.helpers.mustache('', {})).toBe('');
733+
});
734+
735+
it('supports string replace values', () => {
736+
const actual = faker.helpers.mustache('1{{value}}3', { value: '2' });
737+
738+
expect(actual).toBe('123');
739+
});
740+
741+
it('supports function replace values faker values', () => {
742+
const actual = faker.helpers.mustache('1{{value}}3', {
743+
value: faker.datatype.string(2),
744+
});
745+
746+
expect(actual).toHaveLength(4);
747+
});
748+
749+
it('supports function replace values faker function', () => {
750+
const actual = faker.helpers.mustache('1{{value}}3', {
751+
value: () => faker.datatype.string(3),
752+
});
753+
754+
expect(actual).toHaveLength(5);
755+
});
756+
757+
it('supports function replace values no args', () => {
758+
const actual = faker.helpers.mustache('1{{value}}3', {
759+
value: () => '7',
760+
});
761+
762+
expect(actual).toBe('173');
763+
});
764+
765+
it('supports function replace values with args', () => {
766+
const actual = faker.helpers.mustache('1{{value}}3', {
767+
value: (key) => String(key.length),
768+
});
769+
770+
expect(actual).toBe('193');
732771
});
733772
});
734773

0 commit comments

Comments
 (0)