Typing jest test.each tagged template literal with typescript

Viewed 2008

I am trying to type a jest test.each that uses a tagged template literal

test.each`
  height | text
  ${10}  | ${undefined}
  ${20}  | ${undefined}
  ${10}  | ${'text'}
  ${20}  | ${'text'}
`('$height and $text work as expected', ({ height, text }) => {
  //...
});
  • height is a number
  • text is a string or undefined

I could, of course add my types to the tests' function parameters:

({ height, text }: { height: number, text: string? }) => {
  //...
});

But this is not what I want. test.each accepts a generic type

test.each<MyType>`
  height | text
  // ...
`('$height and $text work as expected', ({ height, text }) => {
  //...
});

and I am wondering how I can use that type to infer the types in the function parameters.

1 Answers

I came across this question because I was looking for the same solution, but I have come to the conclusion that it is not possible because the types for the each function only use generics when the arguments passed are not of the template literal form. You can only use generic types when you pass in a table.

So your example would look like this:

test.each<{ height: number; text: string | undefined }>([
    { height: 10, text: undefined },
    { height: 20, text: undefined },
    { height: 10, text: 'text' },
    { height: 20, text: 'text' },
])('$height and $text work as expected', ({ height, text }) => {
    //...
});

Here is a link to the types file. @types/jest Each interface

Related