In a proper unit test we want to isolate external dependencies as much as possible to guarantee a reliable test outcome. Http calls represent such external dependencies. Therefore, when testing our Angular and services that rely on the data retrieved via Http, we need to make sure to M Ock such calls and instead provide some fake data during the test execution. In this lesson we are about the new and that have been added in Angular v4.3.1 to make my life HttpClientTestingModule
HttpTestingController
easier.
Serivce:
Import {injectable} from ' @angular/core 'rxjs/observable' @angular/common/http '; export Interface person { name:string;} @Injectable () Export class Peopleservice { constructor (private http:httpclient) {} fetchpeople (): Observable <Person[]> { returnthis. http . Get<Person[]> ('/ Api/v1/people ');} }
Spec:
Import {TestBed, inject} from ' @angular/core/testing '; import {httpclienttestingmodule, httptestingcontroller} from' @angular/common/http/testing '; import {Peopleservice} from'./people.service ';d Escribe (' The Peopleservice ', () ={Beforeeach ()={Testbed.configuretestingmodule ({imports: [Httpclienttestingmodule], providers: [Peopleservi CE]}); }); It (' Should fetch a list of people ', inject([Peopleservice, Httptestingcontroller], (Peopleservice:peopleservice, Httpmock: httptest Ingcontroller)= { //Execute the callPeopleservice. Fetchpeople (). Subscribe (People={expect (people.length). ToBe (2); Expect (people[0].name). ToBe (' Juri '); }); Const REQ= Httpmock.Expectone('/api/v1/people ', ' Call to PPL API '); Expect (Req.request.method). ToBe (' GET '); Req.flush ([{Name:' xxx '}, {name:' xxx ' } ]); httpmock.verify (); }));});
[Angular + Unit Testing] Mock HTTP requests made with Angular's HttpClient in Unit Tests