SlideShare a Scribd company logo
UNIT TESTING 
FRONT END 
JAVASCRIPT 
YURI TAKHTEYEV 
@QARAMAZOV 
@RANGLEIO
Why Bother with Unit Tests?
Why Bother with Unit Tests?
TDD Lite
Writing Testable Code 
☛ Modular 
code 
☛ AngularJS 
services 
☛ Other 
modules not 
entangled 
with DOM
Keeping Tests Simple
Common Tools 
Runner: Karma 
Task Automation: Gulp || Grunt 
Scorer: Mocha || Jasmine 
Assertions: Chai || Jasmine 
Spies: Sinon || Jasmin 
+ CI tools (e.g. Magnum-CI)
http://yto.io/xunit
Installing the Example Code 
# First install 
git clone https://github.com/yuri/webu-unit.git 
cd webu-unit 
npm install 
sudo npm install -g gulp 
sudo npm install -g bower 
bower install 
# Now run 
gulp karma 
☛ You’ll need to install git and node before
A Basic Test 
function isOdd(value) { 
return (value % 2 === 1); 
} 
describe('isEven', function () { 
it('should handle positive ints', function () { 
if (isOdd(2)) { 
throw new Error('2 should be even'); 
} 
}); 
}); 
☛ Let’s put this in “client/app/is-odd.test.js”
Chai 
describe('isEven', function () { 
it('should handle positive ints', function () { 
expect(isOdd(1)).to.be.true; 
expect(isOdd(2)).to.be.false; 
expect(isOdd(3)).to.be.true; 
}); 
}); 
☛ More Chai at http://chaijs.com/api/bdd/
Extending Tests 
describe('isEven', function () { 
... 
it('should handle negative ints', function () { 
expect(isOdd(-1)).to.be.true; 
}); 
});
Extending Tests 
describe('isEven', function () { 
... 
xit('should handle negative ints', function () { 
expect(isOdd(-1)).to.be.true; 
}); 
});
Extending Tests 
describe('isEven', function () { 
... 
it.only('should handle negative ints', 
function () { 
expect(isOdd(-1)).to.be.true; 
}); 
});
Extending Tests 
describe('isEven', function () { 
... 
it('should handle negative ints', function () { 
expect(isOdd(-1)).to.be.true; 
}); 
}); 
function isOdd(value) { 
return (value % 2 === 1); 
}
Testing a Service 
angular.module('app.tasks', [ 
'app.server' 
]) 
.factory('tasks', function(server) { 
var service = {}; 
service.getTasks = function () { 
return server.get('tasks'); 
}; 
return service; 
}); 
☛ Let’s put this in “client/app/tasks-service.js”
The Test, Take 1 
describe('tasks service', function () { 
beforeEach(module('app.tasks')); 
it('should get tasks', function() { 
var tasks = getService('tasks'); 
expect(tasks.getTasks()).to 
.not.be.undefined; 
}); 
}); 
☛ Let’s put this in “client/app/tasks-service.test.js” 
☛ See “client/testing/test-utils.js” for 
implementation of getService(). 
Error: [$injector:unpr] Unknown provider: 
serverProvider <- server <- tasks
Mocking Dependencies 
var data; 
beforeEach(module(function($provide){ 
$provide.service('server', function() { 
return { 
get: function() { 
return Q.when(data); 
} 
}; 
}); 
$provide.service('$q', function() { 
return Q; 
}); 
})); 
Chrome 37.0.2062 (Mac OS X 10.9.4): Executed 3 of 
3 SUCCESS (0.046 secs / 0.027 secs)
Let’s Extend the Service 
service.getMyTasks = function () { 
return server.getTasks() 
.then(function(taskArray) { 
return _.filter(taskArray, function(task) { 
return task.owner === user.userName; 
}); 
}); 
}; 
☛ We’ll need to inject “user” into the service
Mocking the User 
$provide.service('user', function() { 
return { 
username: 'yuri' 
}; 
}); 
☛ The mock can be very simple
An Async Test, Wrong 
it('should get user's tasks', function() { 
var tasks = getService('tasks'); 
data = [{ 
owner: 'bob', 
description: 'Mow the lawn' 
}, { 
owner: 'yuri', 
description: 'Save the world' 
}]; 
tasks.getMyTasks() 
.then(function(myTasks) { 
expect(myTasks.length).to.equal(1); 
}); 
}); 
☛ Always check that “wrong” tests fail!
An Async Test, Right 
it('should get user's tasks', function() { 
var tasks = getService('tasks'); 
data = [{ 
owner: 'bob', 
description: 'Mow the lawn' 
}, { 
owner: 'yuri', 
description: 'Save the world' 
}]; 
return tasks.getMyTasks() 
.then(function(myTasks) { 
expect(myTasks.length).to.equal(1); 
}); 
});
Spies with Sinon 
$provide.service('server', function() { 
return { 
get: sinon.spy(function() { 
return Q.when(data); 
}) 
}; 
}); 
var server = getService('server'); 
return tasks.getMyTasks() 
.then(function(myTasks) { 
expect(myTasks.length).to.equal(1); 
server.get.should.have.been.calledOnce; 
});
Thank You. 
Contact: 
yuri@rangle.io 
http://yto.io 
@qaramazov 
This presentation: 
http://yto.io/xunit
Image Credits 
by dunechaser 
by lincolnblues 
by spenceyc 
by creative_tools 
by mycroyance 
by angeljimenez 
by snre

