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();
})); });

最新文章

  1. oracle报错:ORA-28000: the account is locked
  2. ps命令使用 进程查看
  3. 汽车之家, 比亚迪等成为开源数据库SSDB的用户
  4. 编写你的第一个 Django 程序 第1部分
  5. Implicit conversion from enumeration type &#39;enum CGImageAlphaInfo&#39; to different enumeration type &#39;CGB
  6. DevExpress ASP.NET 使用经验谈(6)-ASPxGridView属性设置与CRUD界面优化
  7. ARC属性中还能使用assign,copy,retain这些关键字吗
  8. 获取url地址参数值
  9. ubuntu+mono+PetaPoco+Oracle+.net 程序部署
  10. 【DataMagic】如何在万亿级别规模的数据量上使用Spark
  11. 开源项目AndroidReview学习小结(1)
  12. P1337 [JSOI2004]平衡点 / 吊打XXX
  13. 弹性盒式布局flexbox(dispaly:flex)
  14. [LintCode/LeetCode]——两数和、三数和、四数和
  15. SWAP 简介
  16. C++ 第六课:C/C++关键字及其用法
  17. Sql优化-必劳记!
  18. 字符串(string)与整型(int)、浮点型(float)等之间的转换
  19. TensorMask
  20. 【资料】wod地城掉落

热门文章

  1. 【智能家居篇】wifi网络结构(上)
  2. Hibernate单向关联N-N
  3. YunOS曙光初现----看好阿里云OS----阿冬专栏!!
  4. n个整数全排列的递归实现(C++)
  5. log4j日志存储到数据库
  6. android:layout_gravity 和android:gravit的区别?
  7. 0x03 递归
  8. Swift3.0 闭包整理
  9. 未在本地计算机上注册&quot;Microsoft.Jet.OLEDB.4.0&quot;提供程序的解决方法
  10. iOS的流畅性