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 components or services that rely on data retrieved via Http, we need to make sure to mock such calls and instead provide some fake data during the test execution. In this lesson we about the new HttpClientTestingModule and HttpTestingController that has been added in Angular v4.3.1 to make our life easier.

Serivce:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http'; export interface Person {
name: string;
} @Injectable()
export class PeopleService { constructor(private http: HttpClient) {} fetchPeople(): Observable<Person[]> {
return this.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'; describe('The PeopleService', () => { beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
PeopleService
]
});
}); it('should fetch a list of people', inject(
[PeopleService, HttpTestingController],
(peopleService: PeopleService, httpMock: HttpTestingController) => { // execute the call
peopleService
.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的更多相关文章

  1. [Unit Testing] Mock a Node module's dependencies using Proxyquire

    Sometimes when writing a unit test, you know that the module you're testing imports a module that yo ...

  2. [Unit Testing] Mock an HTTP request using Nock while unit testing

    When testing functions that make HTTP requests, it's not preferable for those requests to actually r ...

  3. C/C++ unit testing tools (39 found)---reference

    http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...

  4. [Unit Testing] Using Mockito Annotations - @Mock, @InjectMocks, @RunWith

    Previously we have seen how to do Unit testing with Mockito; import org.junit.Test; import static or ...

  5. [Angular & Unit Testing] Testing a RouterOutlet component

    The way to test router componet needs a little bit setup, first we need to create a "router-stu ...

  6. [Angular & Unit Testing] Automatic change detection

    When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...

  7. [Angular & Unit Testing] Testing Component with Store

    When using Ngrx, we need to know how to test the component which has Router injected. Component: imp ...

  8. [Angular Unit Testing] Debug unit testing -- component rendering

    If sometime you want to log out the comonent html to see whether the html render correctly, you can ...

  9. [Angular Unit Testing] Testing Component methods

    import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...

随机推荐

  1. [jQuery]文本框text变化事件

    $("#key").live("keyup",function(){   })

  2. [Beginning SharePoint Designer 2010]Chapter2 编辑页面

    本章概要: 1.如何展开隐藏任务面板和ribbon标签 2.页面编辑模式 3.代码视图模式和智能提示 4.如何组合SharePoint和页面上其他元素

  3. python处理时间戳

    代码如下: def timestamp_datetime(value):     format = '%Y-%m-%d %H:%M:%S'     # value为传入的值为时间戳(整形),如:133 ...

  4. Codeforces Round #168 (Div. 2)---A. Lights Out

    Lights Out time limit per test 2 seconds memory limit per test 256 megabytes input standard input ou ...

  5. CCDirector导演类

    CCDirector类是Cocos2D-x游戏引擎的核心.它用来创建而且控制着屏幕的显示,同一时候控制场景的显示时间和显示方式. 在整个游戏里一般仅仅有一个导演.游戏的開始.结束.暂停都会调用CCDi ...

  6. 移植MonkeyRunner的图片对照和获取子图功能的实现-Appium篇

    假设你的目标測试app有非常多imageview组成的话,这个时候monkeyrunner的截图比較功能就体现出来了. 而其它几个流行的框架如Robotium,UIAutomator以及Appium都 ...

  7. 2014秋C++ 第7周项目 数据类型和表达式

    课程主页在http://blog.csdn.net/sxhelijian/article/details/39152703,课程资源在云学堂"贺老师课堂"同步展示,使用的帐号请到课 ...

  8. POJ 3905 Perfect Election(2-sat)

    POJ 3905 Perfect Election id=3905" target="_blank" style="">题目链接 思路:非常裸的 ...

  9. BZOJ 2435: [Noi2011]道路修建 dfs搜图

    2435: [Noi2011]道路修建 Description 在 W 星球上有 n 个国家.为了各自国家的经济发展,他们决定在各个国家之间建设双向道路使得国家之间连通.但是每个国家的国王都很吝啬,他 ...

  10. h5-弹出层layer,提示,顶部横条,

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYkAAAI7CAIAAACWVfAJAAAgAElEQVR4nOy9f1ATWb733z3uOA4kIC ...