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 mongoos
As specified in the docs https://docs.nestjs.com/fundamentals/unit-testing you can override the provider with a value, factory or class.
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [EventsModule, DatabaseModule],
providers: [
EventsService,
],
}).overrideProvider('DbConnectionToken')
.useFactory({
factory: async (): Promise<typeof mongoose> =>
await mongoose.connect(IN_MEMORY_DB_URI),
})
.compile();
eventService = module.get<EventsService>(EventsService);
});
An alternative would be to make a provider for your configs :) Like so!
@Module({})
export DatabaseModule {
public static forRoot(options: DatabaseOptions): DynamicModule {
return {
providers: [
{
provide: 'DB_OPTIONS',
useValue: options,
},
{
provide: 'DbConnectionToken',
useFactory: async (options): Promise<typeof mongoose> => await mongoose.connect(options),
inject: ['DB_OPTIONS']
},
],
};
}
}
Then use like this
const module: TestingModule = await Test.createTestingModule({
imports: [DatabaseModule.forRoot({ host: 'whatever'})],
});
Now you're able to change the options wherever you're using it :)