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

Can you direct me to the location where I can access the implementation of Selenium Interfaces?

I have a question regarding the implementation of Selenium Interfaces. Specifically, I am wondering where I can locate the specific implementation details for interfaces such as WebElement and Alert. For instance, WebElement contains a click() method but I ...

Creating an Escape key press event in plain Typescript without using JQuery

Is there a way to trigger an Escape button press event in Angular unit tests? const event = document.createEvent('UIEvent'); event.initUIEvent('keydown', true, true, window, 0); (<any>event).keyCode = 27; (<any ...

Problem with using TypeScript promise types in React's createContext

Currently, I am utilizing Firebase for email link sign-in. My goal is to check the link in the context file and proceed with signing in as shown below: const defaultValue = {}; interface AuthContextInterface { SignInWithLink: (email: string | null) => ...

In what situations is it appropriate to utilize the getInnerHtml() method?

Within Protractor, an ElementFinder instance has access to the getInnerHtml() method: var elm = element(by.id("myid")); expect(elm.getInnerHtml()).toEqual("test"); Interestingly, this method is not included in the official API list. Can you think of any ...

The functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

Tips for building a versatile client-server application with separate codebases for the JavaScript components

We are embarking on the process of rebuilding our CMS and leveraging our expertise with VueJS. Despite our familiarity with VueJS, we won't be able to create a full single-page application due to the presence of server-side rendering files (JSP). The ...

Supporting multiple types for matching object structures is a feature in Jest

I'm currently working on a test using jest to verify if an object key is either a string or a number. It seems like a basic task, but surprisingly there isn't much guidance in the documentation. Test Example: test('Checking asset structure ...

ContentChildren to gather all offspring

Currently, I am in the process of compiling a list of components using data from the Back End. I have implemented a ContentChild object to obtain their reference, however, it seems to be empty. I also attempted using ViewChild, but it only captures the fir ...

"Encountered the error message 'findOne is not a defined function' while using Jest

I am currently using sequelize mock v5 in order to mimic the User model. // user.test.js import User from "../models/user"; // original user model class jest.mock("../models/user", () => () => { const SequelizeMock = require( ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Encountering an issue when using the Google authentication provider with Next.js version 13

I am currently working on integrating next-auth with the Google provider and Prisma in my Next.js application, but I encountered the following error: Error: Detected default export in '/MyProject/foodbrain/app/api/auth/[...nextauth]/route.ts'. Pl ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

What is the correct way to declare the mongoose _id in a TypeScript interface?

I have a question about utilizing Mongoose and TypeScript using the interface+class+schema approach. When it comes to storing the _id field, what is the best method? I understand that the database stores it as a bson ObjectID. However, I've come acr ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Exploring the versatility of Angular 4 by implementing a switch feature with

My goal is to have the menu change based on the click of the "Cadastros" action, but it seems like the issue lies with the "workspaceSelected" property not being visible to all components. I believe the best approach in this situation would be to have the ...

Issue with locating assets in Angular 6 build

Hey there! I'm currently facing an issue while trying to build my angular project. In the project, I am using scss with assets, and below is a snippet of how I have defined the background image: .ciao { background-image: url("../../assets/images/bc ...

The error message for Angular FormControl's minimum length validation is not showing up in the errors

My goal is to access the minlength error, but when I check all the errors, it's not there. Below is my form control title: new FormControl("", [Validators.minLength(10), Validators.required]), I expect to see both the required and minlengt ...

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 ...