Ng test No provider for Http! error

I am trying to run tests for my Angular2 application. I have not done mockingingservices yet, so I try to use my usual service.

exact error:

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]

The component of the component I want to test:

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

I tried to import the HTTPModule into the spec.ts (test) class, but I cannot get it to work. here is the code 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();
  });
});

I also tried this with test class providers:

providers: [{ provide: Http, useValue: GameBoardService }]
+4
source share
1 answer

You still need to provide HTTP to your test class, and you most likely want to use MockBackend for this.

These are the lines that I think you need to add.

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

In your providers of your TestBed.configureTestingModule:

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

Source: https://habr.com/ru/post/1678251/


All Articles