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. poj1035Spell checker

    暴力解决. 先把字典里的每一个单词的长度存起来.在查找的时候.就比較长度,在多一个少一个之间找, #include<stdio.h> #include<string.h> #i ...

  2. bram和dram差别

    选择distributed memory generator和block memorygenerator标准: Dram和bram差别: 1.bram 的输出须要时钟,dram在给出地址后既可输出数据 ...

  3. exFAT格式

    买了一个64GB的T卡,发如今Windows XP上格式化."文件系统"仅仅有exFAT选项. 用这个exFAT格式化还失败了. 给XP打上KB955704补丁,能够用exFAT格 ...

  4. 【分享】GEARS of DRAGOON 1+2【日文硬盘版】[带全CG存档&amp;攻略+SSG改动+打开存档补丁]

    冒险者们哟.寻找龙秘玉吧--! ninetail的最新作,是使用丰富多彩的技能·道具探索迷宫的3D迷宫RPG! 存在着骑士和神官的架空世界常见的职业为首的13种职业.超过数百种的道具的登场! 和伙伴一 ...

  5. Web前端开发实战2:二级下拉式菜单之JS实现

    上一篇博文提到了二级下拉式菜单是用HTML和CSS实现的.我们这一篇来用JavaScript脚本实现下拉菜单的显 示和隐藏. 使用 JavaScript方法实现我们须要用的知识有: 1)JS事件:on ...

  6. Android scrollTo() scrollBy() Scroller解说及应用

    版本号:1.0  日期:2014.6.17  2014.6.18 版权:© 2014 kince 转载注明出处   scrollTo() .scrollBy()及 Scroller在视图滑动中常常使用 ...

  7. HDU TIANKENG’s rice shop(模拟)

    HDU 4884 TIANKENG's rice shop 题目链接 题意:模拟题.转一篇题意 思路:就模拟就可以.注意每次炒完之后就能够接单 代码: #include <cstdio> ...

  8. java 中的静态(static)代码块

    类字面常量 final 静态域不会触发类的初始化操作 非 final static 静态域(以及构造器其实是一种隐式的静态方法) Class.forName():会自动的初始化: 使用 .class来 ...

  9. 杂项-DB-分布式:HBase

    ylbtech-杂项-DB-分布式:HBase HBase是一个分布式的.面向列的开源数据库,该技术来源于 Fay Chang 所撰写的Google论文“Bigtable:一个结构化数据的分布式存储系 ...

  10. linux服务器卸载本机默认安装的jdk

    1.      查看系统安装的版本情况: rpm -qa | grep jdk rpm -qa | grep gcj 2.      查看并删除 [root@iZ2zeedm3x12d8xb4g15a ...