More Related Content

What's hot (20)

Testing AngularJS
Testing AngularJSTesting AngularJS
Testing AngularJS
Jacopo Nardiello
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
Giovanni Lodi
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
Christoffer Noring
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
NAVER SHOPPING
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
Testing in airflow
Testing in airflowTesting in airflow
Testing in airflow
Chandulal Kavar
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
Christoffer Noring
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
bloodredsun
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Javascript: master this
Javascript: master thisJavascript: master this
Javascript: master this
Barak Drechsler
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
Vincent Pradeilles
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
Giovanni Lodi
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
NAVER SHOPPING
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
bloodredsun
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 

Viewers also liked (20)

Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
Seth McLaughlin
 
Cats, Dinosaurs and A Lot of Pizza with Reed + Rader
Cats, Dinosaurs and A Lot of Pizza with Reed + RaderCats, Dinosaurs and A Lot of Pizza with Reed + Rader
Cats, Dinosaurs and A Lot of Pizza with Reed + Rader
FITC
 
(Re)aligning The Way 400,000 People Think
(Re)aligning The Way 400,000 People Think(Re)aligning The Way 400,000 People Think
(Re)aligning The Way 400,000 People Think
FITC
 
A New Era for Animators
A New Era for AnimatorsA New Era for Animators
A New Era for Animators
FITC
 
Managing The Process
Managing The ProcessManaging The Process
Managing The Process
FITC
 
Components are the Future of the Web: It’s Going To Be Okay
Components are the Future of the Web: It’s Going To Be OkayComponents are the Future of the Web: It’s Going To Be Okay
Components are the Future of the Web: It’s Going To Be Okay
FITC
 
The Browser Is Dead, Long Live The Web!
The Browser Is Dead, Long Live The Web!The Browser Is Dead, Long Live The Web!
The Browser Is Dead, Long Live The Web!
FITC
 
Getting to Know Grunt By Writing Your Own Plugin
Getting to Know Grunt By Writing Your Own PluginGetting to Know Grunt By Writing Your Own Plugin
Getting to Know Grunt By Writing Your Own Plugin
FITC
 
It’s the Experience That Makes the Product, Not the Features
It’s the Experience That Makes the Product, Not the FeaturesIt’s the Experience That Makes the Product, Not the Features
It’s the Experience That Makes the Product, Not the Features
FITC
 
Front-end Tools: Sifting Through the Madness
 Front-end Tools: Sifting Through the Madness Front-end Tools: Sifting Through the Madness
Front-end Tools: Sifting Through the Madness
FITC
 
Designing True Cross-Platform Apps
Designing True Cross-Platform AppsDesigning True Cross-Platform Apps
Designing True Cross-Platform Apps
FITC
 
Graphic Designer to Object Designer: Your 3D Printing Evolution
Graphic Designer to Object Designer: Your 3D Printing EvolutionGraphic Designer to Object Designer: Your 3D Printing Evolution
Graphic Designer to Object Designer: Your 3D Printing Evolution
FITC
 
Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015
Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015
Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015
FITC
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the Browser
FITC
 
