Creating a mock instance of a class and a function within that class using Jest

I am currently testing a class called ToTest.ts, which creates an instance of another class named Irrelevant.ts and calls a method on it called doSomething.

// ToTest.ts
const irrelevant = new Irrelevant();
export default class ToTest {

  // ... some implementation, constructor, etc.

  public static callIrrelevant() {
    return irrelevant.doSomething();
  }
}

//Irrelevant.ts
export default class Irrelevant {

  // ... some implementation, constructor, etc.

  public doSomething() {
    console.log("doing something");
  }
}

How can I successfully mock the irrelevant.doSomething() function in my jest test?

I have attempted:

import Irrelevant from '../some/path/irrelevant';
test('irrelevant.doSomething is mocked' => {
  Irrelevant.prototype.doSomething = () => jest.fn().mockImplementation(() => {
    console.log(`function got called`)
  });
  const toTest = new ToTest();
  toTest.callIrrelevant();
});
test('irrelevant.doSomething is mocked -- second try' => {
  jest.mock('../some/path/irrelevant')
  const mockDoSomething = jest.spyOn(Irrelevant, "doSomething"); // Throws error: Argument of type '"doSomething"' is not assignable to parameter of type 'never'.
  mockDoSomething.mockImplementation(() => {
    console.log(`function got called`)
  });
  const toTest = new ToTest();
  toTest.callIrrelevant();
 });
});

The mock implementations fail to execute in both tests. What is the correct way to mock this situation?

Answer №1

When utilizing mockImplementation as a substitute for the constructor of Irrelevant, it is crucial to understand that the result will serve as your mock. For example, you can implement it in this manner:

import Irrelevant from '../some/other/place/irrelevant';

jest.mock('../some/other/place/irrelevant');

const spyDoSomething = jest.fn();

(Irrelevant as any).mockImplementation(() => {
  return { doSomething: spyDoSomething };
})

Answer №2

import Unimportant from '../different/directory/unimportant';
test('unimportant.executeTask is replaced' => {
  Unimportant.prototype.executeTask = () => jest.fn(() => {
    console.log(`function was invoked`)
  });
  const testSubject = new TestSubject();
  testSubject.doUnimportantTask();
});

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

Automatically arrange TypeScript import statements in alphabetical order in WebStorm / PhpStorm

I am using tslint with the default config tslint:recommended and I am looking to minimize the number of rules I need to customize. Some rules require that imports be alphabetized: src/core/task/TaskMockDecorator.ts[2, 1]: Imports within a group must be a ...

What is the best way to iterate through all class properties that are specified using class-validator?

I have a class defined using the class-validator package. class Shape { @IsString() value?: string @IsString() id?: string } I am trying to find a way to retrieve the properties and types specified in this class. Is there a method to do s ...

Incorporate FontAwesome global components into your Vue project using TypeScript

Hey there, I'm a TypeScript newbie and looking to incorporate FontAwesome icons into my Vue 3 App. Here's the setup: Here is my main.ts : import Vue, { createApp } from 'vue'; import './registerServiceWorker'; import { librar ...

What impact does setting 'pathmatch: full' in Angular have on the application?

When the 'pathmatch' is set to 'full' and I try to delete it, the app no longer loads or runs properly. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { H ...

Material-UI Alert: The property `onKeyboardFocus` for event handling is unrecognized and will not be applied

Here is a more detailed trace of the issue: warning.js:33 Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored. in div (created by IconMenu) in div (created by IconMenu) in IconMenu (created by DropdownMenu) in div ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'events& ...

A promise was caught with the following error: "Error in ./Search class Search - inline template:4:0 caused by: Maximum call stack size exceeded"

As a newcomer to Angular2, I am currently developing a web application that requires three separate calls to a REST API. To test these calls, I decided to simulate the API responses by creating three JSON files with the necessary data. However, my implemen ...

Implicated Generic in TypeScript

Is there a way to simplify my class A implementation? export class A<TB extends B<TC>, TC> implements TD<TB, TC> { make(): TC {} } Currently, I have to specify the TC type every time I create an instance of A: class CTest {} class BTes ...

How can I determine which dist folder is utilized during the building of my App if an npm package contains multiple dist folders?

I have integrated an npm package called aurelia-google-maps into my application. This package includes various distribution folders such as AMD, System, CommonJS, Native Modules, and ES2015 within the /node_modules/ directory like so: /node_modules/ /a ...

Error: The function type 'Dispatch<SetStateAction<string>>' cannot be assigned to the type '(value: OptionValue) => void'

I recently dove into the world of integrating Typescript generics with React after reading this insightful article. I followed the code provided in the article, but encountered the following error: Type 'Dispatch<SetStateAction<string>>&ap ...

Flying around in every essential element within a Vue template

Recently, I made the switch to Typescript for Vue and decided to enable the Volar extension. However, after doing so, I noticed that every HTML intrinsic element (such as section and img) is now being flagged as an error: JSX element implicitly has type &a ...

Generate an object in Typescript that includes a dynamic property calculated from an input parameter

Is there a way to achieve the following function in TypeScript? function f<T extends 'a' | 'b'>(t : T): {[t]: ...} { return {[t]: ...} } This code is intended to make f('a') have type {'a': ...} and similarl ...

Defining a type with limited knowledge: if you only have one key in the object

Attempting to establish a type for an object Consider the following object structure: { a: 123, b: "hello", c: { d:"world" } } The keys present in the object are unknown. To define its type, I would use Record<st ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

Testing a feature in Angular that modifies a variable

Trying to test a function that updates a Boolean variable has been causing some confusion for me. The strange thing is, even though the function seems to be called successfully when using the toHaveBeenCalled method, the variable itself never actually gets ...

Tips for getting Angular's HttpClient to return an object rather than a string?

How can I make HttpClient return the data in JSON Object format? The Angular documentation states that HttpClient should automatically parse returned JSON data as an object. However, in my project, it only returns the data as a string. Although using JSO ...

What is causing VSCode's TypeScript checker to overlook these specific imported types?

Encountering a frustrating dilemma within VS Code while working on my Vite/Vue frontend project. It appears that certain types imported from my Node backend are unable to be located. Within my frontend: https://i.stack.imgur.com/NSTRM.png The presence o ...

Issue regarding retrieving the image using TypeScript from an external API

Hey developers! I'm facing an issue with importing images from an external API. I used the tag: <img src = {photos [0] .src} /> but it doesn't seem to recognize the .src property. Can anyone shed some light on how this is supposed to work? ...

Oops! The OPENAI_API_KEY environment variable seems to be missing or empty. I'm scratching my head trying to figure out why it's not being recognized

Currently working on a project in next.js through replit and attempting to integrate OpenAI, but struggling with getting it to recognize my API key. The key is correctly added as a secret (similar to .env.local for those unfamiliar with replit), yet I keep ...