Testing services
As we learned in Chapter 5, Structure an Angular App, a service can inject other services to use them as well. Testing a standalone service is pretty straightforward: we get an instance from the injector and then start to query its public
properties and methods.
Important Note
We are only interested in testing the public API of a service, which is the interface that components and other artifacts interact with. Private symbols do not have any value in being tested, except if they have any public side effects. For example, a public
method can call a private
one that may set a public
property as a side effect.
There are three different types of test that we can perform in a service:
- Testing a synchronous operation, such as a method that returns a simple array
- Testing an asynchronous operation, such as a method that returns an observable
- Testing services with dependencies, such as a method that makes HTTP requests
Let's go through...