Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout

  it.each([
    { numbers: [1, 2, 3] },
    { numbers: [4, 5, 6] }
  ])('Test case %#: Amount is $numbers.length => $numbers', ({ numbers }) => {
    expect(true).toBeTruthy();
  });

The output of the test runner includes

✓ Test case 0: Amount is $numbers.length => $numbers (4ms)

Is there a way to substitute $numbers with its actual value for further manipulation? For example, applying array functions on it.


An effective alternative approach could be

  [
    [1, 2, 3],
    [4, 5, 6]
  ].forEach((numbers, index) => {
      it(`Test case ${index}: Amount is ${numbers.length} => ${numbers}`, () => {
        expect(true).toBeTruthy();
      })
  });

However, it's uncertain if this method is recommended by jest documentation.

Answer №1

To achieve this functionality, you can utilize the template literal approach of using test.each, like so:

test.each`
    input | outcome
    ${4}  | ${'result-4'}
    ${5}  | ${'result-5'}
    ${6}  | ${'result-6'}
`('When the input=$input should yield $outcome', ({ input, outcome }) => { ...

Keep in mind a few essential points regarding this method:

  1. Because it's a template literal, values in the table must be enclosed in ${ }.
  2. The table formatting necessitates the use of | to separate columns.
  3. In the test callback function, make sure to destructure the arguments ( { input, outcome} instead of input, outcome)

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

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

Managing promises - updating database entry if it already exists

I'm encountering a new challenge with Promises. Objective: Update the database entry only if P_KEY exists. The current database is accessible through a module that has both get and put methods for the database, each returning a Promise. Approach: ...

How to efficiently assign a random set of values to a group of players in Javascript/nodejs while ensuring each player does not receive their own inputted value

Within my array, I have stored the following information: players[{nickname: data.player, id: socket.id, data: playerdata}] The playerdata itself is an array playerdata[] In the first value of playerdata, each player has entered a string. (playerindex ...

Error 2322: Troubleshooting Typescript arrow functions overloads issues

Everything seems to be working well with the code below, except for an error that occurs with the resolve constant. const resolve: Resolve Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

What is the best way to integrate react-final-form with material-ui-chip-input in a seamless manner

Currently, I am utilizing Material UI Chip Input wrapped with Field from react-final-form. The main objective is to restrict the number of "CHIPS" to a maximum of 5. Chips serve as concise elements representing inputs, attributes, or actions. For more ...

Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation. For example : 65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111]) 12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [ ...

Submit a form using Ajax without having to reload the page

Seeking help for implementing an ajax form submission with four answer options to a question. The goal is to submit the form without reloading the page upon selecting an option. Below is the code I have been working on. Any suggestions or solutions are wel ...

Get an angular xml file by utilizing the response from a C# web API download

I am trying to download an XML file from a database using a Web API in C#, which returns the file as byte[]. How can I properly read these bytes and convert them into an XML file on the client side using Angular? Despite attempts with blobs and other metho ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Show input field depending on chosen option

I'm looking to create a dynamic form where specific input fields are displayed based on the selection made in another field. For example, if "gender: male" is selected, the input field for "blue" should appear, and if "gender: female" is selected, the ...

Basic node.js server that responds with HTML and CSS

I have successfully created a basic http server to send an HTML file as a response. However, I'm struggling with how to also send a CSS file so that the client can view the HTML page styled with CSS in their browser. Here is my current code: var htt ...

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...

Tips for sending an email to an address from a user input field in React.js/Express.js

I am currently developing an email application that allows users to send emails to any recipient of their choice. The challenge I'm facing is that I need a way to send emails to user-specified email addresses without requiring passwords or user.id det ...

I am facing an issue where the table in my Laravel Vue component is not displaying the data from

Recently, I've been diligently following an instructional series on VUE applications by a highly recommended YouTuber. Every step was meticulously executed until I hit a roadblock out of nowhere. The data from my database refuses to display on the fro ...

Steps for updating the homepage to display a personalized welcome message to the user after logging in and redirecting using node.js and

Upon arriving at the homepage, simply click on the sign-in button. Once redirected back to the home page, you will notice a personalized greeting saying 'Welcome [user]'. Wondering how to achieve this? It's as simple as changing the text fro ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. Referring to the image provided, the first 'Product & Total Product' element ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

How to customize XMLHttpRequest in Firefox's WebExtension

Recently, I've been attempting to override the XMLHttpRequest.protype.open method within Firefox's WebExtension environment. My current approach involves the following code snippet written in a content script: var oldOpen = XMLHttpRequest.protot ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...