Search code examples
typescriptnestjsnestjs-config

How to override an imported module in nestjs testing?


I'm quite new on nestjs, met an issue regarding how to override the load function of ConfigModule, hope someone can help me out, thanks in advance!

My e2e testing:

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

My App Module:

import config from './config/index'

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

My config/index file:

export default async () => {
  someConfigs: ...
}

Now I want the e2e testings use another configurations, but I don't know how to override the AppModule, nor the load function:

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

Solution

  • I don't know what is the elegant NestJs way to do that, but after a deep breath, I reconsidered what I really want to do and then found a hackie way to achieve that.

    I need to mock the config file so that during testing, the load array will be mocked, where the jest.mock comes to the rescue:

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