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. windows系统中软件开发常用的软件

    1.windwos快速打开控制面板:热键+r打开运行框,输入control就打开windows的控制面板了 2.windows自带的远程桌面控制系统:mstsc -Microsoft terminal ...

  2. 多校第二场 1004 hdu 5303 Delicious Apples(背包+贪心)

    题目链接: 点击打开链接 题目大意: 在一个周长为L的环上.给出n棵苹果树.苹果树的位置是xi,苹果树是ai,苹果商店在0位置,人的篮子最大容量为k,问最少做多远的距离可以把苹果都运到店里 题目分析: ...

  3. 启用QNX系统,海尔智能冰箱或成业界“宝马”

        智能家电正处于迅猛发展的态势,国内眼下有非常多企业都在积极布局智能家电,当中又以海尔最为典型.作为家电领域的领头羊,海尔近年来在智能家电领域的动作不小.近期有消息透露.海尔也许会在IFA展会上 ...

  4. iOS-UIImageView载入网络下载的图片(异步+多线程)

    最原始的载入网络下载的图片方式: //最原始载入网络图片方法,相当堵塞主线程,界面卡顿 -(void)setImageWithURL:(NSString *)imageDownloadUrl{ UII ...

  5. UI_KVC赋值

    使用KVC对person的属性进行赋值 [aperson setValue:@"yadong" forKey:@"name"]; [aperson setVal ...

  6. UVA 11426 - GCD - Extreme (II) 欧拉函数-数学

    Given the value of N, you will have to find the value of G. The definition of G is given below:G =i< ...

  7. FFMpeg在Windows下搭建开发环境【转】

    本文转载自:http://blog.csdn.net/wootengxjj/article/details/51758621 版权声明:本文为博主原创文章,未经博主允许不得转载. FFmpeg 是一个 ...

  8. hdoj--3440--House Man(差分约束)

    House Man Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  9. nyoj--74--小学生算术(水)

    小学生算术 时间限制:3000 ms  |  内存限制:65535 KB 难度:1 描述 很多小学生在学习加法时,发现"进位"特别容易出错.你的任务是计算两个三位数在相加时需要多少 ...

  10. Java并发包

    刚看到一篇总结的比较全的JUC包总结,转载如下: 1. java.util.concurrent - Java 并发工具包 Java 5 添加了一个新的包到 Java 平台,java.util.con ...