Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS - Mongoose @InjectConnection unit testing

I have a service that uses the @InjectConnection decorator in it's constructor.

I am unable to instantiate a testingModule for this service. The following error is thrown: Nest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context.

Service constructor:

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

Test module constructor:

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

I realize that I will have to mock the connection object to be callable by GridFS, but right now I am unable to actually get the test module to build.

like image 957
pantera Avatar asked Feb 22 '19 15:02

pantera


1 Answers

When you do not add an explicit connection name, nest.js will use the default connection token DatabaseConnection, which is defined as a constant by the nestjs-mongoose package:

export const DEFAULT_DB_CONNECTION = 'DatabaseConnection';

So you can use getConnectionToken('Database'):

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

Update 2019

The pull request was merged. You can now getConnectionToken().

I have created a pull request which lets getConnectionToken() without any parameters return the default connection token.

like image 52
Kim Kern Avatar answered Nov 08 '22 03:11

Kim Kern