Table Of ContentJesse Palmer
Corinna Cohn
Mike Giambalvo
Craig Nishina
Foreword by
Brad Green, Google
M A N N I N G
Anatomy of a Basic Component Unit Test
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BasicComponent } from './basic.component';
describe('BasicComponent', () => {
let component: BasicComponent;
let fixture: ComponentFixture<BasicComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BasicComponent ]
})
Setup—The setup part of your
.compileComponents();
tests usually will involve three
})); parts: declaring variables, a
beforeEach to configure
beforeEach(() => { TestBed, and a beforeEach to
fixture = TestBed.createComponent(BasicComponent); initialize the variables.
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create an instance of BasicComponent', () => {
expect(component).toBeTruthy();
});
Actual test
afterEach(() => {
fixture = null;
component = null;
});
});
Teardown—Use afterEach to destroy
variable references.
Testing Angular Applications
JESSE PALMER
CORINNA COHN
MICHAEL GIAMBALVO
CRAIG NISHINA
with a Foreword by Brad Green
MANNING
Shelter ISland
For online information and ordering of this and other Manning books, please visit www.manning.com.
The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com
©2018 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form
or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the
publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in the book, and Manning Publications was aware of a
trademark claim, the designations have been printed in initial caps or all caps.
∞Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books
we publish printed on acid-f ree paper, and we exert our best efforts to that end. Recognizing also our
responsibility to conserve the resources of our planet, Manning books are printed on paper that is at
least 15 percent recycled and processed without the use of elemental chlorine.
Manning Publications Co. Development editors: Cynthia Kane and Toni Arritola
20 Baldwin Road Technical development editors: Doug Warren and Nick Watts
PO Box 761 Copyeditor: Carl Quesnel
Shelter Island, NY 11964 Proofreader: Melody Dolab
Technical proofreader: Luis Carlos Sanchez Gonzalez
Typesetter: Happenstance Type-o-Rama
Cover designer: Marija Tudor
ISBN 9781617293641
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – SP – 23 22 21 20 19 18
To my wife, whose love and support helped me get through many long nights and
weekends while working on the book. Your accomplishments inspire me to do my
best every day.
To my parents, who passed down to me their work ethic and provided me with
opportunities to succeed in life, for which I am forever grateful.
—Jesse Palmer
To my dear friends, who encouraged me to keep writing!
—Corinna Cohn
To my wife, who has been consistently and limitlessly supportive over the many
long nights these past few months.
—Michael Giambalvo
To my parents, whose hard work and sacrifice afforded me many opportunities,
and to my wife, who supports me in all that I do.
—Craig Nishina
iii
contents
foreword ix
preface xi
acknowledgments xiii
about this book xv
about the authors xviii
about the cover illustration xx
1 Introduction to testing Angular applications 1
1.1 Angular testing overview 2
1.2 Getting friendly with TypeScript 3
1.3 A closer look at test types 5
Unit tests 5 ■ E2E tests 6 ■ Unit tests vs. E2E tests 7
part 1 Unit testing ................................................11
2 Creating your first tests 13
2.1 Writing tests using Jasmine 14
Writing basic tests 14
2.2 Testing classes 17
Adding the rest of the tests 21
v
vvii contents
3 Testing components 25
3.1 Basic component tests 26
3.2 Real-world component testing 29
Importing the dependencies 30 ■ Setting up the
tests 33 ■ Adding the tests 37
4 Testing directives 43
4.1 What are directives? 44
Components vs. directives 44 ■ Different directives 45
4.2 Testing attribute directives 45
Introducing the favorite icon directive 45 ■ Creating tests for
FavoriteIconDirective 48 ■ Setting up the FavoriteIconDirective
test suite 50 ■ Creating the FavoriteIconDirective tests 51
4.3 Testing structural directives 54
Introducing ShowContactsDirective 54 ■ Creating your tests for
ShowContactsDirective 55 ■ Setting up the ShowContactsDirective
test suite 56 ■ Creating the ShowContactsDirective tests 57
5 Testing pipes 59
5.1 Introducing PhoneNumberPipe 60
5.2 Testing PhoneNumberPipe 61
Testing the default usage for a pipe 61 ■ Testing a pipe with a
single parameter 65 ■ Pipes with multiple parameters 67
6 Testing services 71
6.1 What are services? 72
6.2 How do services work in Angular? 73
Dependency injection 74 ■ The @Injectable class decorator 76
6.3 Creating services with Angular CLI 76
6.4 Testing PreferencesService 77
Testing for failures 82
6.5 Testing services with promises 83
How asynchronous changes testing 86 ■ Testing for failures with
asynchronous services 88
6.6 Testing HTTP services with observables 89
contents vviiii
7 Testing the router 93
7.1 What is the Angular router? 94
Configuring the router 95 ■ Route guards: the router’s lifecycle
hooks 96
7.2 Testing routed components 97
Testing router navigation with RouterTestingModule 97 ■ Testing
router parameters 101
7.3 Testing advanced routes 105
Route guards 105 ■ Resolving data before loading a route 107
part 2 End-to-end testing ....................................109
8 Getting started with Protractor 111
8.1 How Protractor works 112
8.2 Writing your first Protractor test 114
File structure 114
8.3 Installing and running 117
8.4 Interacting with elements 118
Test scenario: creating a new contact 119 ■ Test scenario:
workflows that don’t create a new contact 123
8.5 by and element methods 125
8.6 Interacting with a list of elements 130
Filtering web elements 130 ■ Mapping the contact list to an
array 133 ■ Reduce 135
8.7 Page objects 137
9 Understanding timeouts 141
9.1 Kinds of timeouts 142
9.2 Testing pages without Angular 142
Disabling waitForAngular 143 ■ Automatically
waiting for Angular 144 ■ When to use browser.
waitForAngularEnabled() 145
9.3 Waiting with ExpectedConditions 145
Waiting for the contact list to load 146 ■ Testing a
dialog 147 ■ Waiting for elements to become stale 148
vviiiiii contents
9.4 Creating custom conditions 150
Using browser.wait 150 ■ Getting elements from the browser 151
9.5 Handling long-running tasks 152
Using expected conditions 154 ■ The browser event loop 155
What happened to $timeout? 155 ■ Highway to the Angular
zone 156 ■ Fixing the test 157
10 Advanced Protractor topics 161
10.1 Configuration file in depth 161
Driver provider options 162 ■ Desired capabilities 163
Plugins 166 ■ Environment variables 168
10.2 Screenshot testing 170
Taking screenshots 170 ■ Taking screenshots on test
failure 171 ■ Comparing screenshots 172
10.3 Experimental debugging features 176
WebDriver logs 176 ■ Highlight delay 178 ■ Blocking
proxy 179
10.4 The control flow and debugging with Chrome
DevTools 180
Asynchronous functions and promises 180 ■ The WebDriver
control flow 181 ■ The future: async/await 183 ■ Using
Chrome DevTools 184
part 3 Continuous integration ..........................189
11 Continuous integration 191
11.1 Jenkins 192
Setting up Jenkins 192 ■ Unit tests 194 ■ E2E tests 197
11.2 CircleCI 200
appendix A Setting up the sample project 203
appendix B Additional resources 209
index 211
Description:Testing is vital to the development process. It improves the quality of code and reduces maintenance, saving both time and money. But testing is sometimes neglected since there are few established resources and standards when it comes to testing modern Angular web applications. Testing Angular Appli