Error encountered in spyOn TS when passing array iteration instead of a string

Instead of repeating test cases with minor adjustments, I have implemented an Array and iterated through it.

However, I am encountering a TS error in test when passed from the Array instead of as a string testLink

Error:

No overload matches this call.
  Overload 1 of 4, '(object: { registerLink: () => void; }, method: "registerLink"): SpyInstance<void, []>', gave the following error.
    Argument of type 'string' is not assignable to parameter of type '"registerLink"'.
  Overload 2 of 4, '(object: { registerLink: () => void; }, method: never): SpyInstance<never, never>', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.ts(2769)

Component.test.tsx

  for (let i = 0; i < testProp.length; i++) {
    it(`test default props of ${testProp[i].name}`, () => {
      const test = testProp[i].name
      jest.spyOn(ComponentDefaultProp, test)
    })
  }

But when I pass it as a string, no errors occur

  for (let i = 0; i < testProp.length; i++) {
    it(`test default props of ${testProp[i].name}`, () => {
      jest.spyOn(ComponentDefaultProp, 'testLink')
    })
  }

The array being looped over is:

const testProp = [
  {
    name: 'testLink',
  },
]

What worked but I prefer not to use any:

Test 1

  for (let i = 0; i < testProp.length; i++) {
    it(`test default props of ${testProp[i].name}`, () => {
      const test: any = testProp[i].name
      jest.spyOn(ComponentDefaultProp, test)
    })
  }

Test 2

  for (let i = 0; i < testProp.length; i++) {
    it(`test default props of ${testProp[i].name}`, () => {
      const test = testProp[i].name
      jest.spyOn<any, string>(ComponentDefaultProp, test)
    })
  }

Screenshot showing spyOn: https://i.sstatic.net/4HDeZ.png

The objective is to utilize an array without encountering TS error and avoiding any if possible

Answer №1

Ensure the correct types are added for the testProp variable. The example below demonstrates using

"typescript": "^3.6.4"
.

For instance:

index.test.ts:

const ComponentDefaultProp = {
  testLink() {
    return 'real testLink implementation';
  },
  testAnother() {
    return 'real testAnother implementation';
  },
};

describe('63615134', () => {
  const testProp: Array<{ name: keyof typeof ComponentDefaultProp }> = [{ name: 'testLink' }, { name: 'testAnother' }];

  for (let i = 0; i < testProp.length; i++) {
    it(`test default props of ${testProp[i].name}`, () => {
      const test = testProp[i].name;
      jest.spyOn(ComponentDefaultProp, test);
      ComponentDefaultProp[test]();
      expect(ComponentDefaultProp[test]).toBeCalled();
    });
  }
});

Unit test results:

 PASS  src/stackoverflow/63615134/index.test.ts (10.697s)
  63615134
    ✓ test default props of testLink (5ms)
    ✓ test default props of testAnother (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.982s

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

The function of TypeScript map is not working properly

Encountering the error message "data.map is not a function" while trying to map data from a REST API request returning JSON data. It appears that the issue may stem from the data structure, as it seems like the returned data should be accessed with data.da ...

Obtaining a value from within an Angular 'then' block

I have a unique issue that I haven't been able to find a solution for on StackOverflow: Within an Angular 6 service, I am trying to call a function from another service using TypeScript. Here is the code snippet: Service1: myArray: Array<IMyInte ...

Can a function utilize a Generic-specified type property?

function extractStringValue<T extends object, S extends keyof PickByValue<T, string>>( obj: T, key: S ): string { return obj[key]; }; The PickByValue function extracts properties of object T with values of type string. type CustomType = ...

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

Error in TypeScript: It is not possible to use a component with MUI styling as a JSX element

I can't figure out what's going wrong. I'm attempting to include a child component in the main page, and I have a feeling it has something to do with MUI styles being applied at the end. I removed all unnecessary code and still encounter thi ...

Examining the visual rendering of a webpage using next.js and jest

Is there a way to verify the accuracy of page rendering in next.js using images instead of HTML comparison? Currently, I have only come across a method to theoretically "render" the component into an HTML tags tree using toJSON(): import React from ' ...

Firebase Functions Project encountering a "Cannot find module" error in VS Code

While working on a firebase functions project in Visual Studio Code, I encountered an issue inside the index.ts file. The imported modules were not being recognized even though autocomplete showed that the modules exist. When attempting to import them, I k ...

Tips for incorporating auth0 into a vue application with typescript

Being a beginner in TypeScript, I've successfully integrated Auth0 with JavaScript thanks to their provided sample code. However, I'm struggling to find any sample applications for using Vue with TypeScript. Any recommendations or resources would ...

The new experimental appDir feature in Next.js 13 is failing to display <meta> or <title> tags in the <head> section when rendering on the server

I'm currently experimenting with the new experimental appDir feature in Next.js 13, and I've encountered a small issue. This project is utilizing: Next.js 13 React 18 MUI 5 (styled components using @mui/system @emotion/react @emotion/styled) T ...

Testing axios requests using react testing library and jest: A comprehensive guide

Trying to ensure that the onSubmit function is handled correctly after clicking the search button. My approach involves testing the inner workings of the onSubmit function, specifically focusing on the behavior of the axios request. In my test, I mocked ...

Exploring nested contexts in react testing library with renderHook

This is a sample code snippet in TypeScript that uses React and Testing Library: import React, { FC, useEffect, useMemo, useState } from 'react'; import { renderHook, waitFor } from '@testing-library/react'; interface PropsCtx { inpu ...

You are unable to compile a module in Visual Studio Code unless you provide the --module flag

I am facing an issue with my TypeScript code file that appears to be a common error, but I'm struggling to resolve it. This problem is new to me as I am still getting acquainted with Visual Studio Code. Cannot compile modules unless the '--modul ...

Harness the power of the Node.js Path module in conjunction with Angular 6

I'm currently facing an issue with utilizing the Path module in my Angular 6 project. After some research, I came across a helpful post detailing a potential solution: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d The remedy inv ...

What is the method for implementing two-way binding on a checkbox in Angular?

Within my accordion, I have a series of options in the form of checkboxes. Users are able to select these checkboxes, but I am seeking a way to pre-select certain checkboxes based on specific conditions. The challenge arises when these conditions are deter ...

Proper utilization of react-hook-form in conjunction with TypeScript and material-ui to display error messages efficiently

Currently, I am using a combination of react-hook-form with typescript and material-ui. My goal is to pass the error message as a helperText to the TextField. I attempted to achieve this by utilizing helperText={errors.email?.message} however, TypeScript ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this: const LIMITS: Limit[] = [ { id: 'limit1', value: 1000, disabled: false }, { id: 'limit2', value: 500, disabled: tru ...

When I attempt to map imports in Typescript, an error occurs, stating, "Element implicitly has an 'any' type because the expression of type 'string' is being indexed into type 'typeof import'."

(parameter) key: string An issue arises where the expression of type 'string' cannot be used to index type 'typeof import("d:/Projects/Front/attendance-checker2/src/redux/modules/sagas")', leading to an implicit 'any&a ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...