【问题标题】:How to override an imported module in nestjs testing?如何在 Nestjs 测试中覆盖导入的模块?
【发布时间】:2021-07-15 14:02:45
【问题描述】:

我是nestjs 的新手,遇到了关于如何覆盖ConfigModuleload 函数的问题,希望有人能帮助我,在此先感谢!

我的 e2e 测试:

const moduleForTesting = await Test.createTestingModule({imports: [AppModule]});

我的应用模块:

import config from './config/index'

@Module({
  imports: [ConfigModule.forRoot({isGlobal: true, load: [config]})]
})

我的config/index 文件:

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]})]

【问题讨论】:

  • 这是否回答了您的问题:stackoverflow.com/questions/52095261/…?
  • 谢谢@milo526,但我仍然不知道该怎么做。因为你提供的链接好像用overrideProvider,但我需要overrideModule,哪个方法不存在。

标签: typescript nestjs nestjs-config


【解决方案1】:

参见TestModuleBuilder 中的withModule 方法,来自@jbiskur/nestjs-test-utilities

NestJS 功能请求:https://github.com/nestjs/nest/issues/4905

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2012-09-11
      • 2019-02-05
      相关资源
      最近更新 更多