Mocking is not working for request scoped injection

I'm encountering an issue with mocking the return value of a provider, as it seems to be clearing out the mock unexpectedly.

Module1.ts

@Module({
  providers: [Service1],
  exports: [Service1],
})
export class Module1 {}

Service1.ts

@Injectable({
  scope: Scope.REQUEST,
})
export class Service1 {
  constructor() {
  }
  public getVal() {
    return '3';
  }
}

Service2.ts

@Injectable()
export class Service2 {
  constructor(private readonly service1: Service1) {}
  private someFn() {
    this.service1.getVal();
  }
}

Service2.test.ts

let service1;
let service2;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [Module1],
      providers: [Service2],
    }).compile();
    service2= await module.resolve(Service2);
    service1= await module.resolve(Service1);
  });
it('some test',()=> {
jest.spyOn(service1,'getVal').mockReturnValue('2'); //This should mock getVal function and return 2.
service2.someFn();
});

The issue is that the mock is not being applied. Is there something I am missing?

Answer №1

It is impossible for service1.getVal not to be mocked since the process is very simple. The fact that mocking it does not impact service2.someFn() indicates that service2 does not share the same Service1 instance as the one being mocked.

According to the explanation provided in the documentation:

REQUEST

A new provider instance is generated specifically for each incoming request. This instance is discarded once the request has finished processing.

This implies that Service1 instances are unique. Therefore, the instance associated with Service2 must be mocked:

jest.spyOn(service2['service1'], 'getVal').mockReturnValue('2')

Answer №2

Every instance of the provider is uniquely created with each call to resolve for scoped providers. To ensure consistency in testing scenarios like this, it is important to establish a contextId to maintain a unified DI sub tree.

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [Module1],
      providers: [Service2],
    }).compile();
    const contextId = ContextIdFactory.create();
    service2 = await module.resolve(Service2, contextId);
    service1 = await module.resolve(Service1, contextId);
  });

https://docs.nestjs.com/fundamentals/module-ref#resolving-scoped-providers

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

What is the best way to create a personalized filter function for dates in JavaScript?

I am working with a DataTable that includes a column called Timestamp: <p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt> <p-column field="timestamp" header="Timestamp" [sortable]=" ...

Locate material-ui input element using label in react testing library

Currently, I am working on writing a test case to verify that a number input is disabled when a specific radio option is selected. However, I am facing challenges in utilizing React Testing Library utilities to target the HTML <input> element rendere ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

"Encountering issues with the functionality of two Angular5 routers

main.component.html [...] <a routerLink="/company-list">Open</a> [...] <main> <router-outlet name="content"><router-outlet> </main> [...] app.compoment.html <router-outlet><router-outlet> app.routing.modu ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

Is there a way to conceal an element within a component based on the current component being used with the router?

I have managed to hide an entire component, but I am unsure of how to show or hide specific elements within a component. export class AppComponent { headerFooterVisible: boolean; constructor(private router: Router) { router.events.subscribe(e =&g ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

Unable to delete event listeners from the browser's Document Object Model

Issue at hand involves two methods; one for initializing event listeners and the other for deleting them. Upon deletion, successful messages in the console confirm removal from the component's listener array. However, post-deletion, interactions with ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

Creating a dynamic list in Typescript from a tuple array without any intersections

const colors = ["red", "blue", "green", "yellow"] as const; const buttonSizes = ["small", "medium", "large"] as const; type ColorType = (typeof colors)[number]; type SizeType = (typeof b ...

What does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...

Type definitions in Typescript for the style property of Animated.View

One of my components has a Props interface that extends ViewProps from React Native, like this: export interface Props extends ViewProps { // Custom props } As a result, this also extends the style prop. However, I am facing an issue while using Animat ...

Why does the page not work when I enter a certain URL with an ID parameter, and instead displays the error message "Uncaught ReferenceError: System is not defined"?

This is my "app.routing.ts": import {provideRouter, RouterConfig} from "@angular/router"; import {DashboardComponent} from "./dashboard.component"; import {HeroesComponent} from "./heroes.component"; import {HeroDetailsComponent} from "./hero-details.com ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Experiencing CORS problem in Ionic 3 when accessing API on device

I am a newcomer to IONIC and I am utilizing a slim REST API with Ionic 3. Currently, I am encountering the following error: "Failed to load : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin&apos ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

Implementing generics in TypeScript for objects made easy with this guide!

My question is regarding a function that utilizes generics and selects data from an object based on a key. Can we use generics inside the type of this object, or do we have to create a separate function for options? enum Types { book = 'book', ...

Unlocking the accordion feature in Ionic 3 form: A step-by-step guide

I am currently working on a search form and want to incorporate it within an accordion so that users can simply click to expand the form. Below is the code snippet: TS. buildForm(): void { this.form = this.fb.group({ username: new FormControl(& ...