Angular HttpClientTestingModule - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
For testing service which uses HttpClientModule, we can use the fake implementation HttpClientTestingModule. Then we can use HttpTestingController to fake HTTP response.
import { async, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('RaceService', () => {
let raceService: RaceService;
let http: HttpTestingController;
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [RaceService]
}));
beforeEach(() => {
raceService = TestBed.get(RaceService);
http = TestBed.get(HttpTestingController);
});
it('should return an Observable of 2 races', async(() => {
// fake response
const hardcodedRaces = [{ name: 'London' }, { name: 'Lyon' }];
// call the service
let actualRaces = [];
raceService.list().subscribe(races => actualRaces = races);
// check that the underlying HTTP request was correct
http.expectOne('/api/races')
// return the fake response when we receive a request
.flush(hardcodedRaces);
// check that the returned array is deserialized as expected
expect(actualRaces.length).toBe(2);
}));
});