Skip to content

Instantly share code, notes, and snippets.

@sidharthv96
Last active September 7, 2022 11:13
Show Gist options
  • Save sidharthv96/80cc25016d94b6f6590dec89e6586c64 to your computer and use it in GitHub Desktop.
Save sidharthv96/80cc25016d94b6f6590dec89e6586c64 to your computer and use it in GitHub Desktop.
Vitest template literal support for it.each

Used to convert jest's Tagged Template literals to object arrays as required by vitest. Example: Jest code

it.each`
str       | expected
${'1d'}   | ${moment.duration(1, 'd')}
${'2w'}   | ${moment.duration(2, 'w')}
`('should parse $str to $expected duration', ({ str, expected }) => {
   expect(yourFunction(str)).toEqual(expected);
 });

Vitest code

it.each(convert`
str       | expected
${'1d'}   | ${moment.duration(1, 'd')}
${'2w'}   | ${moment.duration(2, 'w')}
`)('should parse $str to $expected duration', ({ str, expected }) => {
   expect(yourFunction(str)).toEqual(expected);
 });

Warning

This is just a simple hack to support easy migration of jest to vitest. This was tested only on tests in Mermaid repo.

Template literal support has been avoided intentionally in Vitest, this is only meant as a stop-gap.

/*
Used to convert jest's Tagged Template literals to object arrays as required by vitest.
Example:
Jest code
```ts
it.each`
str | expected
${'1d'} | ${moment.duration(1, 'd')}
${'2w'} | ${moment.duration(2, 'w')}
`('should parse $str to $expected duration', ({ str, expected }) => {
expect(yourFunction(str)).toEqual(expected);
});
```
Vitest code
```ts
it.each(convert`
str | expected
${'1d'} | ${moment.duration(1, 'd')}
${'2w'} | ${moment.duration(2, 'w')}
`)('should parse $str to $expected duration', ({ str, expected }) => {
expect(yourFunction(str)).toEqual(expected);
});
```
*/
export const convert = (template: TemplateStringsArray, ...params: any[]) => {
const header = template[0]
.trim()
.split('|')
.map((s) => s.trim());
if (header.length === 0 || params.length % header.length !== 0) {
throw new Error('Table column count mismatch');
}
const chunkSize = header.length;
const out = [];
for (let i = 0; i < params.length; i += chunkSize) {
const chunk = params.slice(i, i + chunkSize);
out.push(Object.fromEntries(chunk.map((v, i) => [header[i], v])));
}
return out;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment