Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 795
Kingamere Avatar asked Dec 13 '18 20:12

Kingamere


People also ask

How do I fix Nullinjectorror no provider for Httpclient?

Resolution. The issue is more due to not registering the required services i.e HttpClientModule in the root module ie. NgModule. As per Angular Design and Architecture every service (internal or external service) is required to be registered with root NgModule as required.

What is TestBed inject?

TestBed. configureTestingModule() helps you configure the providers. Configuring the providers means you are letting the Angular dependency injection system know about this dependency which later it can inject in to components when requested through a dependency injection token.

What is HttpClientTestingModule?

Using the HttpClientTestingModule and HttpTestingController provided by Angular makes mocking out results and testing http requests simple by providing many useful methods for checking http requests and providing mock responses for each request.


1 Answers

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();        });      }); 
like image 179
The Dead Man Avatar answered Sep 18 '22 20:09

The Dead Man