NestJS-猫鼬@InjectConnection单元测试

时间:2019-02-22 15:07:14

标签: node.js typescript mongoose gridfs nestjs

我有一个在其构造函数中使用 override func viewDidLoad() { super.viewDidLoad() if selectedIndex == 1 { observeEnglishCases() } } 装饰器的服务。

我无法为此服务实例化testingModule。引发以下错误:@InjectConnection

服务构造函数:

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

我意识到我将不得不模拟GridFS可以调用的连接对象,但是现在我无法真正构建测试模块。

1 个答案:

答案 0 :(得分:2)

当您不添加显式连接名称时,nest.js将use the default connection token DatabaseConnection,由nestjs-mongoose包定义为常量:

export const DEFAULT_DB_CONNECTION = 'DatabaseConnection';

因此您可以使用getConnectionToken('Database')

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

更新2019

合并请求。您现在可以getConnectionToken()

我创建了一个pull request,它使getConnectionToken()无需任何参数即可返回默认的连接令牌。