Overriding providers in NestJS Jest tests

为君一笑 提交于 2019-12-04 10:55:30

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!