mongoose.connect is not a function when running tests
alsoicode opened this issue · 0 comments
alsoicode commented
I would like to create an e2e test for a module that is reliant on MongooseService.
When I run my test:
// mongoose.service.ts
import { Component, Logger } from '@nestjs/common';
import * as mongoose from 'mongoose';
@Component()
export class MongooseService {
private readonly logger = new Logger(MongooseService.name);
private instance: mongoose.Connection;
constructor() {
(mongoose as any).Promise = global.Promise;
}
get connection() {
if (this.instance) {
return this.instance;
}
else {
mongoose.connect(process.env.MONGODB_URI, { useMongoClient: true });
this.instance = mongoose.connection;
this.instance.on('error', (e: Error) => {
this.logger.error('MongoDB conenction error:' + e);
});
this.instance.once('open', () => {
this.logger.log('Successful MongoDB Connection');
});
return this.instance;
}
}
}
// unsubscribes.module.ts
import { UnsubscribeRequestModel } from './unsubscribes.model';
@Module({
modules: [
SharedModule,
],
controllers: [
UnsubscribesController,
],
components: [
UnsubscribeRequestModel,
],
exports: [
UnsubscribeRequestModel,
],
})
export class UnsubscribesModule {
public configure(consumer: MiddlewaresConsumer) {
consumer
.apply(PassportMiddleware)
.forRoutes(UnsubscribesController);
}
}
// unsubscribes.spec.ts
describe('Controller', () => {
beforeAll(async () => {
const unsubscribesModule = await Test.createTestingModule({
modules: [
SharedModule,
UnsubscribesModule,
],
}).compile();
const app = unsubscribesModule.createNestApplication(server);
await app.init();
});
it('should not throw an exception', async () => {
expect(true).toBe(true);
});
});
I always get "mongoose.connect is not a function". I've tried manually providing the value in the components
:
components: [{ provide: MongooseService, useValue: mongoose }],
and
components: [{ provide: 'MongooseService', useFactory: () => new MongooseService(), inject: [MongooseService] }],
but am coming up short. Any helpful hints?