5 Things Every Designer Should be Doing Right Now
5 Things Every Designer Should be Doing Right Now5 Things Every Designer Should be Doing Right Now
5 Things Every Designer Should be Doing Right Now
FITC
 
Functional Web Development
Functional Web DevelopmentFunctional Web Development
Functional Web Development
FITC
 
Pocket web gl sk
Pocket web gl skPocket web gl sk
Pocket web gl sk
FITC
 
Designing Interactive Experiences for Kids of All Ages with Mark Argo
Designing Interactive Experiences for Kids of All Ages with Mark ArgoDesigning Interactive Experiences for Kids of All Ages with Mark Argo
Designing Interactive Experiences for Kids of All Ages with Mark Argo
FITC
 
Kickstarting Your Stupid Magazine
Kickstarting Your Stupid MagazineKickstarting Your Stupid Magazine
Kickstarting Your Stupid Magazine
FITC
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
Seth McLaughlin
 
Cats, Dinosaurs and A Lot of Pizza with Reed + Rader
Cats, Dinosaurs and A Lot of Pizza with Reed + RaderCats, Dinosaurs and A Lot of Pizza with Reed + Rader
Cats, Dinosaurs and A Lot of Pizza with Reed + Rader
FITC
 
(Re)aligning The Way 400,000 People Think
(Re)aligning The Way 400,000 People Think(Re)aligning The Way 400,000 People Think
(Re)aligning The Way 400,000 People Think
FITC
 
A New Era for Animators
A New Era for AnimatorsA New Era for Animators
A New Era for Animators
FITC
 
Managing The Process
Managing The ProcessManaging The Process
Managing The Process
FITC
 
Components are the Future of the Web: It’s Going To Be Okay
Components are the Future of the Web: It’s Going To Be OkayComponents are the Future of the Web: It’s Going To Be Okay
Components are the Future of the Web: It’s Going To Be Okay
FITC
 
The Browser Is Dead, Long Live The Web!
The Browser Is Dead, Long Live The Web!The Browser Is Dead, Long Live The Web!
The Browser Is Dead, Long Live The Web!
FITC
 
Getting to Know Grunt By Writing Your Own Plugin
Getting to Know Grunt By Writing Your Own PluginGetting to Know Grunt By Writing Your Own Plugin
Getting to Know Grunt By Writing Your Own Plugin
FITC
 
It’s the Experience That Makes the Product, Not the Features
It’s the Experience That Makes the Product, Not the FeaturesIt’s the Experience That Makes the Product, Not the Features
It’s the Experience That Makes the Product, Not the Features
FITC
 
Front-end Tools: Sifting Through the Madness
 Front-end Tools: Sifting Through the Madness Front-end Tools: Sifting Through the Madness
Front-end Tools: Sifting Through the Madness
FITC
 
Designing True Cross-Platform Apps
Designing True Cross-Platform AppsDesigning True Cross-Platform Apps
Designing True Cross-Platform Apps
FITC
 
Graphic Designer to Object Designer: Your 3D Printing Evolution
Graphic Designer to Object Designer: Your 3D Printing EvolutionGraphic Designer to Object Designer: Your 3D Printing Evolution
Graphic Designer to Object Designer: Your 3D Printing Evolution
FITC
 
Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015
Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015
Upgrading the Web with Douglas Crockford @ FITC's Web Unleashed 2015
FITC
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the Browser
FITC
 
5 Things Every Designer Should be Doing Right Now
5 Things Every Designer Should be Doing Right Now5 Things Every Designer Should be Doing Right Now
5 Things Every Designer Should be Doing Right Now
FITC
 
Functional Web Development
Functional Web DevelopmentFunctional Web Development
Functional Web Development
FITC
 
Pocket web gl sk
Pocket web gl skPocket web gl sk
Pocket web gl sk
FITC
 
Designing Interactive Experiences for Kids of All Ages with Mark Argo
Designing Interactive Experiences for Kids of All Ages with Mark ArgoDesigning Interactive Experiences for Kids of All Ages with Mark Argo
Designing Interactive Experiences for Kids of All Ages with Mark Argo
FITC
 
