[Angular + Unit Testing] Mock HTTP requests made with Angular's HttpClient in Unit Tests

Source: Internet
Author: User
Tags export class

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.