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.


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} ...

Get Angular 2 Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.