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.
HttpClientModule
into your test. Your tests create their own modules. If you don't importHttpClientModule
(orHttpClientTestingModule
) there,HttpClient
won't work because Angular doesn't know about it. It doesn't matter that you addedHttpClientModule
to, say,AppModule
. It needs to be inTestBed.configureTestingModule
. Could also import aSharedModule
if you have one, as long asHttpClientModule
is in theexports
.But test will be slower because theSharedModule
would contain unneeded stuff – PresumablyHttpClientTestingModule
. – Plucky