Kickstarting Your Stupid Magazine
Kickstarting Your Stupid MagazineKickstarting Your Stupid Magazine
Kickstarting Your Stupid Magazine
FITC
 
Ad

Similar to Unit Testing Front End JavaScript (20)

Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
Nir Kaufman
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
FITC
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
Jim Lynch
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
Michael Haberman
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
Prince Norin
 
Angular testing
Angular testingAngular testing
Angular testing
Raissa Ferreira
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...
Gavin Pickin
 
ITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenches
Ortus Solutions, Corp
 
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven TomacJavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim Lynch
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Katy Slemon
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
Andrey Kolodnitsky
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End Developers
FITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
Roy Yu
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)
Anna Khabibullina
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014
DA-14
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
Nir Kaufman
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
FITC
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
Jim Lynch
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
Michael Haberman
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
Prince Norin
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...
Gavin Pickin
 
ITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenchesITB2016 -BDD testing and automation from the trenches
ITB2016 -BDD testing and automation from the trenches
Ortus Solutions, Corp
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim Lynch
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Katy Slemon
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
Andrey Kolodnitsky
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End Developers
FITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
Roy Yu
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)
Anna Khabibullina
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014
DA-14
 
Ad

More from FITC (20)

Cut it up
Cut it upCut it up
Cut it up
FITC
 
Designing for Digital Health
Designing for Digital HealthDesigning for Digital Health
Designing for Digital Health
FITC
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
FITC
 
Surviving Your Tech Stack
Surviving Your Tech StackSurviving Your Tech Stack
Surviving Your Tech Stack
FITC
 
How to Pitch Your First AR Project
How to Pitch Your First AR ProjectHow to Pitch Your First AR Project
How to Pitch Your First AR Project
FITC
 
Start by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the AnswerStart by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the Answer
FITC
 
Cocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s StoryCocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s Story
FITC
 
Everyday Innovation
Everyday InnovationEveryday Innovation
Everyday Innovation
FITC
 
HyperLight Websites
HyperLight WebsitesHyperLight Websites
HyperLight Websites
FITC
 
Everything is Terrifying
Everything is TerrifyingEverything is Terrifying
Everything is Terrifying
FITC
 
Post-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future HumanPost-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future Human
FITC
 
The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)
FITC
 
East of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR GameEast of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR Game
FITC
 
Creating a Proactive Healthcare System
Creating a Proactive Healthcare SystemCreating a Proactive Healthcare System
Creating a Proactive Healthcare System
FITC
 
World Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product DesignWorld Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product Design
FITC
 
The Power of Now
The Power of NowThe Power of Now
The Power of Now
FITC
 
High Performance PWAs
High Performance PWAsHigh Performance PWAs
High Performance PWAs
FITC
 
Rise of the JAMstack
Rise of the JAMstackRise of the JAMstack
Rise of the JAMstack
FITC
 
From Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self DiscoveryFrom Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self Discovery
FITC
 
Projects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time ForProjects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time For
FITC
 
Cut it up
Cut it upCut it up
Cut it up
FITC
 
Designing for Digital Health
Designing for Digital HealthDesigning for Digital Health
Designing for Digital Health
FITC
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
FITC
 
Surviving Your Tech Stack
Surviving Your Tech StackSurviving Your Tech Stack
Surviving Your Tech Stack
FITC
 
How to Pitch Your First AR Project
How to Pitch Your First AR ProjectHow to Pitch Your First AR Project
How to Pitch Your First AR Project
FITC
 
Start by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the AnswerStart by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the Answer
FITC
 
Cocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s StoryCocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s Story
FITC
 
Everyday Innovation
Everyday InnovationEveryday Innovation
Everyday Innovation
FITC
 
HyperLight Websites
HyperLight WebsitesHyperLight Websites
HyperLight Websites
FITC
 
Everything is Terrifying
Everything is TerrifyingEverything is Terrifying
Everything is Terrifying
FITC
 
Post-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future HumanPost-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future Human
FITC
 
The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)
FITC
 
East of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR GameEast of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR Game
FITC
 
Creating a Proactive Healthcare System
Creating a Proactive Healthcare SystemCreating a Proactive Healthcare System
Creating a Proactive Healthcare System
FITC
 
World Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product DesignWorld Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product Design
FITC
 
