nestjsnestjs-testing

Testing Class with @Injectable Scope / @Inject(REQUEST) NestJS


I have set up a MongooseConfigService to allow us to dynamically switch out the connection string for certain requests and am trying to get the tests set up correctly.

@Injectable({scope: Scope.REQUEST})
export class MongooseConfigService implements MongooseOptionsFactory {
  constructor(
    @Inject(REQUEST) private readonly request: Request) {
  }

I am however having trouble providing request to the test context.

  let service: Promise<MongooseConfigService>;
  
  beforeEach(async () => {
    const req = new JestRequest();
    
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        MongooseConfigService,
        {
          provide: getModelToken(REQUEST),
          inject: [REQUEST],
          useFactory: () => ({
            request: req,
          }),
        },
      ],
    }).compile();
    
    service = module.resolve<MongooseConfigService>(MongooseConfigService);
  });

This is as far as I have gotten, have tried it without the inject and with/without useValue, however this.request remains undefined when trying to run the tests.

TIA


Solution

  • maybe try to instantiate the testing module with only import: [appModule] and then try to get the service. also, try to use overrideprovider and usevalue like this:

    let service: Promise<MongooseConfigService>;
      
      beforeEach(async () => {
        const req = new JestRequest();
        
        const module: TestingModule = await Test.createTestingModule({
          imports: [appModule]
        }).overrideProvider(REQUEST)
          .useValue(req)
          .compile();
        
        service = module.resolve<MongooseConfigService>(MongooseConfigService);
      });