Search code examples
angulartypescriptangular-test

Angular undefined error while running ng test with environment.ts


I have environment.ts in project to set env data from kubernate yaml.

export const environment = {
  PROD_URL: window["env"].prodUrl || 'http://localhost:8080/v1/'
};

While running ng test , I am getting below error.

An error was thrown in afterAll
  Uncaught TypeError: Cannot read property 'prodUrl ' of undefined
  TypeError: Cannot read property 'prodUrl ' of undefined
      at Module.AytR (http://localhost:9876/_karma_webpack_/webpack:/src/environments/environment.ts:9:30)

Solution

  • window["env"] can be null/undefined. For that case just use optional chaining.

    export const environment = {
      PROD_URL: window["env"]?.prodUrl || 'http://localhost:8080/v1/'
    };