ng test没有Http的提供者!错误

时间:2017-05-31 10:40:39

标签: angular karma-jasmine

我尝试为我的Angular2应用程序进行测试。我还没有制作模拟服务,所以我尝试使用我的正常服务。

确切的错误:

Error: No provider for Http!
    at injectionError (http://localhost:9876/base/src/test.ts:1538:86) [angular]
    at noProviderError (http://localhost:9876/base/src/test.ts:1576:12) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_._throwOrNull (http://localhost:9876/base/src/test.ts:3077:19) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_._getByKeyDefault (http://localhost:9876/base/src/test.ts:3116:25) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_._getByKey (http://localhost:9876/base/src/test.ts:3048:25) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_.get (http://localhost:9876/base/src/test.ts:2917:21) [angular]
    at DynamicTestModuleInjector.Array.concat.NgModuleInjector.get (http://localhost:9876/base/src/test.ts:3864:52) [angular]

我要测试的组件的@component是:

@Component({
  selector: 'app-game-board',
  templateUrl: './game-board.component.html',
  styleUrls: ['./game-board.component.css'],
  providers: [GameBoardService]
})

我尝试在spec.ts类(测试)中导入HTTPModule,但我无法让它工作。这是spec.ts的代码

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { GameBoardComponent } from './game-board.component';
import { GameBoardService } from "app/services/gameboardservice";

describe('GameBoardComponent', () => {
  let component: GameBoardComponent;
  let fixture: ComponentFixture<GameBoardComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule], //this is where I try to import the HttpModule
      declarations: [ GameBoardComponent ],
      providers: [GameBoardService]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(GameBoardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

我也在测试类的提供者中尝试过这个:

providers: [{ provide: Http, useValue: GameBoardService }]

1 个答案:

答案 0 :(得分:9)

您仍然需要为测试类提供HTTP,并且您可能希望使用MockBackend。

这是我认为你需要添加的行。

import { MockBackend } from '@angular/http/testing';
import { HttpClient } from '@angular/common/http';

在TestBed.configureTestingModule的提供程序中:

providers: [
  {provide: HttpClient, deps: [MockBackend]},
  ...
],