问题描述
我是 nestjs
的新手,遇到了一个关于如何覆盖 load
的 ConfigModule
函数的问题,希望有人能帮助我,在此先感谢!
我的 e2e 测试:
const moduleForTesting = await Test.createTestingModule({imports: [AppModule]});
我的应用模块:
import config from './config/index'
@Module({
imports: [ConfigModule.forRoot({isGlobal: true,load: [config]})]
})
export default async () => {
someConfigs: ...
}
现在我希望 e2e 测试使用其他配置,但我不知道如何覆盖 AppModule,也不知道如何覆盖 load
函数:
// AppModule
import config from './config/index' // This is ok for production,but need to be overridden in testing
...
imports: [ConfigModule.forRoot({isGlobal: true,load: [config]})]
解决方法
我不知道 NestJs 的优雅方式是什么,但深呼吸后,我重新考虑了我真正想做的事情,然后找到了实现这一目标的 hackie 方式。
我需要模拟 config
文件,以便在测试过程中模拟 load
数组,而 jest.mock
可以派上用场:
// e2e testing file
jest.mock('../src/config/index',() => ({
default: async () => ({
someConfigs: 'mocked config'
})
})) // <--- By putting the `jest.mock` before the `createTestingModule`,the `load` array will be mocked.
...
const moduleForTesting = await Test.createTestingModule({imports: [AppModule]});