Services

testing-services

Isolated Services

You may test isolated Services that don't depend on any other Services like this.

Services with Dependencies

Services often depend on other services that Angular inject into the constructor.

Create and inject these dependencies by hand.

triangle-exclamation

Injecting with new

Only use this way if testing real simple Services.

triangle-exclamation

Injecting with spies

Services with TestBed

Angular DI handle the discovery and creating of dependant services.

As a service consumer, you don't worry about the order of constructor arguments or how they are created. For this you use TestBed testing utility to provide and create services.

Simple Service test

  1. You set the providers property with an array of the services that you'll test or mock.

  2. Then inject it inside a test by calling TestBed.inject() with the service class as the argument.

Injecting other services as dependencies

When testing a service with a dependency, provide the mock in the providers array.

Data Services that make HTTP calls to remote servers typically inject and delegate to the Angular HttpClient service for XHR calls.

You can test a data service with an injected HttpClient spy as you would test any service with a dependency.

Test with spies

triangle-exclamation

Extended interactions between a data service and the HttpClient can be complex and difficult to mock with spies.

Test the service

Lets suppose we have a Service that hits an endpoint url/fruits.

Testing error handling

To test handling of backend errors (when the server returns a non-successful status code), flush requests with an error response that emulates what your backend would return when a request fails.

Testing Interceptors

More on the docs.arrow-up-right

Last updated