gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:01:26 27 4
gpt4 key购买 nike

我是 nestjs 的新手,遇到了一个关于如何覆盖 ConfigModuleload 函数的问题,希望有人能帮助我出来,提前致谢!

我的端到端测试:

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

关于typescript - 如何在 nestjs 测试中覆盖导入的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67194776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com