Search code examples
javascripttypescriptenvironment-variablesnestjs

Nest environment variable undefined


I am following the official documentation on the NestJs website that shows how to get started with config files: https://docs.nestjs.com/techniques/configuration

I have the following code:

app.module

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

import { AppController } from './app.controller';
import { AppService } from './app.service';

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

app.controller

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getTest(): string {
    return this.appService.getTest();
  }
}

app.service

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

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

  getTest(): string {
    console.log(this.configService);

    return this.configService.get<string>('TEST_VAR');
  }
}

app.controller.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigService } from '@nestjs/config';

describe('AppController', () => {
  let appController: AppController;

  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      controllers: [AppController],
      providers: [ConfigService, AppService],
    }).compile();

    appController = app.get<AppController>(AppController);
  });

  describe('Test variable', () => {
    it('should return "ASD"', () => {
      expect(appController.getTest()).toBe('ASD');
    });
  });
});

The .env file is defined as follows:

TEST_VAR=ASD

Running npm run test will show that the test failed because with

Expected: "ASD"
Received: undefined

I have tried looking at other answers with no success. The only one that was similar was this one: NestJS env variable undefined which has an accepted answer, but it gives multiple options which I have tried and none work.

  1. I have the .env file.
  2. I have tried placing the .env file both in the root of the project and in the src directory.
  3. Since the .env is inside the project files it should be accessible
  4. I have run npm i --save dotenv
  5. I am running on my local machine

Solution

  • you didn't import the config module in your testing module, which is the one that will load the dot env file. The ConfigService by itself doesn't do anything.

    I'd suggest you to use fake doubles instead of importing the config module, tho. See: Advanced Testing Strategies with Mocksin NestJS