使用@Injectable Scope / @Inject(REQUEST) NestJS 测试 Class

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

我已经设置了一个 MongooseConfigService 以允许我们为某些请求动态切换连接字符串,并且正在尝试正确设置测试。

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

但是,我无法向测试上下文提供 request

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

据我所知,在没有 inject 和 with/without useValue 的情况下尝试过,但是 this.request 在尝试 [=26] 时仍然未定义=] 测试。

TIA

也许可以尝试仅使用 import: [appModule] 实例化测试模块,然后尝试获取服务。另外,尝试像这样使用 overrideprovider 和 usevalue:

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