Chapter 10. Unit Testing Services

In the previous two chapters, we started understanding what Angular services are, when to create them, and how to use them. We also started learning how to make HTTP calls and handle the various use cases that crop up when working with servers.

In this chapter, we will take a step back and try to see how we can unit test these services. We will first see how to unit test a service, followed by understanding how to leverage the Angular dependency injection system to mock out service dependencies in unit tests. Finally, we will dig into writing unit tests when we are working with HttpClient.

If you want to quickly recap what unit tests are and how to write them for components, you can refer to Chapter 5.

How to Unit Test Services

The first thing we will start with is learning how to unit test very simple services. These might be services without any dependencies that act as encapsulators of business logic or functionality that needs to be reused across our application.

We will start with testing the very simple service we built in Chapter 8. You can use the codebase in chapter8/simple-service as the base for this section. The finished code is available in chapter10/simple-service.

Any time we are unit testing our service, we must do a few things over and above what we did for testing components. Namely:

  • Configure the Angular TestBed with a provider for the service we want to test.

  • Inject an instance of the service we want to test either into ...

Get Angular: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.