Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal

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

One option would be to specify types in the test function parameters:

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

However, that's not my ideal solution. The generic type accepted by test.each.

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

Now the challenge is to utilize this type inference for the function parameter types.

Answer №1

While searching for a solution, I stumbled upon this question seeking the same answer. However, after some exploration, I have realized that achieving it might not be possible. This is because the each function only accepts generic types when the arguments provided are not in a template literal form. Generics can only be used with a table.

To illustrate, your example should resemble the following:

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 }) => {
    //...
});

If you would like to explore more about the types, refer to this @types/jest Each interface.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Snapshots testing app Expo TypeScript Tabs App.tsx

After setting up an Expo project with Typescript and Tabs, I decided to add unit testing using Jest but ran into some issues. If you want to create a similar setup, check out the instructions here: . Make sure to choose the Typescript with Tabs option whe ...

What steps can I take to ensure that AstroJS components do not conceal SVG elements when the SVG is incorporated into another file with client:load?

Currently, I am developing a weather application using Astro.js in conjunction with React. One of the features includes an SVG component that serves as the project logo and is implemented in the initial page loader. Upon the page loading, the SVG functions ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Creating and updating a TypeScript definition file for my React component library built with TypeScript

As I work on developing a React library using TypeScript, it is important to me that consumers of the library have access to a TypeScript definition file. How can I ensure that the TypeScript definition file always accurately reflects and matches the Java ...

Ways to verify the functionality of a webpage once it has been loaded on my local machine's browser

I manage a website that is currently hosted on a server and being used by thousands of visitors. The site is created using Java and soy template technology. I am looking to test the frontend rendering and JavaScript files. Can this be done directly from my ...

Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code: import ytdl from 'react-native-ytdl'; type DirectLink = { url: string; headers: any[]; }; type VideoFormat = { itag: number; url: string; width: number; height: number; }; type ...

Tips for enforcing strict typing in TypeScript when implementing abstract functions

Consider the following scenario with two classes: abstract class Configuration { abstract setName(name: string); } class MyConfiguration extends Configuration { setName(name) { // set name. } } In this setup, the name parameter in M ...

Generating a type definition from a JavaScript file

Looking to convert a .js file to a d.ts file, I've noticed that most resources on this topic are from 2 years ago How do you produce a .d.ts "typings" definition file from an existing JavaScript library? My question is, after 2 years, is there a simp ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

Leveraging react-share in combination with react-image-lightbox

I have recently inherited a React project and am struggling to integrate react-share with react-image-lightbox. My experience with both React and Typescript is limited, so any assistance would be greatly appreciated. Below are the relevant code snippets: ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

The error message "Property 'then' is not available on type 'void' within Ionic 2" is displayed

When retrieving data from the Google API within the function of the details.ts file, I have set up a service as shown below. However, I am encountering a Typescript error stating Property 'then' does not exist on type 'void'. this.type ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

What is the overlay feature in Material-UI dialogs?

I recently started using the React-Redux Material-UI package found at http://www.material-ui.com/#/components/dialog My goal is to implement a grey overlay that blankets the entire dialog element, complete with a circular loading indicator after the user ...

What is the best way to hand off this object to the concatMap mapping function?

I'm currently in the process of developing a custom Angular2 module specifically designed for caching images. Within this module, I am utilizing a provider service that returns Observables of loaded resources - either synchronously if they are already ...

Explain the object type that is returned when a function accepts either an array of object keys or an object filled with string values

I've written a function called getParameters that can take either an array of parameter names or an object as input. The purpose of this function is to fetch parameter values based on the provided parameter names and return them in a key-value object ...

Issue: The function react.useState is either not defined or its output is not iterable

I'm facing an issue while programming in Next.js 13. Any help or suggestions would be greatly appreciated! Here are the relevant files: typingtext.tsx import React from "react"; export function useTypedText(text: string, speed: number, dela ...

Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship: Departament: @Entity('Departament') export default class Departament { @PrimaryGeneratedColumn() id: string; @Column() departament_name: string; @OneToOne(type ...