aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/helpers.ts17
-rw-r--r--test/helpers.spec.ts49
2 files changed, 51 insertions, 15 deletions
diff --git a/src/helpers.ts b/src/helpers.ts
index 051de5ea..f302ac46 100644
--- a/src/helpers.ts
+++ b/src/helpers.ts
@@ -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;
}
diff --git a/test/helpers.spec.ts b/test/helpers.spec.ts
index 0be83f98..cf817ae5 100644
--- a/test/helpers.spec.ts
+++ b/test/helpers.spec.ts
@@ -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');
});
});