0
votes

I'am new using Node and Nest framework, and I have a problem when testing modules that import a Custom Config Module that uses Joi to validate env vars:

yarn test
 
Test suite failed to run 
Config validation error: "APP_PORT" is required

app-config.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      expandVariables: true,
      load: [configuration],
      validationSchema: Joi.object({
        APP_PORT: Joi.number().required()
      }),
    }),
  ],
  providers: [AppConfigService],
  exports: [AppConfigService],
})
export class AppConfigModule { }

app.config.ts

import { registerAs } from '@nestjs/config';

export default registerAs('app', () => ({
    env: process.env.NODE_ENV,
    port: process.env.APP_PORT || 3000
...
}));

invoice.service.spec.ts

describe('InvoiceService', () => {
  let service: InvoiceService;

  beforeEach(async () => {
    
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          load: [configuration],
          ignoreEnvFile: true,
        }),
        AppConfigModule        
      ],
      providers: [
        InvoiceService,
        ....
      ],
    }).compile();

    service = module.get<InvoiceService>(InvoiceService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

I use env file to deploy locally, and I only set up ignoreEnvFile: true in test class because env file is ignore from github repo, and project integrate github actions that run unit test.

How is the best way to solved this problem? I would not like add env file to repo. Exist any way to disable/fake/mock Joi validation method. I saw some examples using setupFiles but I'm not sure if it's a good practice.

1

1 Answers

1
votes

May you please show the package.json file? you must have installed npm i --save @nestjs/config then create .env file inside root directory. Moreover you should import that into you app module.

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: ".development.env",
    }),
  ],
})

export class AppModule {}

Ref: https://docs.nestjs.com/techniques/configuration