如何在nestjs测试中覆盖导入的模块?

Jef*_*ian 5 typescript nestjs nestjs-config

我对 很陌生nestjs,遇到了有关如何覆盖load功能的问题ConfigModule,希望有人可以帮助我,提前致谢!

我的端到端测试:

const moduleForTesting = await Test.createTestingModule({imports: [AppModule]});
Run Code Online (Sandbox Code Playgroud)

我的应用程序模块:

import config from './config/index'

@Module({
  imports: [ConfigModule.forRoot({isGlobal: true, load: [config]})]
})
Run Code Online (Sandbox Code Playgroud)

我的config/index文件:

export default async () => {
  someConfigs: ...
}
Run Code Online (Sandbox Code Playgroud)

现在我希望 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]})]
Run Code Online (Sandbox Code Playgroud)

Jef*_*ian 1

我不知道 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]});

Run Code Online (Sandbox Code Playgroud)