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.
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.
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.
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.
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(); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With