4

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]})]
Jeff Tian
  • 5,210
  • 3
  • 51
  • 71
  • Does this answer your question: https://stackoverflow.com/questions/52095261/overriding-providers-in-nestjs-jest-tests? – milo526 Apr 21 '21 at 12:50
  • Thank you @milo526, but I still don't know how to do it. Because the link you provided seems to use `overrideProvider`, but I need to `overrideModule`, which method is not exist. – Jeff Tian Apr 22 '21 at 01:51

3 Answers3

2

See withModule method in TestModuleBuilder from @jbiskur/nestjs-test-utilities

NestJS feature request: https://github.com/nestjs/nest/issues/4905

Joe Bowbeer
  • 3,574
  • 3
  • 36
  • 47
  • 1
    Looks like this is [scheduled](https://github.com/nestjs/nest/pull/8777) for 10.0.0. great work. Will look into it more but do you know off hand what the difference is when using overrideProvider vs specifying a provider in the array when created the testing module ? – Norbert Apr 17 '23 at 17:59
  • Quick search seems like I found it [here](https://stackoverflow.com/questions/69000993/nestjs-overrideprovider-vs-provider-in-unit-testing) – Norbert Apr 17 '23 at 18:01
1

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

Jeff Tian
  • 5,210
  • 3
  • 51
  • 71
0

You can use overridProvider

const moduleForTesting = await Test.createTestingModule({imports: [AppModule]}).overrideProvider(MyService).useValue(myServiceMock).compile()
cgat
  • 3,689
  • 4
  • 24
  • 38