Overriding providers in NestJS Jest tests

前端 未结 1 488
[愿得一人]
[愿得一人] 2021-02-08 10:58

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

相关标签:
1条回答
  • 2021-02-08 11:24

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

    0 讨论(0)
提交回复
热议问题