How to mock environment files import in unit tests

一曲冷凌霜 提交于 2019-12-05 15:44:15

问题


In our angular app, we use environment files to load some config.

environment.ts

export const environment = {
  production: false,
  defaultLocale: 'en_US',
};

We then use it in one of our service:

import { environment } from '../../environments/environment';
import { TranslateService } from './translate.service';

@Injectable()
export class LocaleService {
  constructor(private translateService: TranslateService){}

  useDefaultLocaleAsLang(): void {
    const defaultLocale = environment.defaultLocale;
    this.translateService.setUsedLang(defaultLocale);
  }
}

So I use the values in environment file in a service method.

In our test file, we can of course Spy on the translateService:

translateService = jasmine.createSpyObj('translateService', ['setUsedLang']);

But I don't know how to mock the environment values in my testing file (in a beforeEach for example). Or even transform it, for testing purpose, to a Subject so I can change it and test different behaviors.

More generally speaking, how can you mock such imports values in tests to be sure not to use real values?


回答1:


You can't test/mock environment.ts. It is not part of Angular's DI system, it is a hard dependency on a file on the filesystem. Angular's compilation process is what enables swapping out the different environment.*.ts files under the hood when you do a build.

Angular's DI system is a typical Object Oriented approach for making parts of your application more testable and configurable.

My recommendation would be to take advantage of the DI system and use something like this sparingly

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

Instead do what Angular does for these dependencies it wants you to be abstracted away from. Make a service that provides a seam between the environment.ts data and your application pieces.

It doesn't need to have any logic, it could simply pass through the properties of environment directly (therefore it wouldn't need tested itself).

Then in your services/components that depend on environment.ts at runtime you can use the service and at test time you can mock it, sourcing the data from somewhere other than environment.ts




回答2:


A technique I use in situations like this is to create a wrapper service e.g. EnvironmentService.ts and in this case it returns the environment configuration.

This allows me to mock calls to the EnvironmentService's getEnvironmentConfiguration method just like any other spyOn call.

This then allows for the modification of environment variables in unit tests :)



来源:https://stackoverflow.com/questions/49091393/how-to-mock-environment-files-import-in-unit-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!