The Power of Now
The Power of NowThe Power of Now
The Power of Now
FITC
 
High Performance PWAs
High Performance PWAsHigh Performance PWAs
High Performance PWAs
FITC
 
Rise of the JAMstack
Rise of the JAMstackRise of the JAMstack
Rise of the JAMstack
FITC
 
From Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self DiscoveryFrom Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self Discovery
FITC
 
Projects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time ForProjects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time For
FITC
 

Recently uploaded (20)

MOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary detailsMOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary details
benamorraj
 
LpQuantueer rtwrt 1e erere errerqer m.ppt
LpQuantueer rtwrt 1e erere errerqer m.pptLpQuantueer rtwrt 1e erere errerqer m.ppt
LpQuantueer rtwrt 1e erere errerqer m.ppt
cyberesearchprof
 
Cloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptxCloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptx
islamicknowledge5224
 
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptxInter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
secretarysocom
 
AI theory work for students to understand the logic
AI theory work for students to understand the logicAI theory work for students to understand the logic
AI theory work for students to understand the logic
areeba15775n
 
Unlocking Business Growth Through Targeted Social Engagement
Unlocking Business Growth Through Targeted Social EngagementUnlocking Business Growth Through Targeted Social Engagement
Unlocking Business Growth Through Targeted Social Engagement
Digital Guider
 
DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19
APNIC
 
Internet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet SystemInternet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet System
cpnabil59
 
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
CartCoders
 
3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen
Jago de Vreede
 
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animationUV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
17218
 
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
Taqyea
 
3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx
islamicknowledge5224
 
In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...
raguclc
 
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM HallucinationsCBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
Jason Packer
 
Quantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptxQuantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptx
cyberesearchprof
 
Timeline Infographics Para utilização diária
Timeline Infographics Para utilização diáriaTimeline Infographics Para utilização diária
Timeline Infographics Para utilização diária
meslellis
 
simple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptxsimple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptx
ashokjayapal
 
Vigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptxVigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptx
secretarysocom
 
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdfPredicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Behzad Hussain
 
MOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary detailsMOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary details
benamorraj
 
LpQuantueer rtwrt 1e erere errerqer m.ppt
LpQuantueer rtwrt 1e erere errerqer m.pptLpQuantueer rtwrt 1e erere errerqer m.ppt
LpQuantueer rtwrt 1e erere errerqer m.ppt
cyberesearchprof
 
Cloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptxCloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptx
islamicknowledge5224
 
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptxInter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
secretarysocom
 
AI theory work for students to understand the logic
AI theory work for students to understand the logicAI theory work for students to understand the logic
AI theory work for students to understand the logic
areeba15775n
 
Unlocking Business Growth Through Targeted Social Engagement
Unlocking Business Growth Through Targeted Social EngagementUnlocking Business Growth Through Targeted Social Engagement
Unlocking Business Growth Through Targeted Social Engagement
Digital Guider
 
DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19
APNIC
 
Internet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet SystemInternet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet System
cpnabil59
 
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
CartCoders
 
3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen
Jago de Vreede
 
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animationUV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
17218
 
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
Taqyea
 
3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx
islamicknowledge5224
 
In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...
raguclc
 
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM HallucinationsCBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
Jason Packer
 
Quantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptxQuantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptx
cyberesearchprof
 
Timeline Infographics Para utilização diária
Timeline Infographics Para utilização diáriaTimeline Infographics Para utilização diária
Timeline Infographics Para utilização diária
meslellis
 
simple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptxsimple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptx
ashokjayapal
 
Vigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptxVigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptx
secretarysocom
 
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdfPredicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Behzad Hussain
 

