Is there a way to mimic a static method using moq.ts?

There is a class called MyLogger with a static method getInstance(id: string) that returns an instance of Logger.

class Logger {
  error(message: string): Logger {
    // implementation...
  }
}

In the system under test, there is a class Sut with a log property initialized with MyLogger.getInstance(). It has a testMethod() that calls the error() method on the logger.

class Sut {
  log = MyLogger.getInstance();
  testMethod() {
    this.log.error('Foo');
  }
}

The goal is to intercept the method call and pass a mock logger instead. One way to achieve this is by using a Mock object:

const loggerMock = new Mock<MyLogger>();
loggerMock
  .setupStatic(()=>MyLogger.getInstance())
  .returns(loggerMock.object());

// assert call to `error()` method has parameter 'Foo'

Answer №1

This is the solution I have found:

const loggerMock = new Mocker<Logger>();
MyLogger.getInstance = jest.fn().mockReturnValue(loggerMock.object());

Is there a way to remove the reliance on jest.fn()?

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

Is there a way to configure side={THREE.BackSide} using an external .glb file?

As a beginner in Threejs, I am trying to incorporate the use of side="THREE.BackSide" with an external model file named room.glb. My development environment consists of nextjs 13 (with typescript and app directory enabled) along with @react-three ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

What is the best way to showcase images in an Angular application when the images are saved in the server uploads folder of a Node.js

In my node.js server, I have a separate directory where I store files in the uploads folder and save image paths in the db. The directory structure looks like this: node_modules src uploads |category-name-folder |image-name.jpg |category-name-folde ...

What steps can I take to resend a fetch request in React.js if I receive a 408 or 503 error?

There are times when I am fetching data from a server and the request takes too long, resulting in the server responding with a 408 status code. This is how my code currently looks: export class ResponseError extends Error { public response: Response; ...

Is it advisable to reuse encapsulated constants during unit testing and if so, what is the best

Hey there, I'm currently working on a unit test for a function. While the technical details are not crucial, I thought it would be helpful to provide some code snippets for better understanding. Check out the function below: export function getSalu ...

Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated. Below is the class in my SCSS file: .form-validation.invalid { border: 2px solid red } In my ts file, there's a variable named isEmailValid. When this variable is set to ...

Encountering TS 2694 Error while running the ng serve command

I'm encountering some troublesome errors while attempting to run my angular application. Honestly, I can't figure out what's wrong, so I'm hoping someone here can assist me. I didn't make any significant changes, just added a singl ...

Is there a way for me to determine the value that has been assigned to a <li> key attribute in React using Jest and testing-library/react?

In my current project, I am using a combination of React with TypeScript and Jest along with Testing Library for testing purposes. I have a specific requirement to unit test some code where I need to ensure that the person.id is correctly set as the key at ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

Some challenges encountered in Typescript/tslint

Just starting out with Typescript and trying basic annotations. First, having trouble with one of the imports. Second, unable to recognize type inside object destructuring. Third, facing issues with JSX implementation. Here is my code: import * as React ...

What is the reason for TypeScript's prioritization of arguments over assignment in generic inference?

When it comes to Typescript generics inference, the priority is given to arguments over assignment. This means that any param props are automatically converted into type unknown, even if they are assigned to a variable whose type param is set to an object ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

Does the router navigate function instantly update the router URL?

I'm testing whether the navigate function will immediately alter the router URL upon execution. this.router.navigate(['/home/products']); if (this.router.url.includes('/home/products')) console.log('URL has been changed&apos ...

The React error message states that there are no shared properties between the 'Component<P, S>' type and the 'ComponentLifeCycle<P, S>' type

Encountering an error when attempting to bundle my React application, here is the issue I am facing: https://i.sstatic.net/g0yRh.png This is the structure of my @types/react/index.d.ts file: class Component<P, S> implements ComponentLifecycle< ...

Fetching FormControl from Directive in Angular

Is there a way to dynamically add validators to a FormControl through a custom Directive? @Directive({ selector: "[idNumber]", }) export class IdNumberDirective implements OnInit { constructor(private formControl: FormControl) { } ngOnInit() ...

In TypeScript, a generic function with an index constraint

Is it possible to define an element that operates in the manner indicated here? function fn<T, U extends keyof T, T[U] extends number>() I am having trouble making the "T[U] extends number" portion function correctly. ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

React-select initial value set to null after first selection

I've been working on a dropdown feature with the help of react-select: The options for the dropdown are fetched from an API endpoint, but I'm encountering a peculiar issue. When I initially select an option, my AccountSelected1 remains null. Sub ...

Maximizing the potential of useRef within a function handler when utilizing hooks

I'm running into an issue where I am unable to set the state on values when submitting a form that sends an http request. It seems that the values are undefined and not being passed upon click, resulting in errors with the set...() function. Below yo ...