Skip to content

Commit

Permalink
jest-each: simplify interpolation (#13898)
Browse files Browse the repository at this point in the history
  • Loading branch information
Connormiha committed Feb 11, 2023
1 parent ee1895f commit c81dfaf
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 18 deletions.
27 changes: 27 additions & 0 deletions packages/jest-each/src/__tests__/template.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,33 @@ describe('jest-each', () => {
undefined,
);
});

test('calls global with title containing param values when using fake $variable', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)`
a | b | expected
${0} | ${1} | ${1}
${1} | ${1} | ${2}
`;
const testFunction = get(eachObject, keyPath);
testFunction(
'expected string: a=$a, b=$b, b=$b, b=$b.b, b=$fake, expected=$expected index=$#',
noop,
);

const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string: a=0, b=1, b=1, b=1, b=$fake, expected=1 index=0',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: a=1, b=1, b=1, b=1, b=$fake, expected=2 index=1',
expectFunction,
undefined,
);
});
});
});
});
30 changes: 12 additions & 18 deletions packages/jest-each/src/table/interpolation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,19 @@ export const interpolateVariables = (
template: Template,
index: number,
): string =>
Object.keys(template)
.reduce(getMatchingKeyPaths(title), []) // aka flatMap
.reduce(replaceKeyPathWithValue(template), title)
.replace('$#', `${index}`);

const getMatchingKeyPaths =
(title: string) => (matches: Headings, key: string) =>
matches.concat(title.match(new RegExp(`\\$${key}[\\.\\w]*`, 'g')) || []);
title
.replace(
new RegExp(`\\$(${Object.keys(template).join('|')})[.\\w]*`, 'g'),
match => {
const keyPath = match.slice(1).split('.');
const value = getPath(template, keyPath);

const replaceKeyPathWithValue =
(template: Template) => (title: string, match: string) => {
const keyPath = match.replace('$', '').split('.');
const value = getPath(template, keyPath);

if (isPrimitive(value)) {
return title.replace(match, String(value));
}
return title.replace(match, pretty(value, {maxDepth: 1, min: true}));
};
return isPrimitive(value)
? String(value)
: pretty(value, {maxDepth: 1, min: true});
},
)
.replace('$#', `${index}`);

/* eslint import/export: 0*/
export function getPath<
Expand Down

0 comments on commit c81dfaf

Please sign in to comment.