簡體   English   中英

NestJS - Mongoose @InjectConnection單元測試

[英]NestJS - Mongoose @InjectConnection unit testing

我有一個在它的構造函數中使用@InjectConnection裝飾器的服務。

我無法為此服務實例化testingModule。 拋出以下錯誤: Nest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context. Nest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context.

服務構造函數:

  constructor(@InjectConnection() private readonly mongooseConnection: Mongoose,
              @Inject(Modules.Logger) private readonly logger: Logger) {
    this.attachmentGridFsRepository = gridfs({
      collection: 'attachments',
      model: Schemas.Attachment,
      mongooseConnection: this.mongooseConnection,
    });

    this.attachmentRepository = this.attachmentGridFsRepository.model;
  }

測試模塊構造函數:

const module: TestingModule = await Test.createTestingModule({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new transports.Console({
          level: 'info',
          handleExceptions: false,
          format: format.combine(format.json()),
        }),
      ],
    }),
  ],
  providers: [AttachmentsService, {
    provide: getConnectionToken(''),
    useValue: {},
  }],
}).compile();

service = module.get<AttachmentsService>(AttachmentsService);

我意識到我必須模擬連接對象才能被GridFS調用,但是現在我無法實際構建測試模塊。

如果不添加顯式連接名稱,nest.js將使用默認連接標記 DatabaseConnection ,它由nestjs-mongoose包定義為常量:

export const DEFAULT_DB_CONNECTION = 'DatabaseConnection';

所以你可以使用getConnectionToken('Database')

providers: [AttachmentsService, {
  provide: getConnectionToken('Database'),
  useValue: {},
}]

更新2019年

拉取請求已合並。 你現在可以getConnectionToken()

我創建了一個pull請求 ,它允許不帶任何參數的getConnectionToken()返回默認連接令牌。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM