0

I have created a Nestjs server and loading configs using .env file

  ConfigModule.forRoot({
    isGlobal: true,
    envFilePath: [`../.env.${process.env.NODE_ENV}`, '../.env'],
  }),

I have e2e test cases and need to test a condition on different values for same key in ConfigService Is there any options to change value of a key?

Midhun G S
  • 906
  • 9
  • 22

2 Answers2

0

Credits: Micael Levi

import { createMock, DeepMocked } from '@golevelup/ts-jest';

let mockConfigService: DeepMocked<ConfigService>
let app: INestApplication;

// Before Each
 const moduleRef = await Test.createTestingModule({
    providers: [
      {
        provide: ConfigService,
        useValue: createMock<ConfigService>(),
      },
    ],
  }).compile();

  app = moduleRef.createNestApplication();

  // Other configs

  await app.init();

  mockConfigService = moduleRef.get(ConfigService)

// it(...)
  jest.spyOn(mockConfigService, 'get').mockImplementation((key: string) => {
    if (key === 'KEY_To_BE_MOCKED') {
      return 'true';
    } else {
      return process.env[key];
    }
  });

Midhun G S
  • 906
  • 9
  • 22
0

if mocking is a headache you can always go for the "hacky" solution and manually modify the internals of the service object.

example:

config.get('someKey'); // 'original'
config.internalConfig['someKey'] = 'mockValue'; // the hacky act
config.get('someKey'); // 'mockValue'

then you can use the same object and modify it with beforeEach and afterEach or however you see fit in your tests

Hagai Kalinhoff
  • 606
  • 3
  • 10