9

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

RemeJuan
  • 823
  • 9
  • 25
  • Have you taken a look at the [docs on testing request scoped services](https://docs.nestjs.com/fundamentals/testing#testing-request-scoped-instances)? – Jay McDoniel Aug 24 '20 at 14:23
  • 3
    @JayMcDoniel, yeah, but with 5 lines of code and no apparent context around how to actually use, it does not get one very far. – RemeJuan Aug 24 '20 at 15:50
  • 1
    What is JestRequest()? Did you created it yourself or is part of the Jest dependency? – Cedric Achi Mar 24 '22 at 09:11
  • 1
    @CedricAchi I can only assume it's part of their dependencies or another package, have not touched this project or JS for that matter in over a year. – RemeJuan Mar 25 '22 at 10:06

1 Answers1

9

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);
  });
adamC
  • 235
  • 1
  • 4