Testing Services

Learn how to test services by injecting AsyncService in the TestBed method.

As we learned, a service can inject other services. Testing a standalone service is pretty straightforward: we get an instance from the injector and then start to query its public properties and methods.

Note: We are only interested in testing the public API of a service, which is the interface that components and other artifacts use. Private symbols do not have any value in being tested because they represent the internal implementation of the service.

There are three different types of testing 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.

In the following sections, we will go through each of them in more detail.

Testing a synchronous method

When we create an Angular service using the Angular CLI, it also creates a corresponding test file. When we created the async service, the Angular CLI created the following async.service.spec.ts file:

Get hands-on with 1200+ tech skills courses.