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.