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.
HttpClientModuleinto your test. Your tests create their own modules. If you don't importHttpClientModule(orHttpClientTestingModule) there,HttpClientwon't work because Angular doesn't know about it. It doesn't matter that you addedHttpClientModuleto, say,AppModule. It needs to be inTestBed.configureTestingModule. Could also import aSharedModuleif you have one, as long asHttpClientModuleis in theexports.But test will be slower because theSharedModulewould contain unneeded stuffHttpClientTestingModule.