Unit Testing Front End JavaScript

  • 1. UNIT TESTING FRONT END JAVASCRIPT YURI TAKHTEYEV @QARAMAZOV @RANGLEIO
  • 2. Why Bother with Unit Tests?
  • 3. Why Bother with Unit Tests?
  • 5. Writing Testable Code ☛ Modular code ☛ AngularJS services ☛ Other modules not entangled with DOM
  • 7. Common Tools Runner: Karma Task Automation: Gulp || Grunt Scorer: Mocha || Jasmine Assertions: Chai || Jasmine Spies: Sinon || Jasmin + CI tools (e.g. Magnum-CI)
  • 9. Installing the Example Code # First install git clone https://github.com/yuri/webu-unit.git cd webu-unit npm install sudo npm install -g gulp sudo npm install -g bower bower install # Now run gulp karma ☛ You’ll need to install git and node before
  • 10. A Basic Test function isOdd(value) { return (value % 2 === 1); } describe('isEven', function () { it('should handle positive ints', function () { if (isOdd(2)) { throw new Error('2 should be even'); } }); }); ☛ Let’s put this in “client/app/is-odd.test.js”
  • 11. Chai describe('isEven', function () { it('should handle positive ints', function () { expect(isOdd(1)).to.be.true; expect(isOdd(2)).to.be.false; expect(isOdd(3)).to.be.true; }); }); ☛ More Chai at http://chaijs.com/api/bdd/
  • 12. Extending Tests describe('isEven', function () { ... it('should handle negative ints', function () { expect(isOdd(-1)).to.be.true; }); });
  • 13. Extending Tests describe('isEven', function () { ... xit('should handle negative ints', function () { expect(isOdd(-1)).to.be.true; }); });
  • 14. Extending Tests describe('isEven', function () { ... it.only('should handle negative ints', function () { expect(isOdd(-1)).to.be.true; }); });
  • 15. Extending Tests describe('isEven', function () { ... it('should handle negative ints', function () { expect(isOdd(-1)).to.be.true; }); }); function isOdd(value) { return (value % 2 === 1); }
  • 16. Testing a Service angular.module('app.tasks', [ 'app.server' ]) .factory('tasks', function(server) { var service = {}; service.getTasks = function () { return server.get('tasks'); }; return service; }); ☛ Let’s put this in “client/app/tasks-service.js”
  • 17. The Test, Take 1 describe('tasks service', function () { beforeEach(module('app.tasks')); it('should get tasks', function() { var tasks = getService('tasks'); expect(tasks.getTasks()).to .not.be.undefined; }); }); ☛ Let’s put this in “client/app/tasks-service.test.js” ☛ See “client/testing/test-utils.js” for implementation of getService(). Error: [$injector:unpr] Unknown provider: serverProvider <- server <- tasks
  • 18. Mocking Dependencies var data; beforeEach(module(function($provide){ $provide.service('server', function() { return { get: function() { return Q.when(data); } }; }); $provide.service('$q', function() { return Q; }); })); Chrome 37.0.2062 (Mac OS X 10.9.4): Executed 3 of 3 SUCCESS (0.046 secs / 0.027 secs)
  • 19. Let’s Extend the Service service.getMyTasks = function () { return server.getTasks() .then(function(taskArray) { return _.filter(taskArray, function(task) { return task.owner === user.userName; }); }); }; ☛ We’ll need to inject “user” into the service
  • 20. Mocking the User $provide.service('user', function() { return { username: 'yuri' }; }); ☛ The mock can be very simple
  • 21. An Async Test, Wrong it('should get user's tasks', function() { var tasks = getService('tasks'); data = [{ owner: 'bob', description: 'Mow the lawn' }, { owner: 'yuri', description: 'Save the world' }]; tasks.getMyTasks() .then(function(myTasks) { expect(myTasks.length).to.equal(1); }); }); ☛ Always check that “wrong” tests fail!
  • 22. An Async Test, Right it('should get user's tasks', function() { var tasks = getService('tasks'); data = [{ owner: 'bob', description: 'Mow the lawn' }, { owner: 'yuri', description: 'Save the world' }]; return tasks.getMyTasks() .then(function(myTasks) { expect(myTasks.length).to.equal(1); }); });
  • 23. Spies with Sinon $provide.service('server', function() { return { get: sinon.spy(function() { return Q.when(data); }) }; }); var server = getService('server'); return tasks.getMyTasks() .then(function(myTasks) { expect(myTasks.length).to.equal(1); server.get.should.have.been.calledOnce; });
  • 24. Thank You. Contact: [email protected] http://yto.io @qaramazov This presentation: http://yto.io/xunit
  • 25. Image Credits by dunechaser by lincolnblues by spenceyc by creative_tools by mycroyance by angeljimenez by snre