Unit testing a component with a service dependency using spies

The ability to stub out services is useful, but it can be limiting in a number of ways. It can also be tedious, as the stubs you create must remain up to date with the public interface of the service. Another excellent tool at your disposal when writing unit tests is the spy.

A spy allows you to select a function or method. It also helps you collect information about if and how it was invoked as well as how it will behave once it is invoked. It is similar in concept to a stub but allows you to have a much more robust unit test.

Note

The code, links, and a live example related to this recipe are available at http://ngcookbook.herokuapp.com/3444/.

Getting ready

Begin with the component tests ...

Get Angular 2 Cookbook 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.