Angular 2测试-process.env [英] Angular 2 testing - process.env

查看:186
本文介绍了Angular 2测试-process.env的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在应用程序中模拟请求,但是流程变量存在问题.我将process.env.backendUrl网址存储在后端API中.然后在RestService中,我有:

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/";
}

现在无法运行测试,因为例如在LoginComponent中,我具有RestService依赖性,并且出现此错误:

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)

我在enviroment.ts(由angular-cli创建的文件)中设置了 proccess.env.backendUrl .

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?

推荐答案

如果您正在使用angular-cli,则只需将backendUrl添加到environment.

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

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

您还应该将其添加到environment.prod.ts文件中,并将URL设置为生产URL.在生产环境中构建时,将使用.prod文件.

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.

在文件中,您应该导入environment(从environment.ts文件中)并仅使用environment.backendUrl.

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

另请参见:

这篇关于Angular 2测试-process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