"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests.

Below is the code snippet:

const invalidTestCases = [
  [null, TypeError],
  [undefined, TypeError],
  [false, TypeError],
  [true, TypeError],
];

describe('normalizeNames', () => {
  describe('invalid', () => {
    test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => {
      expect(() => normalizeNames(actual as any)).toThrowError(expected);
    });
  });

  describe('valid', () => {
    // ...
  });
});

The issue arises when attempting to run this code due to TypeScript errors:

Argument of type '(actual: boolean | TypeErrorConstructor | null | undefined, expected: boolean | TypeErrorConstructor | null | undefined) => void' is not assignable to parameter of type '(...args: (TypeErrorConstructor | null)[] | (TypeErrorConstructor | undefined)[] | (boolean | TypeErrorConstructor)[]) => any'.
      Types of parameters 'actual' and 'args' are incompatible.
        Type '(TypeErrorConstructor | null)[] | (TypeErrorConstructor | undefined)[] | (boolean | TypeErrorConstructor)[]' is not assignable to type '[boolean | TypeErrorConstructor | null | undefined, boolean | TypeErrorConstructor | null | undefined]'.
          Type '(TypeErrorConstructor | null)[]' is missing the following properties from type '[boolean | TypeErrorConstructor | null | undefined, boolean | TypeErrorConstructor | null | undefined]': 0, 1
           test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => {
                                                       ~~~~~~~~~~~~~~~~~~~~~~~

I also experimented with using an array of objects instead of a 2D array, like so:

const invalidTestCases = [
  { actual: null, expected: TypeError },
  { actual: undefined, expected: TypeError },
  { actual: false, expected: TypeError },
  { actual: true, expected: TypeError },
];

describe('normalizeNames', () => {
  describe('invalid', () => {
    test.each(invalidTestCases)('some description for (%p, %p)', ({ actual, expected }) => {
      expect(() => normalizeNames(actual as any)).toThrowError(expected);
    });
  });

  describe('valid', () => {
    // ...
  });
});

...however, by doing it this way, getting the correct test description for object values becomes challenging.

Answer №1

Currently, I am unable to test it in my current location. However, adding type annotations usually resolves that particular error.

Therefore, you could attempt the following:

type testCaseErrorTypes = null|undefined|boolean
const invalidTestCases: [testCaseErrorTypes, typeof TypeError][] = [
  [null, TypeError],
  [undefined, TypeError],
  [false, TypeError],
  [true, TypeError],
];
test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => { … }

This adjustment will convert invalidTestCases from a

(testCaseErrorTypes|TypeError)[][]
to the accurate type of
[testCaseErrorTypes, TypeError][]
.

Answer №2

If all the expected values are the same, you can simplify by using a 1-dimensional array and passing the TypeError directly to the toThrowError function. Here's an example implementation:

const invalidValues = [
  null,
  undefined,
  false,
  true,
];

describe('normalizeNames', () => {
  describe('invalid input', () => {
    test.each(invalidValues)('testing for (%p)', value => {
      expect(() => normalizeNames(value as any)).toThrowError(TypeError);
    });
  });

  describe('valid input', () => {
    // ...
  });
});

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

Navigating through JavaScript links in Selenium (Scrapy) and returning to the initial page: A step-by-step guide

Having some difficulties with pages that have javascript links embedded in them. This issue arises when the page contains a list of cities with javascript in their links. Each link needs to be navigated individually, scraping information and then returning ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

Activate on-demand static regeneration with Next.js

I am thoroughly impressed by the functionality of Incremental Static Regeneration in Next.js. However, I am currently seeking a method to manually trigger static page regeneration as needed. It would be ideal to have a command that can be executed via an ...

Incorporate data binding within ngFor

When working with an array in HTML using *ngFor, I need to calculate the total value of the array without utilizing the .ts file. The total value should be displayed in a separate row. <ion-grid> <ion-row *ngFor="let item of dailyDays"> ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

Undefined scope

angular.module('CrudApp', []). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/', { templateUrl: 'assets/tpl/lists.html', controller: ListCtrl }). when('/add-user&apos ...

Steps for building JSX with a loop

Recently diving into the world of React and Javascript, I've been attempting to assemble a JSX 'tree' dynamically using a loop rather than hard-coding the data. However, I find myself facing a hurdle where Visual Studio Code insists on havi ...

It takes a brief moment for CSS to fully load and render after a webpage has been loaded

For some reason, CSS is not rendering properly when I load a webpage that was created using React, Next.js, Material UI, and Styled-components. The website is not server-side rendered, but this issue seems similar to what's described here You can see ...

Differences Between Angular 2 CoreModule and SharedModule

Can anyone provide an explanation of the purpose of a SharedModule and a CoreModule? I've noticed that many projects are adopting this structure when building their Angular applications. What is the reasoning behind having two separate modules? At ...

Can README docs be prioritized to appear before all other stories in Storybook navigation?

Organizing my Storybook stories is important to me. I like to nest all my stories under a “Docs” header, with each component having a README mdx file followed by its stories. My preferred order is to always have the README appear first in the navigatio ...

Issues with Jquery Div sliding transitions from right to left are not functioning correctly

Creating page transitions in jQuery similar to "http://support.microsoft.com/." Encountering an issue where after the page transitions are completed, they start from the left instead of the expected right direction. Referencing this fiddle (Working Code) ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Guide to excluding all subdependencies using webpack-node-externals

My current setup involves using webpack to bundle both server assets and client code by specifying the target property. While this configuration has been working well, I encountered an issue where webpack includes all modules from node_modules even for ser ...

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

After upgrading to version 8 of the Firebase JS SDK, the "firestore" module (imported as "firebase") could not be located within the "firebase" package

After upgrading the firebase JS SDK from v7 to v8.0.0, I changed my import of firebase as shown below. import * as firebase from 'firebase'; However, attempting to access certain properties resulted in an error message: firebase.firestore.FieldV ...

What is the process for reading server responses following the delivery of an alert to a designated user through socket.io?

Recently, I started exploring Socket.io and encountered an interesting challenge. My goal is to retrieve real-time location data from an Android device. To achieve this, I developed a basic application to access the current GPS coordinates. Additionally, I ...

Transmitting a jQuery array from the client to the server using AJAX in

I've looked at so many posts about this issue, but I still can't get my code to work. My goal is to retrieve a PHP array of values from the checkboxes that are checked. Here is my code snippet: <!doctype html> <html> <head> & ...

Utilizing Glassfish Application Server and MSSQL Database for Angular Front-End Authentication in Jakarta

Embarking on my journey in the realm of web development, I am eager to implement authentication for my full-stack application. Armed with Angular 13 on the front end, Jakarta 9 running on Glassfish app server, and MSSQL database, I find myself at a loss on ...