Unit testing a component with a service dependency using stubs
Standalone component testing is easy, but you will rarely need to write meaningful tests for a component that exists in isolation. More often than not, the component will have one or many dependencies, and writing good unit tests is the difference between delight and despair.
Note
The code, links, and a live example related to this recipe are available at http://ngcookbook.herokuapp.com/6651/.
Getting ready
Suppose you already have the service from the Unit testing a synchronous service recipe. In addition, you have a component, which makes use of this service:
[src/app/magic-eight-ball/magic-eight-ball.component.ts] import {Component} from '@angular/core'; import {MagicEightBallService} from '../magic-eight-ball.service'; @Component({ selector: 'app-magic-eight-ball', template: ` <button (click)="update()">Click me!</button> <h1>{{ result...