Search code examples
angularkarma-jasmineangular-test

Angular 9 - Error: StaticInjectorError[Http]: StaticInjectorError[Http]: NullInjectorError: No provider for Http


I'm new in Angular testing. Now I am trying to test services. When I run ng test for my unit tests, and when those tests use the service, I am getting the error:

Error: StaticInjectorError[Http]:  
StaticInjectorError[Http]: 
NullInjectorError: No provider for Http!

Here is my spec file:

import { TestBed, inject } from "@angular/core/testing";
import { ContactService } from "./contact.service";
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';

describe("ContactService", () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, HttpClientModule], 
        providers: [ContactService],
    });
  });
  
  it("should ...", inject([ContactService], (service: ContactService) => {
    expect(service).toBeTruthy();
  }));
});

And this is my .sevice.ts file imports:

import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Contact } from '../';


Solution

  • You are injecting http module from @angular/common but you have imported @angular/http module.

    Change to this:

    import { Headers, Http } from '@angular/common/http';
    

    and you just need this:

    imports: [HttpClientTestingModule], 
    

    or instead of actual ContactService you can mock it:

    class MockContactService {
       // properties and methods to mock
    }
    

    now you can use this within your provider:

    providers: [
       {
         provide: ContactService,
         useClass: MockContactService
       }
    ]