Angular 6 - NullInjectorError: No provider for HttpClient in unit tests
89,770
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();
});
});
Author by
Kingamere
Updated on July 08, 2022Comments
-
Kingamere almost 2 years
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.
-
Kingamere over 5 yearsThanks, I just needed to add
HttpClientTestingModule
to theimports
array in theconfigureTestingModule
method. -
The Dead Man over 5 yearsYes, I wanted to just post that but I said let make it full , am happy it helped
-
Salvatore Pannozzo Capodiferro about 5 yearsworking for me, I was aspecting to add the module in the main test instead it must be added in the test of the service
-
iowatiger08 almost 5 yearsThis helped but import {HttpClientModule} from '@angular/common/http'; is not necessary since the test class does not actually use it.
-
Takatalvi over 4 yearsThe user asks for unit testing... not using it in a service
-
Hassan Raza about 4 yearsThanks! This worked for me in Angular 9. import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; beforeEach(() => TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [myService] }));
-
Tinashe over 3 yearsI spent most of my time trying to figure out how to create Jasmine Spy HttpClient object until I found this solution. Thanks.
-
bob about 3 yearsA description of what the solution adds--why it works, would be helpful. Without words, I'm forced to do a visual diff between OP's post and this answer.