Angular 4单元测试,但收到错误没有Http的提供者

时间:2018-02-09 16:33:45

标签: javascript angular unit-testing

我试图学习如何在角度4上运行单元测试组件,但是我没有成功,当我使用下面的代码运行测试时出现此错误:

  

错误:http没有提供商!和失败::   无法找到一个对象来监视filexGeneralData()

我不知道我是否正确的方式......

看看我的代码

我的规范文件



import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';

import { of } from 'rxjs/observable/of';
import { filex } from '../../../models/filex';
import { filexService } from '../../../services/filex.service';
import { fileyfilexComponent } from './filey-filex.component';
import { dataService } from '../../../services/data.service';

describe('fileyfilexComponent', () => {
  let filexService;
  let myComponent;
  let fixture;
  let element;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        declarations: [fileyfilexComponent],
        providers: [filexService, dataService],
        imports: [HttpModule]
      }).compileComponents();
    })
  );

  beforeEach(inject([filexService], s => {
      filexService = s;
      fixture = TestBed.createComponent(fileyfilexComponent);
      myComponent = fixture.componentInstance;
      element = fixture.nativeElement;
    }));

  it(
    'should call getUsers and return list of users',
    async(() => {
      const response: filex[] = [];

      spyOn(filexService, 'filexGeneralData').and.returnValue(of(response));

      myComponent.method1();

      fixture.detectChanges();

      expect(myComponent.datafilex).toEqual(response);
    })
  );
});




1 个答案:

答案 0 :(得分:1)

您只需在HubWrapperComponent中加入TestBed即可。在providers数组中,您需要包含提供给正在测试的组件的所有服务(更好的是,您应该提供"模拟"这些服务的版本)。所以,你可以把错误带到"走开"只需将HubWrapperComponent添加到providers文件的spec方法中的TestBed.configureTestingModule数组即可。最终看起来像这样:

spec.ts

TestBed.configureTestingModule({
    declarations: [IndicatorsDashboardComponent],
    providers: [DashboardService, DadosService, HubWrapperComponent],
    imports: [HttpModule]
  }).compileComponents();

另外一条建议:我建议使用jasmine来模拟你的HubWrapperComponent(这似乎是HttpClient的包装?)。

mockWrapper = jasmine.createSpyObj('http', ['get']);

然后在你的providers数组中:

{provide: HubWrapperComponent, useValue: mockWrapper}

这种方法看起来像这样:

  let mockHub: SpyObj<HubWrapperComponent>;

  beforeEach(
    async(() => {
      mockHub = jasmine.createSpyObj('http', ['get']);

      TestBed.configureTestingModule({
        declarations: [IndicatorsDashboardComponent],
        providers: [
          DashboardService, 
          DadosService,
          { provide: HubWrapperComponent, useValue: mockHub }
        ],
        imports: [HttpModule]
      }).compileComponents();
    })
  );

首选模拟服务/进行Http次呼叫的任何内容都是首选,因为您不希望在测试中发出实际请求。