Testing is something near and dear to my heart. When we launched our first production Angular2 application into the wild two weeks ago
the question was asked, “Where are the tests?”. We had a few e2e tests that covered core functionality but now that we
have a chance to look over our last 8 months of work we realized we need to refactor quite a bit of the code.
Before refactor though we needed to wrap our code in unit tests as well.
One of the easiest things for us to test are simple http services. Tour of Heroes had a good example of a simple http service.
In order to begin our unit testing we have to configure our TestBed. Angular2 provides a testing module that we can configure and control
our injections. I found that having the configuration in a beforeEach block allows for easy setup and tear-downs.
For this example we need to setup http.
After our test bed is configured we need to actually inject http into the service itself.
With the setup complete we can actually test our service. Because this is going to be asynchronous we need to have a callback for Jasmine to know when
the test is done executing.
While the service itself is simple we can test a few things on it that might come in handy later. By hooking into the mockBackend’s connections
we can verify the method, url, and mock a response. This allows us to verify the correct url was called, with the correct parameter.
Because our search function is returning an observable we can also verify any side effects we may be using on the response. In this case there are none
but we still verify the data coming back.
Here is the test as a whole for our hero-search.service.
Testing Services (Complex Example)
For a more complex example we have the hero.service which converts the observables to promises, and also has some catch logic.
Since this test has a little more complexity we need to have some differences for the test bed configuration. Instead of having it in the before each block
I decided to move it to a function block. I’m going to pass into this block a failed or successful http connection.
For the failed request we can create a simple class.
The same is true for the successful request.
The setup function itself is very similar to the setup we used for the simple service except the httpMock is passed in.
With the setup complete we can verify that the handle error functionality has been called when a http request fails.