typescriptunit-testingdependency-injectionjestjsnestjs

Request scoped injection is not getting mocked


I am trying to mock the return value of a provider, but for some reason, it's clearing out the mock.

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();
});

But, the mock is not happening. Am I doing something wrong?


Solution

  • There's no chance for service1.getVal to not be mocked, the mock is very straightforward. That it doesn't affect service2.someFn() means that service2 doesn't use the same Service1 instance as the one that was mocked.

    As the documentation states:

    REQUEST

    A new instance of the provider is created exclusively for each incoming request. The instance is garbage-collected after the request has completed processing.

    This means that Service1 instances are unique. The one that belongs to Service2 needs to be mocked:

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