6 Testing services


This chapter covers

  • Understanding what services do in Angular applications
  • Using dependency injection with service unit tests
  • Creating isolated unit tests by using spies as test doubles
  • Testing services that return results asynchronously using promises and RxJS observables
  • Testing web services with Angular’s HTTP utilities

In this chapter, you’ll create and test the services you need for setting preferences in the Contacts app, and for loading and saving contacts from a server. PreferencesService will save application settings to the user’s browser using either cookies or localStorage. The example we’ll look at will show you how to test with both synchronous services and asynchronous services (services that return promises or observables). You’ll learn how to isolate your code under test from its related dependencies by using Jasmine spies. ContactService uses Angular’s HttpClient to fetch and store data from a REST service using observables, which are like promises but return continuous streams of values. You’ll learn how to configure service tests, set up mocks and dependencies, and exercise service interfaces through test-driven development.

By the end of this chapter, you’ll know how to write and test services that use HttpClient and how to move the code associated with manipulating data (the business logic) into tested services to help organize your application’s architecture.

6.1 What are services?

6.2 How do services work in Angular?

6.2.1 Dependency injection

6.2.2 The @Injectable class decorator

6.3 Creating services with Angular CLI

6.4 Testing PreferencesService

6.4.1 Testing for failures

6.5 Testing services with promises

6.5.1 How asynchronous changes testing

6.5.2 Testing for failures with asynchronous services

6.6 Testing HTTP services with observables