Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果我以前调用testBed.get(),是否必须在单元测试中注入服务?_Javascript_Angular_Unit Testing_Jasmine_Karma Jasmine - Fatal编程技术网

Javascript 如果我以前调用testBed.get(),是否必须在单元测试中注入服务?

Javascript 如果我以前调用testBed.get(),是否必须在单元测试中注入服务?,javascript,angular,unit-testing,jasmine,karma-jasmine,Javascript,Angular,Unit Testing,Jasmine,Karma Jasmine,我在angular 2单元测试中使用了一个服务 我首先使用TestBed.get()调用beforeach块中的服务 示例: beforeEach(() => { fixture = TestBed.createComponent(ConfigComponent); component = fixture.componentInstance; service = TestBed.get(ConfigService); fixture.detectChang

我在angular 2单元测试中使用了一个服务

我首先使用TestBed.get()调用beforeach块中的服务

示例

 beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });
 it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));
然后,我在单元测试中使用此服务,如下所示:

示例

 beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });
 it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));
如果以前调用过,我是否需要在单元测试中注入服务,还是只需要调用TestBed.get()并跨平台使用它,还是应该两者都使用?

如中所述,
inject
TestBed.get
是类似的,因此这是一个风格问题。所有规范共有的一些服务可以分配给变量,而特定于特定规范的服务只能在这些规范中注入

如果spec函数依赖于
inject
而不是局部变量,则它不必在当前
descripe
块的范围内定义,并且可以重用或移动到某个辅助函数

应该注意的是,injector实例是在第一个
Injection
函数或
TestBed上创建的。get
调用,它们的使用方式可以改变结果