Testing Angular HTTP Communication

Testing Angular HTTP Communication

Angular has great built-in tools for making web requests. It also contains a great module for testing HTTP communication: HttpClientTestingModule. This module contains full toolbox to ensure web communication happens as intended by the developer.

Angular has great built-in tools for making web requests. It also contains a great module for testing HTTP communication: HttpClientTestingModule.This module contains full toolbox to ensure web communication happens as intended by the developer. Let’s explore HttpClientTestingModule and get to know how to:

  • test HTTP requests
  • emulate response
  • handle errors
  • test HTTP interceptors

Testing HTTP requests

Let’s make a simple app that shows a list of repositories starred by a GitHub user. It will consist of an input field for the user name, a button to make a request and a table to show results. To make things look pretty, let’s use bootstrap.

We need to make web requests when a user clicks on the “show” button. Let’s set up a test suit and create a test to make sure a web request happens.

Angular is equipped with a great HTTP testing toolbox. HttpClientTestingModule is a ready to go container for all the tools we need for HTTP testing. It provides HttpTestingController — an injectable service to manage HTTP requests. HttpTestingController exposes information about all HTTP requests that happen during the execution of a test. We can inject an instance of it as with any other injectable service.

Let’s do the setup code.

describe('AppComponent', () => {
      let component: AppComponent;
      let fixture: ComponentFixture<AppComponent>;
      let httpMock: HttpTestingController;

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
          declarations: [AppComponent]
        })
          .compileComponents();

        httpMock = TestBed.inject(HttpTestingController);
      }));

Now time to write the first test. The endpoint to retrieve all the repos which are starred by the user is https://api.github.com/users/:userName/starred.When a user clicks on the button we expect this request.

it(`should make http call to proper GitHub API url when show button is clicked`, () => {
      component.userName = 'IAfanasov';

      fixture.debugElement.query(By.css('button')).nativeElement.click();

      expect(() => httpMock.expectOne('https://api.github.com/users/IAfanasov/starred'))
        .not.toThrow();
    });

HttpTestingController contains two expectation methods: expectOne and expectNone. Both have a couple of overloads with different parameters to recognize specific requests. The name of methods perfectly describes what they do — expect none or only one specific request. If an expectation is not met, an exception is thrown. Jasmine requires an “expect” statement. To make the test pass with a green mark we put expect().not.toThrow().

angular http-interceptors unit-testing http-request

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Introduction to Unit Testing in Angular

What is Unit Testing ? Unit testing is testing a unit in an isolated environment. A unit can be a class, component, service, directive module etc. which can

Super easy trick to bypass Http Interceptors in Angular

BONUS: Searching for a better folder structure for angular projects? check it out and you can thank me later.

Testing Microservices Applications

The shift towards microservices and modular applications makes testing more important and more challenging at the same time. Learn more here.

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

An Introduction to Unit Testing in Angular

Unit testing, as the name implies, is about testing individual units of code. Unit tests try to answer questions such as "Did I think about the logic correctly?" or "Does the sort function order the list in the right order