How to mock environment files import in unit tests

前端 未结 3 1311
花落未央
花落未央 2021-02-19 13:11

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

environment.ts

export const environment = {
  production: false,
  defaultLocale: \'en         


        
相关标签:
3条回答
  • 2021-02-19 13:18

    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

    0 讨论(0)
  • 2021-02-19 13:34

    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 :)

    0 讨论(0)
  • 2021-02-19 13:38

    Something like this worked for me:

    it('should test', () => {
      environment.defaultLocale = <location-to-test>;
    
      const result = service.method();
    
      expect(result).toEqual(<expected-result>);
    });
    
    0 讨论(0)
提交回复
热议问题