I want to use an in-memory Mongo instance to mock data for testing purposes in my NestJS application. I have a database provider which connects to my production db using mongoose, which is part of my database module, which in turn gets imported into other modules.
I am trying to override the database provider within my Jest tests so I can use the in-memory Mongo instance.
This is the database module:
import { Module } from '@nestjs/common';
import { databaseProviders } from './database.providers';
@Module({
providers: [...databaseProviders],
exports: [...databaseProviders],
})
export class DatabaseModule { }
and the databaseProvider:
export const databaseProviders = [
{
provide: 'DbConnectionToken',
useFactory: async (): Promise<typeof mongoose> =>
await mongoose.connect(PRODUCTION_DATABASE_URL),
},
];
I have an Events module which imports and uses the database connection from the database module the Events service is what I am testing - the beforeEach in my events.spec.ts:
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [EventsModule],
providers: [
EventsService,
{
provide: 'EventModelToken',
useValue: EventSchema
},
],
}).compile();
eventService = module.get<EventsService>(EventsService);
});
I tried importing the DatabaseModule into the testing module and then adding my custom provider assuming it would override the database provider, but it doesn't work as I expected so I fear I may misunderstand how overriding providers works in this context.
This is what I tried:
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [EventsModule, DatabaseModule],
providers: [
EventsService,
{
provide: 'EventModelToken',
useValue: EventSchema
},
{
provide: 'DbConnectionToken',
useFactory: async (): Promise<typeof mongoose> =>
await mongoose.connect(IN_MEMORY_DB_URI),
},
],
}).compile();
eventService = module.get<EventsService>(EventsService);
});