Angular 2 testing - process.env

北战南征 提交于 2019-12-07 22:24:19

问题


I try to mock requests in my application, but there is a problem with process variable. I store in process.env.backendUrl url to backend API. And then in RestService I have:

constructor(private http: Http) {
    this.rest = process.env.backendUrl + "/api/";
}

And now it is impossible to run tests because in for example LoginComponent I have RestService dependency and I've got this error:

zone.js:140 Uncaught Error: Error in ./LoginComponent class LoginComponent_Host - inline template:0:0 caused by: process is not defined
ReferenceError: process is not defined
at new RestService (http://localhost:9876/base/src/test.ts:21595:2790)
at DynamicTestModuleInjector.get (DynamicTestModule.ngfactory.js:170:67)
at DynamicTestModuleInjector.get (DynamicTestModule.ngfactory.js:180:93)
at DynamicTestModuleInjector.getInternal (DynamicTestModule.ngfactory.js:255:51)
at DynamicTestModuleInjector.NgModuleInjector.get (http://localhost:9876/base/src/test.ts:25036:27)
at TestBed.get (http://localhost:9876/base/src/test.ts:5589:51)
at _View_LoginComponent_Host0.createInternal (LoginComponent_Host.ngfactory.js:16:74)
at _View_LoginComponent_Host0.AppView.create (http://localhost:9876/base/src/test.ts:36192:21)
at _View_LoginComponent_Host0.DebugAppView.create (http://localhost:9876/base/src/test.ts:36404:44)

I set proccess.env.backendUrl in enviroment.ts (file created by angular-cli).

process.env.backendUrl = 'http://localhost:8080';

export const environment = {
  production: false
};

Should I set it somewhere else or is there any method to tell karma about this variable?


回答1:


If you're using angular-cli, you should just add the backendUrl to the environment.

export const environment = {
  production: false,
  backendUrl: 'http://localhost:8080'
};

You should also add it in the environment.prod.ts file, setting the url to the production url. When you build in production, the .prod file will be used.

In your files, you should import the environment (from the environment.ts file) and just use environment.backendUrl.

See Also:

  • Build Targets and Environment Files


来源:https://stackoverflow.com/questions/40424199/angular-2-testing-process-env

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