[Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests
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的更多相关文章
- [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 ...
- [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 ...
- C/C++ unit testing tools (39 found)---reference
http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...
- [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 ...
- [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 ...
- [Angular & Unit Testing] Automatic change detection
When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...
- [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 ...
- [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 ...
- [Angular Unit Testing] Testing Component methods
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...
随机推荐
- [Linux]第三部分-学习Shell和Shell脚本
vim 高级的 vii o a 进入编辑模式 esc进入一般模式:wq离开alias vi='vim' 使用vim打开viv块选择 y复制反白,d删除反白在vi中打开一个文件后,可以使用 sp fil ...
- [BZOJ 3884][欧拉定理]上帝与集合的正确使用方法
看看我们机房某畸形写的题解:http://blog.csdn.net/sinat_27410769/article/details/46754209 此题为popoQQQ神犇所出,在此orz #inc ...
- NYOJ 145 聪明的小珂
/* 题目大意:求解和输入数的互质的数 解题思路:求解和 n 互质的最大数.从n/2開始找 关键点:GCD函数的使用 解题人:lingnichong 解题时间:2014-10-04 16:11:55 ...
- centos下yum安装lamp和lnmp轻松搞定
centos下yum安装lamp和lnmp轻松搞定.究竟多轻松你看就知道了.妈妈再也不操心不会装lamp了. 非常辛苦整理的安装方法,会持续更新下去.凡无法安装的在评论里贴出问题来,会尽快解决.共同维 ...
- HDU 2054 A==B? 大数
Problem Description Give you two numbers A and B, if A is equal to B, you should print "YES&quo ...
- python matplot 绘图
import numpy as np import matplotlib.pyplot as plt plt.figure(1) # 创建图表1 plt.figure(2) # 创建图表2 ax1 = ...
- elasticsearch源码分析之search模块(client端)
elasticsearch源码分析之search模块(client端) 注意,我这里所说的都是通过rest api来做的搜索,所以对于接收到请求的节点,我姑且将之称之为client端,其主要的功能我们 ...
- JAVA好书之《深入理解Java虚拟机》
最近打算做好现有工作的前提下,扎实一下自己专业的技术知识,并将相关的经典书也记录一下.今天看了一些JVM相关的知识,这里面的经典是<深入理解Java虚拟机>,适合有点基础又想深入理解其中原 ...
- ROS-SLAM-gmapping
前言:gmapping是最常用和成熟的slam导航算法,gmapping功能包集成了Rao-Blackwellized粒子滤波算法,为开发者隐去了复杂的内部实现. 前提:已下载并编译了相关功能包集,如 ...
- ROS-参数
前言:参数的用法. 一.参数常用命令 命令 功能 rosparam list 参数列表 rosparam get 获取参数 rosparam set 设置参数 rosparam load 加载参数 ...