如果我先前测试testBed.get(),是否必须在单元测试中注入服务? [英] Do I have to inject the service in the unit test if I cal testBed.get() previously?

查看:322
本文介绍了如果我先前测试testBed.get(),是否必须在单元测试中注入服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,我正在使用我的角度2单元测试。



我首先使用TestBed.get()调用beforeEach块中的服务/ p>

示例

  beforeEach(( )=> {
fixture = TestBed.createComponent(ConfigComponent);
component = fixture.componentInstance;
service = TestBed.get(ConfigService);
fixture.detectChanges() ;
});

然后我在单元测试中使用此服务,如下所示:



示例

  it('应该做点什么',注入([ ConfigService],(configService)=> {
//此处代码
}));

我是否需要在单元测试中注入服务如果之前调用过,或者我是否需要调用TestBed.get()并使用它或者我应该同时使用它吗?

解决方案

正如在这个答案注入 TestBed.get 类似,所以这是一个风格问题。所有规格通用的某些服务可以分配给变量,而特定规格的服务只能在这些规格中注入。



在spec的情况下函数依赖于 inject 而不是局部变量,它不必在当前描述的范围内定义阻止并可以重用或移动到某个辅助函数。



应该注意到,第一个 inject 函数或 TestBed.get 调用,它们的使用方式可能会改变结果。


I have a service which I'm consuming in my angular 2 unit test.

I call the service in the beforeEach block first with TestBed.get()

Example:

 beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });

I then use this service in the unit test like this:

Example:

 it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));

Do I need to inject the service in the unit test If called previously, or do I need to just call TestBed.get() and the use it across or should I do both?

解决方案

As it's explained in this answer, inject and TestBed.get are similar, so it's a matter of style. Some services that are common to all specs can be assigned to variables, while services that are specific to particular specs can be injected only in those specs.

In the case when spec function relies on inject and not local variables, it doesn't have to be necessarily defined in the scope of current describe block and can be reused or moved to some helper function.

It should be noticed that injector instance is created on first inject function or TestBed.get call, the way they are used can alter the results.

这篇关于如果我先前测试testBed.get(),是否必须在单元测试中注入服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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