ConfigService is undefined while running testcases in Nest.js

1k views Asked by At

I am running nestjs server locally and if I test with postman it works fine. But when I run testcases, the ConfigService gets undefined!

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({ load: [configuration], isGlobal: true }),
    AppDeployModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

configuration.ts

export default () => ({
  app: {
    baseUrl: 'https://app-deploy.com',
  },
});

app-deploy.controller.spec.ts

describe('AppDeployController', () => {
  let controller: AppDeployController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [AppDeployController],
      providers: [AppDeployService],
      imports: [ConfigModule],
    }).compile();

    controller = module.get<AppDeployController>(AppDeployController);
  });

  it.only('should create an app', async () => {
    const res = await controller.create({ appName: 'Hello World' });
    console.log(res);
  });
});
Here in service file, configService.get('app') is undefined!

app-deploy.service.ts

@Injectable()
export class AppDeployService {
  constructor(private configService: ConfigService) {}

  create(createAppDeployDto: CreateAppDeployDto) {
    console.log(this.configService.get('app')); // Here while running test it gets undefined

    const baseUrl = this.configService.get('app').baseUrl;

    return {
      appName: createAppDeployDto.appName,
      appUrl:
        baseUrl +
        '/' +
        createAppDeployDto.appName.toLowerCase().replace(' ', '-'),
    };
  }
}

This is the result after running test.

FAIL  src/app-deploy/app-deploy.controller.spec.ts
  AppDeployController
    × should create an app (51 ms)

  ● AppDeployController › should create an app

    TypeError: Cannot read properties of undefined (reading 'baseUrl')

      11 |     console.log(this.configService.get('app')); // Here while running test it gets undefined
      12 |
    > 13 |     const baseUrl = this.configService.get('app').baseUrl;
         |                                                  ^
      14 |
      15 |     return {
      16 |       appName: createAppDeployDto.appName,

      at AppDeployService.create (app-deploy/app-deploy.service.ts:13:50)
      at AppDeployController.create (app-deploy/app-deploy.controller.ts:12:34)
      at Object.<anonymous> (app-deploy/app-deploy.controller.spec.ts:20:34)
1

There are 1 answers

0
Mostafa Fakhraei On BEST ANSWER

In your app-deploy.controller.spec.ts, try to change this part of your code:

const module: TestingModule = await Test.createTestingModule({
  controllers: [AppDeployController],
  providers: [AppDeployService],
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
    }),
  ],
}).compile();

controller = module.get<AppDeployController>(AppDeployController);