Testing with the Angular HttpClient API

Embracing Observables and Immutability FTW

Ciro Nunes
Netscape
2 min readAug 21, 2017

--

The HttpClientTestingModule makes it easier to mock requests using the HttpTestingController service. In this post we’ll learn how to setup our tests and see real examples of how it can be used.

Series

This post is part of the HttpClient API series:

  1. The new Angular HttpClient API
  2. Testing with the Angular HttpClientTesting API

Demo

We will create a simple GitHub API service that can get users and make searches. More precisely we will:

  • Create the GithubApiService and write tests for it.
  • Consume the service created in our GithubComponent to list users and make searches and write tests for it. (this part is not covered in this post)

You can jump straight to the code you want. Check this GitHub repository.

Unit testing services with HttpClient

The service

As mentioned before, our service will allow us to get users and make searches. It'll have two methods getUsers and search.

Notice how we throw an error in case the consumer tries to search for a non supported type:

This example should be fun enough for us to write some tests for.

Setup

Now we setup the TestBed importing the HttpClientTestingModule and providing the HttpTestingController. Of course we also provide the service we're testing:

Notice that for convenience we saved the injector and the providers we'll use in our tests in variables. Another option would be to use the inject function.

We also run HttpTestingController#verify to make sure that there are no outstanding requests:

Mocking

You can use the HttpTestingController to mock requests and the flush method to provide dummy values as responses. As the HTTP request methods return an Observable, we subscribe to it and create our expectations in the callback methods:

Dealing with errors

In this case we're using the error callback of the subscribe method. We also use the expectNone matcher to confirm that the request wasn't made:

Testing parameters

In that case we can verify the request.params to assert if the request was made with the correct parameters. As the HttpParams#set method is immutable, the result is predictable and the tests easy to write:

Wrapping up

There’s a very simple and common flow for creating the tests:

1- Subscribe to the results of a request

2- Mock the request using expectOne, expectNone or match

3- flush the request passing dummy values (in case of expectNone this step isn't necessary)

What's next

In the next post we'll cover testing interceptors. Stay tuned.

--

--

Ciro Nunes
Netscape

👨‍👩‍👧, 🇧🇷, 🇦🇺, ⚽️, web development, js, functional programming, haskell, ocaml, reasonml, rust, entrepreneurship, martial arts