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

});

原文地址:https://www.cnblogs.com/Answer1215/p/8448923.html

时间: 2024-10-25 21:20:06

[Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests的相关文章

[Unit Testing] Mock a Node module&#39;s dependencies using Proxyquire

Sometimes when writing a unit test, you know that the module you're testing imports a module that you would like to observe, or at the very least mock to prevent side effects like network activity or file system operations. For JavaScript unit tests

[Angular 8 Unit Testing] Testing a component

Setting up a Presentational Component: import {Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation} from '@angular/core'; import {Course} from '../model/course'; import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; imp

Unit Testing a zend-mvc application

Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in large projects, especially those with many people involved. Going back and manually testing every individual component of an application after every c

[Unit Testing] AngularJS Unit Testing - Karma

Install Karam: npm install -g karma npm install -g karma-cli Init Karam: karma init First test: 1. Add test file to the karma.conf.js: // list of files / patterns to load in the browser files: [ 'test/hello.js' ], 2. Add test file: describe('First Un

Unit Testing PowerShell Code with Pester

Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerShell code. Note   This is a five-part series that includes the following posts: What is Pester and Why Should I Care?Learn about a new test framework

[Mockito] Spring Unit Testing with Mockito

It is recommened to write unit testing with Mockito in Spring framework, because it is much faster with Spring framework test. But in case you can doing MVC, you still need to use spring framework test. In this post, we need to understand why to use

Java Unit Testing - JUnit &amp; TestNG

转自https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaUnitTesting.html yet another insignificant programming notes...   |   HOME TABLE OF CONTENTS (SHOW) Java Unit Testing -  & TestNG 1.  Introduction to Unit Testing Framework The various type o

8 Principles of Better Unit Testing

结合工作中的实例,如何设计一个良好的Unit Test,不仅关系到程序的正确性,更关系到有效的缩短整个团队的开发周期(coding, build, refactoring),深刻的关系到敏捷在实际中的应用. 单元测试,是编程契约的一种重要体现.Unit Test应该相信别人会遵守契约.每个Project应该Cover住自己的行为,而不应该去测试别人的行为. Writing good, robust unit tests is not hard -- it just takes a little

Live Unit Testing

Live Unit Testing 相对于传统的Unit Test,VS2017 带来了一个新的功能,叫Live Unit Testing,从字面意思理解就是实时单元测试,在实际的使用中,这个功能就是可以在编写代码的时候进行实时的background的单元测试. 在体验之前,有几点注意事项是需要了解的: 1.目前 live unit tesing仅仅支持 C#和VB的传统.net版本,不支持.net core,当然,我觉得也不支持其他的语言,这点是暂时让我遗憾的,因为从体验的结果来看,如果能支持