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 you wrote in the last recipe:
[src/app/magic-eight-ball/magic-eight-ball.component.spec.ts] import {TestBed, async} from '@angular/core/testing'; import {MagicEightBallComponent} from './magic-eight-ball.component'; &...