Testing with the Angular HttpClient API
Embracing Observables and Immutability FTW
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.
This post is part of the HttpClient API series:
We will create a simple GitHub API service that can get users and make searches. More precisely we will:
- Create the
GithubApiServiceand write tests for it.
- Consume the service created in our
GithubComponentto 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
As mentioned before, our service will allow us to get users and make searches. It'll have two methods
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.
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
We also run
HttpTestingController#verify to make sure that there are no outstanding requests:
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:
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:
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
flush the request passing dummy values (in case of
expectNone this step isn't necessary)
In the next post we'll cover testing
interceptors. Stay tuned.