Angular 5 service failing to pass unit tests with (NullInjectorError: No provider for HttpClient!) Angular 5 service failing to pass unit tests with (NullInjectorError: No provider for HttpClient!) typescript typescript

Angular 5 service failing to pass unit tests with (NullInjectorError: No provider for HttpClient!)


The reason for "NullInjectorError: No provider for HttpClient!" are unresolved dependencies. In this case the lack of a HttpClientModule.

In your .service.spec.ts file add

  imports: [        HttpClientTestingModule,    ],

You might notice that I wrote HttpClientTestingModule instead of HttpClientModule. The reason is that we don't want to send actual http requests, but rather use a Mock API of the test framework.


simply add it like this,

  beforeEach(() => {    TestBed.configureTestingModule({      imports: [        HttpClientModule,      ],    }).compileComponents();  });


Try wrapping your inject in an async, like below:

import { TestBed, async, inject } from '@angular/core/testing';import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';import { ApiService } from './api.service';describe('ApiService', () => {    beforeEach(() => {      ...    });      it(`should create`, async(inject([HttpTestingController, ApiService],    (httpClient: HttpTestingController, apiService: ApiService) => {      expect(apiService).toBeTruthy();  })));});

Don't forget to import async from @angular/core/testing.

I have had good success with this. It's the only different from your unit tests and mine where I use HttpClientTestingModule.