How to Unit Test an HTTP Service in Angular
September 20, 2021
We now understand the importance of testing in isolation I want to shift our focus to testing an HTTP Service. By the time we wrap up this addition to the series, not only will you understand how to write valuable tests, but you'll also understand what to test - something I feel a lot of newcomers to unit testing struggle to wrap their minds around.
📢 If you haven't read parts one and two, I encourage you to come back to this article after reviewing the foundational concepts laid out in those posts.
Understanding the setup
For the purposes of this article, I've created a new Angular application and bootstrapped a json-server into the project so we can make API requests and compliment our learning process. By default, this API is running on localhost:3000
.
If you'd like to follow along, feel free to clone down this repo before continuing! I've created a starting
branch that has everything you need to follow along!
Altering the karma.config with ChromeHeadless
When you run ng test
in a new Angular project, the Karma report will be opened in a new Chrome tab. I prefer to have my test results shown in the terminal. To make this change, alter the browsers
property in your karma.config.js
file.
The Angular HTTP Service We Will Be Unit Testing
I have created a very simplistic HTTP service with all of the CRUD operations. Take a look below.
If you feel uncomfortable with any of these functions and what they are doing or the various operators in play, read the official Angular documentation about creating HTTP services.
📢 I have defined the URL here in the service, but ideally this would be sourced from an environment variable defined in your project.
What Do I Need to Unit Test?
With this basic Service in play, now is a good time to address the elephant in the room. What should you test in this class? There's a total of five functions, each making an API call to our json-server backend.
All functions we create, whether that's in a Component or Service, should have valuable supporting test cases.
💡 Want to know how to write valuable test cases? I released another article that provides an outline of 6 key points for you to follow.
To help identify what to test, let's briefly turn our attention to a simple metaphor from a previous article I wrote called The Gumball Machine: How To Quickly Identify Unit Test Cases.
The Gumball Machine
How does a gumball machine work? There are three major events:
Put a quarter in the machine
Turn the handle
A gumball comes rolling out
Think of functions as a gumball machine and follow the three steps:
Put the quarter in the machine (pass arguments to the function, if necessary)
Turn the handle (execute the code under test — the function itself)
A gumball comes rolling out (verify the behavior - the function returns the expected data)
I find it's helpful to scan the function and write down the various logic branches and the possible values that can be returned. These notes become an outline for writing unit tests for that function.
Identifying What to Test in an Angular HTTP Service
Take a second and give the Service above a once-over. Scan through the functions and determine the input and output. Is there anything else that would be beneficial for us to check? Create a testing outline and then continue reading.
Done?
Here's what I came up with:
Check that the functions return appropriate data (array of Books or a single Book)
Check that the expected API endpoint was called with the appropriate request method
If an error occurs, check to make sure that the
handleError
function was called with the appropriate argument(s). NOTE: I won't be focussing on this test case in this article.
Adding the HttpClientTestingModule to our Angular Unit Test File
Running the tests at this point produces an error. Can you guess why?
The error message actually gives us a hint. We aren't testing this Service in isolation - is has an injected dependency: the HTTP Client. In order for the default test to pass in the Service, we need to bring in the HttpClientTestingModule
- a module that provides all of the tools that we need to properly test Angular HTTP Services.
The test should pass now. Great!
📢 It is possible to test HTTP services without using the HTTPClientTestingModule
by mocking out various dependencies, but for the sake of simplicity, this tutorial will only demonstrate solutions with the module Angular provides.
Unit Testing Pattern: Arrange-Act-Assert
When writing unit tests, I like to follow the Arrange-Act-Assert (the 3 A's) pattern to help structure my test cases.
Arrange - set up the test case. Does the test require any special preparation? Use this step to get the code under test (the Service function) in a place where we can make our assertions. There will be times when there isn't anything to Arrange. That's fine - continue on to the next step.
Act - execute the code under test. In order for us to determine the expected behavior of software, we need to run the code under test. Pass any necessary arguments to the code under test in order to achieve the expected behavior.
Assert - verify expected outcomes. This is the step that actually controls whether your test passes or fails.
Writing an Angular Unit Test for the getAllBooks Function
Let's focus on the first piece of code in the HTTP service - the getAllBooks
function. It doesn't take any function arguments and is expected to return an array of Books.
With this in mind, let's create a new test and add the following test logic:
This may look like a lot and be confusing, so let me break it down.
I call the code under test - the
getAllBooks
function. This is part of the Act step in the Arrange-Act-Assert pattern.I make sure the data coming back from the function is an array of Books, which I've mocked out and brought into this test file. This satisfies the Assert step in the Arrange-Act-Assert pattern.
You may be thinking that this looks funny; why do we need to subscribe to thegetAllBooks
function? The function returns an Observable, so the only way to check the data that is being returned is to subscribe to the Observable and make the assertion inside.We set up and utilize the
HttpTestingController
for multiple reasons, but here we're using it to specify the URL that we expect the Service function to hit, as well as the request method to be used.We also use the
HttpTestingController
to flush (send) data through the stream. At first glance, this sort of seems to go against the normal testing pattern where you'd specify the data to be returned before the assertion statement. However, because we must subscribe to thegetAllBooks
function, we flush the data after we're listening for that Observable to emit the value.
To be even more clear, when the flush statement is executed, it sends themockBookArray
data through the stream, the subscribe block resolves and our assertion then takes place.
At this point, if you run the test, you should get a passing checkmark.
📢 If you'd like access to the mock data I'm using in these examples, check out my GitHub repo under the completed_test
branch.
Writing a Unit Test for the getBookById Function
This function is similar to the first. Can you come up with test criteria?
Here's how I'm testing this function:
This test allows you to see a bit more of the Arrange-Act-Assert pattern. Due to the nature of the code under test, we know that the function requires an ID value to be passed. We control this from the test-side by declaring an id
variable, setting the value to '1'
, and passing it to the getBookById
function.
Everything else is familiar - we still check that the request method is GET
and that the appropriate URL is being hit. We also send back a mock Book via the flush
method so that our assertion kicks off inside of the subscribe block.
Writing a Unit Test for the updateBook Function
Now let's look at the updateBook
function. The same patterns apply here, but the request method is different. Don't let that scare you! Take note of what argument(s) the function requires, and what the expected output is, then write the test.
Conclusion
Once you know the pattern, testing HTTP Services in Angular isn't that difficult.
Try testing the remaining functions in the Service class. Can you do it?
Feel free to check the completed_tests
branch of my GitHub repository and use it as a reference if you get stuck!
Thanks for reading! If you enjoyed this article and found it helpful, consider reading my other articles and subscribing to my newsletter below!