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

The console is displaying a promise that is pending, rather than the desired data

Here is the content of my file: 'use strict' import * as moment from "moment"; import { Report} from "./Report"; import { Timeframe} from "./Timeframe"; import { ReportComparison } from "./ReportComparison"; function test(firstFrom: string, fi ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

Executing an asynchronous function within an Angular 7 interceptor is crucial

I've been working on creating an interceptor to handle a situation where a function needs to be called to refresh the session upon receiving a 401 error response. Here's what I have so far but I'm facing build issues and struggling to figure ...

Issues with the rating plugin functionality in Ionic 3

After following the instructions in this tutorial: http://ionicframework.com/docs/native/app-rate/ Even though I implemented the second method, I encountered the following error: Uncaught (in promise): TypeError: Cannot read property 'split' ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

Utilizing React's idiomatic approach to controlled input (leveraging useCallback, passing props, and sc

As I was in the process of creating a traditional read-fetch-suggest search bar, I encountered an issue where my input field lost focus with every keypress. Upon further investigation, I discovered that the problem stemmed from the fact that my input comp ...

A new concept within the realm of programming is the Export class statement that utilizes

Is it possible to define both a class and an interface in the same file and export the class directly without any issues? I have encountered problems when using export default Foo, as it exports as { default: Foo } instead of the actual class object. I am ...

Using Angular to declare a variable for reuse within nested HTML elements

Exploring the realm of angular development has sparked my interest, however, I found myself at a roadblock while reading through the documentation. The issue lies in figuring out how to declare a variable that can be reused effectively within nested HTML e ...

Exploring Angular5 Testing Utilizing Jasmine: A Component Found in Both the AppModule and DynamicTestModule's Declarations

Currently, I'm working on writing my initial test and facing a specific error: An error stating that Type SearchComponent is part of the declarations of 2 modules – AppModule and DynamicTestModule. The suggestion is to consider moving SearchCompo ...

TS2688 Error: Type definition file for 'keyv' is missing

The automated code build process failed last night, even though I did not make any changes related to NPM libraries. The error message I received was: ERROR TS2688: Cannot find type definition file for 'keyv'. The file is in the program because: ...

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

What is the best approach to validating GraphQL query variables while utilizing Mock Service Worker?

When simulating a graphql query with a mock service worker (MSW), we need to verify that the variables passed to the query contain specific values. This involves more than just type validation using typescript typings. In our setup, we utilize jest along ...

Completely turn off type checking for all files within the *.test.* extension, including imported components

"exclude": ["*.test.ts", "*.test.tsx"] in the tsconfig file only stops type checking for test-specific types like describe, it, expect, etc. However, errors still appear for imported Components in every test file in vscode. The only way to remove these err ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Tips for obtaining type narrowing for a function within a mixed array

In my coding adventure, I have crafted a brilliant match function. This function is designed to take a value along with an array of [case, func] pairs. The value is then compared to each case, and if a match is found, the associated func is executed with t ...

Angular time-based polling with conditions

My current situation involves polling a rest API every 1 second to get a result: interval(1000) .pipe( startWith(0), switchMap(() => this.itemService.getItems(shopId)) ) .subscribe(response => { console.log(r ...

What is the process for obtaining a flattened tuple type from a tuple comprised of nested tuples?

Suppose I have a tuple comprised of additional tuples: type Data = [[3,5,7], [4,9], [0,1,10,9]]; I am looking to develop a utility type called Merge<T> in such a way that Merge<Data> outputs: type MergedData = Merge<Data>; // type Merged ...

Steps for calculating the average of several columns within a table using Angular 10

Currently, I have a function that successfully calculates the sum of JSON data in all columns on my tables. However, my attempt to get the average of each column is resulting in NaN or infinity. What could be the issue here? Here is my current implementat ...

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

The error message "Type 'string | number' is not assignable to type 'number'" indicates a type mismatch in the code, where a value can be either

I encountered an error code while working with AngularJS to create a countdown timer. Can someone please assist me? //Rounding the remainders obtained above to the nearest whole number intervalinsecond = (intervalinsecond < 10) ? "0" + intervalinseco ...