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

问题描述

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

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

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...