Tips for creating a mock object for a class that was instanced with the `new`

class MyClass {

    async myMethod(req, res):Promise<any>{
        const result = await new Helper().doSomething()
    }
}

When creating a unit test for myMethod, how can we mock the Helper class method?

Answer №1

If you haven't specified the testing package you're using, here is a solution using Jest.

To create a manual mock, save a mock implementation in the mocks folder. This allows for specifying the implementation and using it across test files.

// __mocks__/HelperClass.js

// Import this named export into your test file:
export const mockRandomMethod = jest.fn();
const mock = jest.fn().mockImplementation(() => {
  return {randomMethod: mockRandomMethod};
});

export default mock;

Import the mock and the shared mock method:

// myMainClass.test.js
import HelperClass, {mockRandomMethod} from './HelperClass';
import myMainClass from './myMainClass';
jest.mock('./HelperClass'); // HelperClass now acts as a mock constructor

beforeEach(() => {
  // Clear all instances and calls to constructor and methods:
  HelperClass.mockClear();
  mockRandomMethod.mockClear();
});


it('Verify if the consumer called a method on the class instance', () => {
  const myMainClassInstance = new myMainClass();
  myMainClassInstance.sampleMethod();
  expect(mockRandomMethod).toHaveBeenCalled();
});

Jest Documentation

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 provide the syntax for a generic type parameter placed in front of a function type declaration?

While reviewing a project code recently, I came across some declarations in TypeScript that were unfamiliar to me: export interface SomeInterface<T> { <R>(paths: string[]): Observable<R>; <R>(Fn: (state: T) => R): Observable ...

Function overloading proving to be ineffective in dealing with this issue

Consider the code snippet below: interface ToArraySignature { (nodeList: NodeList): Array<Node> (collection: HTMLCollection): Array<Element> } const toArray: ToArraySignature = <ToArraySignature>(arrayLike: any) => { return []. ...

Issues with executing code within the react package for Yahoo Finance 2

I am currently in the process of developing a React application using Vite. The purpose of my app is to retrieve stock-related information from Yahoo using the yahoo-finance2 package. Interestingly, when I run the code as a standalone JavaScript file, eve ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Having trouble importing the Renderer2 component in Angular

Trying to include Renderer2 with the following import: import { Renderer2 } from '@angular/core'; Encountering an error: "Module 'project/node_modules/@angular/core/index' does not have an exported member 'Renderer2'. Puzz ...

Utilize the key types of an object to validate the type of a specified value within the object

I am currently working with an object that contains keys as strings and values as strings. Here is an example of how it looks: const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff', } Next, I define a type ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

Unable to link to 'Attribute A' because it is not recognized as a valid property of 'Subcomponent'

Within my project, I have a generic class with several components that inherit from it. BaseRdnInput.ts: @Injectable() export abstract class BaseRdnInput implements ControlValueAccessor, Validator { @Input() rdnModel?: any | Array<any ...

Tips for sending a timestamp as input to a stored procedure in TypeScript with the mssql module

Currently, I am utilizing the mssql npm package to communicate with SQL server. I have encountered a dilemma where the variable (which is of type TIMESTAMP in sql server) fetched from a stored procedure is returned as a byte array. Now, I need to pass this ...

I am encountering an issue in Vue3 where the parent event handler arguments are not being typed with the child's defineEmits definition. Can anyone explain this to me

I am struggling to correctly type the parent event handler based on the child definition, but no matter what I try, I always end up with `any` as the event type. Here is a code example: <script setup lang="ts"> // Child component type Even ...

Encasing event handler callback within Observable pattern

I am currently exploring how to wrap an event callback from a library to an RxJS Observable in a unique way. This library I am working with sets up handlers for events like so: const someHandler = (args) => {}; const resultCallback = (result) => {} ...

Angular version 6 and its routing functionality

Hey there, I need some help with setting up routers in my Angular app. Here is the code from my files: import {NgModule} from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const APP_ROUTES: Routes = [ {pa ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

Exploring the generalization of class member initialization in TypeScript

I am looking to make some modifications to the Blog constructor provided in the "Minimal working example" linked below. The objective is to refactor it using pseudo-code by leveraging a generic ModelHelper class to initialize the members of the "Blog" clas ...

Aliases for NPM packages and TypeScript declaration files

I am in need of two separate versions of a package, and fortunately with npm 6.9.0 I can easily accomplish that now. My dilemma is this: the package comes with type definitions. However, when I create an alias for this package and refer to it using the al ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Annoying glitch when using http get in Ionic (version 3.19.0)

Issue: Having trouble with Ionic's http get function, as I keep running into this error message: Typescript Error Expected 1-2 arguments, but got 3. The line causing the problem seems to be similar to this: this.http.get('http://127.0.0.1 ...

TypeScript and Angular: Error Encountered when Trying to Combine Two Arrays

I'm attempting to combine two arrays of the same type that are nested within a "parent" array. The end goal is to flatten the structure. Below is the code I have been using: ngOnInit() { this.Logs.getAllLogs() .subscribe(logs => { ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...