SlideShare a Scribd company logo
1 of 32
Angular 2 Unit Testing
October 25, 2016
Vikram Subramanian
Google
Introduction
● Angular 2.0 final!
● Changes in Test API from RC to final
○ Decrease number of concepts and boilerplate
○ Independent of test framework
○ NgModule
Introduction
Pragmatic Unit testing
● Decisions to make
● Testing Recipes
Decisions
Should I write unit tests?
○ Yes
○ Yes!!
Framework to use
○ Jasmine
○ Mocha
Test Runner
○ Karma
Decisions - Angular specific
● Testing Module Setup
○ How much to mock?
○ Isolation vs Being close to production
● Test Method Setup
○ () => { }
○ async() => { }
○ fakeAsync() => { }
Decisions - Angular specific (contd.)
● Locating elements
○ Using DOM API
○ Using DebugElement
● Dispatching events
○ Using DOM API
○ Using DebugElement
Recipes
Simple Component with templateUrl
Recipes - Simple Component with templateUrl
[app.component.ts]
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html'
})
export class AppComponent {}
[app.component.html]
<h1>My First Angular App</h1>
Recipes - Simple Component with templateUrl
[app.component.spec.ts]
...
beforeEach(async(() => {
TestBed.configureTestingModule({imports: [AppModule]});
// Precompile components with templateUrl.
TestBed.compileComponents();
}));
...
Recipes - Simple Component with templateUrl
[app.component.spec.ts]
...
// Synchronous test method.
it('displays properly', () => {
let fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe("My First Angular App");
});
...
Recipes
Component communicating with backend service
Component
Users Service
Backend
Angular App
Recipes - Component Communicating with Backend service
beforeEach(async(() => {
TestBed.configureTestingModule({imports: [AppModule]});
// Override providers for the UsersService in the App module.
TestBed.overrideModule(AppModule,
{set:
{providers: [{provide: UsersService, useClass: MockUsersService}]}
}
);
TestBed.compileComponents();
}));
Recipes - Component Communicating with Backend service
it('displays user details on click', async(() => {
...
// Locate the fetch button.
let debugFetchButton = fixture.debugElement.query(By.css('button'));
expect(debugFetchButton).not.toBe(null);
// Trigger the click event through the DOM.
debugFetchButton.nativeElement.click();
...
}
Recipes - Component Communicating with Backend service
it('displays users list on click', async(() => {
...
// Wait for the async getUsers to complete and Angular to become stable.
fixture.whenStable().then(() => {
// Trigger rendering component state to DOM.
fixture.detectChanges();
// Check that the user list is displayed.
...
}
}
Recipes - Component Communicating with Backend service
// fakeAsync() version.
it('displays user details on click(fakeAsync)', fakeAsync(() => {
...
// Trigger the click event through the DOM.
debugFetchButton.nativeElement.click();
// Wait for Promise resolution and Angular to stabilize.
tick();
fixture.detectChanges();
...
}
Recipes - Component Communicating with Backend service
import {XHRBackend} from '@angular/http';
import {MockBackend} from '@angular/http/testing';
...
// Setup for mocking the HTTP Backend.
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
UsersService,
{ provide: XHRBackend, useClass: MockBackend }
]
...
Recipes - Component Communicating with Backend service
it('returns all users', async(() => {
let backend = TestBed.get(XHRBackend);
let http = TestBed.get(Http);
let service = new UsersService(http);
let fakeUsers = makeUsers();
let options = new ResponseOptions({status: 200, body: fakeUsers});
let response = new Response(options);
backend.connections.subscribe(
(c: MockConnection) => c.mockRespond(response));
service.getUsers().then(users => { ...
Recipes
Testing Application Routing
Recipes - Testing Application Routing
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes(ROUTES),
AppModule
]
});
Recipes - Testing Application Routing
// async version
router.navigateByUrl('/about');
fixture.whenStable().then(() => {
fixture.detectChanges();
// Verify we navigated to About page.
let desc = fixture.debugElement.query(By.css('.description'));
expect(desc).not.toBe(null);
expect(desc.nativeElement.textContent).toContain('All about this sample');
});
Recipes - Testing Application Routing
// fakeAsync Version
router.navigateByUrl('/about');
tick();
fixture.detectChanges();
// Verify we navigated to About page.
let desc = fixture.debugElement.query(By.css('.description'));
expect(desc).not.toBe(null);
expect(desc.nativeElement.textContent).toContain('All about this sample');
Recipes
Testing Nested Components
Recipes - Testing Nested Components
[app.component.html]
<app-banner></app-banner>
<app-welcome></app-welcome>
<user-details></user-details>
Testing nested components - Approach 1
Don’t mock out anything
beforeEach(async(() => {
TestBed.configureTestingModule({imports: [AppModule]});
TestBed.compileComponents();
}));
Testing nested components - Approach 2
Mock all dependencies
...
TestBed.configureTestingModule({
declarations: [AppComponent, MockBannerComponent,
MockWelcomeComponent, MockUserDetailsComponent],
});
...
Testing nested components - Approach 3
Shallow Testing - NO_ERRORS_SCHEMA
...
TestBed.configureTestingModule({
declarations: [AppComponent],
schemas: [NO_ERRORS_SCHEMA],
});
...
WRITE UNIT TESTS!!
Resources
● Angular.io Testing Guide
● Testing Angular 2 - Julie Ralph
● Three ways to test Angular 2 components
Acknowledgements
● Mashhood Rastgar, Gerard Sans - Ideas for the talk
● Jasmine Plunker template - Ken Rimple - @krimple
● Ward and the docs team for putting up the best docs
Backup
Properties of good unit tests
● Fast
● Isolated
● Repeatable
● Self-verifying
● Timely
Source: https://pragprog.com/magazines/2012-01/unit-tests-are-first

More Related Content

Similar to Angular 2 Unit Testing.pptx

Introduction to Angular2
Introduction to Angular2Introduction to Angular2
Introduction to Angular2Ivan Matiishyn
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Frost
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Justin James
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement BardejovTesting in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement BardejovMarian Rusnak
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6William Marques
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Naveen Pete
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web developmentalice yang
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with exampleshadabgilani
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
 

Similar to Angular 2 Unit Testing.pptx (20)

Introduction to Angular2
Introduction to Angular2Introduction to Angular2
Introduction to Angular2
 
Angular js
Angular jsAngular js
Angular js
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement BardejovTesting in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6
 
React loadable
React loadableReact loadable
React loadable
 
mean stack
mean stackmean stack
mean stack
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
Angular 2.0 - What to expect
Angular 2.0 - What to expectAngular 2.0 - What to expect
Angular 2.0 - What to expect
 

More from accordv12

TypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptxTypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptxaccordv12
 
Lttctt ngân hàng trung ương
Lttctt   ngân hàng trung ươngLttctt   ngân hàng trung ương
Lttctt ngân hàng trung ươngaccordv12
 
Lt tctt chương 3
Lt tctt   chương 3Lt tctt   chương 3
Lt tctt chương 3accordv12
 
Lt tctt chương 1
Lt tctt   chương 1Lt tctt   chương 1
Lt tctt chương 1accordv12
 
Chapter tgtc
Chapter tgtcChapter tgtc
Chapter tgtcaccordv12
 
Kỹ thuật lập trình mảng và các giải thuật với mảng
Kỹ thuật lập trình   mảng và các giải thuật với mảngKỹ thuật lập trình   mảng và các giải thuật với mảng
Kỹ thuật lập trình mảng và các giải thuật với mảngaccordv12
 

More from accordv12 (7)

TypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptxTypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptx
 
Lttctt ngân hàng trung ương
Lttctt   ngân hàng trung ươngLttctt   ngân hàng trung ương
Lttctt ngân hàng trung ương
 
Lt tctt chương 3
Lt tctt   chương 3Lt tctt   chương 3
Lt tctt chương 3
 
Lt tctt chương 1
Lt tctt   chương 1Lt tctt   chương 1
Lt tctt chương 1
 
Chapter tgtc
Chapter tgtcChapter tgtc
Chapter tgtc
 
Nsnn
NsnnNsnn
Nsnn
 
Kỹ thuật lập trình mảng và các giải thuật với mảng
Kỹ thuật lập trình   mảng và các giải thuật với mảngKỹ thuật lập trình   mảng và các giải thuật với mảng
Kỹ thuật lập trình mảng và các giải thuật với mảng
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 

Recently uploaded (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Angular 2 Unit Testing.pptx

  • 1. Angular 2 Unit Testing October 25, 2016 Vikram Subramanian Google
  • 2. Introduction ● Angular 2.0 final! ● Changes in Test API from RC to final ○ Decrease number of concepts and boilerplate ○ Independent of test framework ○ NgModule
  • 3. Introduction Pragmatic Unit testing ● Decisions to make ● Testing Recipes
  • 4. Decisions Should I write unit tests? ○ Yes ○ Yes!! Framework to use ○ Jasmine ○ Mocha Test Runner ○ Karma
  • 5. Decisions - Angular specific ● Testing Module Setup ○ How much to mock? ○ Isolation vs Being close to production ● Test Method Setup ○ () => { } ○ async() => { } ○ fakeAsync() => { }
  • 6. Decisions - Angular specific (contd.) ● Locating elements ○ Using DOM API ○ Using DebugElement ● Dispatching events ○ Using DOM API ○ Using DebugElement
  • 8. Recipes - Simple Component with templateUrl [app.component.ts] @Component({ moduleId: module.id, selector: 'my-app', templateUrl: 'app.component.html' }) export class AppComponent {} [app.component.html] <h1>My First Angular App</h1>
  • 9. Recipes - Simple Component with templateUrl [app.component.spec.ts] ... beforeEach(async(() => { TestBed.configureTestingModule({imports: [AppModule]}); // Precompile components with templateUrl. TestBed.compileComponents(); })); ...
  • 10. Recipes - Simple Component with templateUrl [app.component.spec.ts] ... // Synchronous test method. it('displays properly', () => { let fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe("My First Angular App"); }); ...
  • 13. Recipes - Component Communicating with Backend service beforeEach(async(() => { TestBed.configureTestingModule({imports: [AppModule]}); // Override providers for the UsersService in the App module. TestBed.overrideModule(AppModule, {set: {providers: [{provide: UsersService, useClass: MockUsersService}]} } ); TestBed.compileComponents(); }));
  • 14. Recipes - Component Communicating with Backend service it('displays user details on click', async(() => { ... // Locate the fetch button. let debugFetchButton = fixture.debugElement.query(By.css('button')); expect(debugFetchButton).not.toBe(null); // Trigger the click event through the DOM. debugFetchButton.nativeElement.click(); ... }
  • 15. Recipes - Component Communicating with Backend service it('displays users list on click', async(() => { ... // Wait for the async getUsers to complete and Angular to become stable. fixture.whenStable().then(() => { // Trigger rendering component state to DOM. fixture.detectChanges(); // Check that the user list is displayed. ... } }
  • 16. Recipes - Component Communicating with Backend service // fakeAsync() version. it('displays user details on click(fakeAsync)', fakeAsync(() => { ... // Trigger the click event through the DOM. debugFetchButton.nativeElement.click(); // Wait for Promise resolution and Angular to stabilize. tick(); fixture.detectChanges(); ... }
  • 17. Recipes - Component Communicating with Backend service import {XHRBackend} from '@angular/http'; import {MockBackend} from '@angular/http/testing'; ... // Setup for mocking the HTTP Backend. beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpModule], providers: [ UsersService, { provide: XHRBackend, useClass: MockBackend } ] ...
  • 18. Recipes - Component Communicating with Backend service it('returns all users', async(() => { let backend = TestBed.get(XHRBackend); let http = TestBed.get(Http); let service = new UsersService(http); let fakeUsers = makeUsers(); let options = new ResponseOptions({status: 200, body: fakeUsers}); let response = new Response(options); backend.connections.subscribe( (c: MockConnection) => c.mockRespond(response)); service.getUsers().then(users => { ...
  • 20. Recipes - Testing Application Routing TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes(ROUTES), AppModule ] });
  • 21. Recipes - Testing Application Routing // async version router.navigateByUrl('/about'); fixture.whenStable().then(() => { fixture.detectChanges(); // Verify we navigated to About page. let desc = fixture.debugElement.query(By.css('.description')); expect(desc).not.toBe(null); expect(desc.nativeElement.textContent).toContain('All about this sample'); });
  • 22. Recipes - Testing Application Routing // fakeAsync Version router.navigateByUrl('/about'); tick(); fixture.detectChanges(); // Verify we navigated to About page. let desc = fixture.debugElement.query(By.css('.description')); expect(desc).not.toBe(null); expect(desc.nativeElement.textContent).toContain('All about this sample');
  • 24. Recipes - Testing Nested Components [app.component.html] <app-banner></app-banner> <app-welcome></app-welcome> <user-details></user-details>
  • 25. Testing nested components - Approach 1 Don’t mock out anything beforeEach(async(() => { TestBed.configureTestingModule({imports: [AppModule]}); TestBed.compileComponents(); }));
  • 26. Testing nested components - Approach 2 Mock all dependencies ... TestBed.configureTestingModule({ declarations: [AppComponent, MockBannerComponent, MockWelcomeComponent, MockUserDetailsComponent], }); ...
  • 27. Testing nested components - Approach 3 Shallow Testing - NO_ERRORS_SCHEMA ... TestBed.configureTestingModule({ declarations: [AppComponent], schemas: [NO_ERRORS_SCHEMA], }); ...
  • 29. Resources ● Angular.io Testing Guide ● Testing Angular 2 - Julie Ralph ● Three ways to test Angular 2 components
  • 30. Acknowledgements ● Mashhood Rastgar, Gerard Sans - Ideas for the talk ● Jasmine Plunker template - Ken Rimple - @krimple ● Ward and the docs team for putting up the best docs
  • 31.
  • 32. Backup Properties of good unit tests ● Fast ● Isolated ● Repeatable ● Self-verifying ● Timely Source: https://pragprog.com/magazines/2012-01/unit-tests-are-first

Editor's Notes

  1. Decisions to take while unit testing and some recipes for some common situations that arise during Angular development
  2. High level decisions that you take once per project
  3. Decisions to take per module/component that are more Angular specific
  4. Prefer DOM API - If Component is tied to DOM Renderer anyway DebugElement - Renderer independent way and also query by Directive type
  5. http://embed.plnkr.co/aTS4NZjeUIpIGTqZwEl9/
  6. Asynchronous is contained in the test setup in beforeEach. The actual test method itself can be synchronous
  7. Reuse NgModule from the application and use overrideModule to override any of the module settings
  8. Locate and trigger events on component elements
  9. fixture.whenStable - Wait for Angular to stabilize. Similar to what Protractor does in E2E tests
  10. Same test written using fakeAsync. fakeAsync lets you control the async event queue in a synchronous manner through the magic of Zone.js.