Skip to content

Commit

Permalink
chore: fix mustache type warning and add some tests (#753)
Browse files Browse the repository at this point in the history
  • Loading branch information
ST-DDT committed Apr 4, 2022
1 parent 9e03bcf commit 8b545b4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 15 deletions.
17 changes: 7 additions & 10 deletions src/helpers.ts
Expand Up @@ -477,22 +477,19 @@ export class Helpers {
*/
mustache(
str: string | undefined,
data: Record<
string,
string | ((substring: string, ...args: any[]) => string)
>
data: Record<string, string | Parameters<string['replace']>[1]>
): string {
if (str == null) {
return '';
}
for (const p in data) {
const re = new RegExp('{{' + p + '}}', 'g');
str = str.replace(
re,
// TODO @Shinigami92 2022-01-14: Try to improve the type or maybe use `if`
// @ts-expect-error
data[p]
);
const value = data[p];
if (typeof value === 'string') {
str = str.replace(re, value);
} else {
str = str.replace(re, value);
}
}
return str;
}
Expand Down
49 changes: 44 additions & 5 deletions test/helpers.spec.ts
Expand Up @@ -724,11 +724,50 @@ describe('helpers', () => {
});

describe('mustache()', () => {
it('returns empty string with no arguments', () => {
expect(
// @ts-expect-error
faker.helpers.mustache()
).toBe('');
it('returns empty string with no template input', () => {
expect(faker.helpers.mustache(undefined, {})).toBe('');
});

it('returns empty string with empty template input', () => {
expect(faker.helpers.mustache('', {})).toBe('');
});

it('supports string replace values', () => {
const actual = faker.helpers.mustache('1{{value}}3', { value: '2' });

expect(actual).toBe('123');
});

it('supports function replace values faker values', () => {
const actual = faker.helpers.mustache('1{{value}}3', {
value: faker.datatype.string(2),
});

expect(actual).toHaveLength(4);
});

it('supports function replace values faker function', () => {
const actual = faker.helpers.mustache('1{{value}}3', {
value: () => faker.datatype.string(3),
});

expect(actual).toHaveLength(5);
});

it('supports function replace values no args', () => {
const actual = faker.helpers.mustache('1{{value}}3', {
value: () => '7',
});

expect(actual).toBe('173');
});

it('supports function replace values with args', () => {
const actual = faker.helpers.mustache('1{{value}}3', {
value: (key) => String(key.length),
});

expect(actual).toBe('193');
});
});

Expand Down

0 comments on commit 8b545b4

Please sign in to comment.