How to mock environment files import in unit tests

前端 未结 3 1356
花落未央
花落未央 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

提交回复
热议问题