Testing with Jest and Typescript: Verify whether the method "Array.prototype.reverse()" has been invoked

I'm currently grappling with how to properly test a function that involves calling the Array.prototype.reverse method on an array.

The issue lies in my struggle to effectively spy on the "reverse" method. I seem unable to correctly set the parameters for the jest.spyOn function.

This is a snippet resembling the actual code I aim to test:

const parentFunction = (param) => {
    let someArray = [];
    switch(param) {
        case 1:
            someArray = childFunction();
            break;
        default:
            break;        
    }
    return someArray;
}

const childFunction = () => {
    const anotherArray = [1, 2, 3, 4];
    const reversedArray = anotherArray.reverse();
    return reversedArray;
}

Here's what I've come up with for my test thus far:

test("checking if the reverse function has been called", () => {
    jest.spyOn(Array, "reverse"); // encountered an error in my editor
    jest.spyOn(Array.prototype, "reverse"); // also led to an error in my editor

    parentFunction(1);
    expect(Array.reverse).toHaveBeenCalled();
    expect(Array.prototype.reverse).toHaveBeenCalled();
});

In my Visual Studio Code editor, the word "reverse" is highlighted in red and displays the following error message:

No overload matches this call.   Overload 1 of 4, '(object: any\[\], method: FunctionPropertyNames\<any\[\]\>): never', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'FunctionPropertyNames\<any\[\]\>'.   Overload 2 of 4, '(object: any\[\], method: ConstructorPropertyNames\<any\[\]\>): never', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'ConstructorPropertyNames\<any\[\]\>'.

Could it be that I'm missing particular imports necessary for testing this function?

Any advice or suggestions would be greatly appreciated!

Answer №1

Always make sure to inspect your spy instance, rather than the object itself.

verify("whether the reverse function has been invoked", () => {
  const spyReverse = jest.spyOn(Array.prototype, "reverse");
  mainMethod(1);
  expect(spyReverse).toHaveBeenCalled();
});

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

Update TypeScript definitions in version 2.2.2 obtained from NPM @Types

I am currently utilizing the component react-router-bootstrap along with the definitions from DefinitelyTyped. However, the downloaded definitions do not align with the component. While I have submitted a pull request to rectify this issue, it has not yet ...

ERROR: The 'then' property is not found in the 'Hero[]' type

Code from the app.component.ts file import { Component, OnInit } from '@angular/core'; import { Hero } from './hero'; import { HeroService } from './hero.service'; @Component({ selector: 'app-root', templateUrl ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

How to style the currently active route link in Angular 2 using CSS

I want to add custom CSS styles to active router links: <a [routerLink]='link'>{{name}}</a> Here's what I attempted so far (Using the default router-link-active class): .router-link-active { color: #000; font-weight: bold; ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Can someone explain how I can extract values from components that have been added using a for each loop in Svelte

Embarking on my journey in frontend development and Svelte, I decided to dive into some experimentation. Here is a counter component with buttons to increment or decrement the number of items: Counter.svelte <script> export let quantity = 0; ...

I am encountering syntax errors with the @Page decorator and constructor () while working on the Ionic 2 template project

Recently, I created an Ionic 2 beta app, but encountered syntax errors when opening it in Visual Studio (VS) 2015. The errors were present inside all the .js files for the @Page decorator and the contructor () { }. As a newcomer to Ionic 2, pinpointing whe ...

The mat-table fails to populate with data retrieved from the rest service

I have successfully fetched an array from my REST service and displayed some information from the response on the page. However, I am facing issues populating my mat-table and I'm unsure of the cause. The mat-table was functioning properly in the past ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

There was a build error in npm run due to the inability to destructure the 'store' property from 'useReduxContext2()' when it is null. Additionally, hooks cannot be conditional in Next Js

Next.js with Redux is the framework I am working on, aiming to host the application on Vercel. However, during the local app building process, I'm facing a particular error: The following error occurs - TypeError: Cannot destructure property 's ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

Difficulty in updating the value of HTML Range element using Angular6 function

My goal is to retrieve the changing values from a series of HTML range sliders. This is how they are set up: <li *ngFor="let rgbVal of rgbVals; let i=index"> {{i}}: {{rgbVal}} <br> <div class="color-box" [style.back ...

The useRef function is malfunctioning and throwing an error: TypeError - attempting to access 'filed2.current.focus' when 'filed2' is null

I'm attempting to switch focus to the next input field whenever the keyboard's next button is pressed. After referring to the react native documentation, it seems that I need to utilize the useRef hook. However, when following the instructions f ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

The value of additionalUserInfo.isNewUser in Firebase is consistently false

In my application using Ionic 4 with Firebase/AngularFire2, I authenticate users with the signinwithemeailandpassword() method. I need to verify if it's the first time a user is logging in after registering. Firebase provides the option to check this ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

Click the button to apply a custom pipe for filtering the Angular table

I have successfully implemented a custom pipe to filter a table based on two input fields within a form. However, I now want to add functionality where the filtering only occurs when a submit button is clicked, similar to a search function. While I have fo ...

When ngIf fails to detect a change in a variable's value

Whenever I try to set a simple boolean variable to show/hide a div from another component, the ngIf directive doesn't seem to recognize it. In my messages-refresh.component.html file: <div class="divOpacity" *ngIf="show"> <div class="boxMes ...