angularunit-testingmockingkarma-jasmine

Angular test how to mock an imported const


I have an angular service being tested, which import a const from another file

import { environment } from "../environments/environment";

The environment.ts is like

export const environment = {
    ...window.mainConfig,
    production: false
};

window.mainConfig is an electron context bridge exposed variable. It is undefined in ng test context so I have to mock it.

I tried the following

import * as environment from '../environments/environment';

describe("...",()=>{
  beforeEach(() => {
    //...
    spyOnProperty(environment,"environment","get").and.returnValue({/* ... */});
    //...
  });
});

But this gives Error: <spyOnProperty> : environment is not declared configurable. How do I mock this correctly?


Solution

  • Could you try Object.assign to override the internal properties with the new properties.

    Object.assign(environment, {/* ... */});
    

    If not you can run a loop across the properties and assign the values manually also.

    const mockEnv = {/* ... */};
    
    for (const [key, value] of Object.entries(mockEnv)) {
      environment[key] = value;
    }
    

    The most ideal solution is to configure in the angular.json, the environment replacement, for testing environment. This will be configured when you start testing.

    "test": {
      ...
      "options": {
        ...
        "fileReplacements": [{
          "replace": "src/environments/environment.ts",
          "with": "src/environments/environment.tst.ts"
        }],
        ...
    

    Reference Answer