angularkarma-jasmineangular-test

Angular 6 - NullInjectorError: No provider for HttpClient in unit tests


I am importing and using HttpClient in a service as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root',
})
export class MyService {
    constructor(private http: HttpClient) { }

    getData() {
        return this.http.get("url...");
    }
}

However, when I run ng test for my unit tests, and when those tests use the service, I am getting the error:

Error: StaticInjectorError(DynamicTestModule)[HttpClient]: 
  StaticInjectorError(Platform: core)[HttpClient]: 
    NullInjectorError: No provider for HttpClient!

The Angular 6 documentation on HTTP just says to do what I did above.


Solution

  • import { TestBed } from '@angular/core/testing';
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    import {HttpClientModule} from '@angular/common/http';
    import { myService } from './myservice';
    
    
    describe('myService', () => {
    
          beforeEach(() => TestBed.configureTestingModule({
            imports: [HttpClientTestingModule], 
            providers: [myService]
          }));
    
           it('should be created', () => {
            const service: myService = TestBed.get(myService);
            expect(service).toBeTruthy();
           });
    
           it('should have getData function', () => {
            const service: myService = TestBed.get(myService);
            expect(service.getData).toBeTruthy();
           });
    
        });