【问题标题】:NestJS - Mongoose @InjectConnection unit testingNestJS - Mongoose @InjectConnection 单元测试
【发布时间】:2019-07-16 17:11:16
【问题描述】:

我有一个在其构造函数中使用 @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.

服务构造函数:

  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 调用,但现在我无法真正构建测试模块。

【问题讨论】:

    标签: node.js typescript mongoose gridfs nestjs


    【解决方案1】:

    当你不添加显式连接名称时,nest.js 将use the default connection tokenDatabaseConnection,这是由nestjs-mongoose 包定义为常量的:

    export const DEFAULT_DB_CONNECTION = 'DatabaseConnection';
    

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

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

    2019 年更新

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

    我创建了一个pull request,它让getConnectionToken() 不带任何参数返回默认连接令牌。

    【讨论】:

      猜你喜欢
      • 2019-11-22
      • 2020-08-30
      • 2021-01-31
      • 1970-01-01
      • 2016-11-19
      • 2020-11-20
      • 2021-05-29
      • 2019-02-18
      • 2021-02-22
      相关资源
      最近更新 更多