Angular Service HTTP testing
June 23, 2021 · 2 min readLucian CiobanuIn order to test a service which uses HTTP Client Module, the following should be added:
import { TestBed } from '@angular/core/testing';
import { NameService } from './name.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/testing';
describe ('NameService', () => {
let service: NameService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ NameService ],
imports: [ HttpClientTestingModule ]
});
service = TestBed.inject(NameService);
});
afterEach(() => {
httpTestingController.verify();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
//rest of tests go here...
});
Later added: in the component which calls the service, in order to test the called method, you should add:
import { HttpClientTestingModule } from '@angular/common/http/testing';
[...]
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
})
.compileComponents();
});
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery