In this blogpost I want to show you how you can test the new HttpClient introduced with the version 4.2 of angular.
The HttpClient service
Lets take this service as a reference
Here we are injecting the httpClient and using it firing a http request to an api.
At first we have to include the
HttpClientTestingModule and our
CustomHttpService in our testbed like so:
The next step is to hold the
CustomHttpService itself and the
HttpTestingController to mock http calls. We need this later on. Modify your sources like this:
Notice that we store the service and the httpmock in variables we can access in every test and gets instanciated every time before a test runs
The testing method
Lets do a single test with the
it(...) like we know it first.
Next step is to consume the service and fire up a request like we would do it normally. Keep in mind that we are not using the real
HttpClient but a mock of that provided by angular.
Here we are also expecting the correct (but faked) result: A property
name with the value
So now we can tell the httpMock what kind of request we expect and toward which URL. We can do this like this:
Notice that the url has to be the same as the url in the service.
So we are expecting a call to this API and we consider it as a GET request.
Last thing is to “fire” the request with its data we really expect. So in this case we give a sample object with a property “name” and the value “Luke Skywalker” as expected.
httpMock.verify(); we verify that there are not outstanding http calls.
Thats it for the GET request. We can fire up the other (POST/PUT/DELETE) requests in nearly the same way!
Lets do this:
You can see that the structure of the tests is the same.
With the new HttpClient you can test your http services with ease.