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

PPT
AngularJS Testing Strategies
Β 
PDF
Redux Sagas - React Alicante
PPTX
React hooks
PPTX
The redux saga begins
PDF
activity_and_fragment_may_2020_lakopi
ODP
Angular JS Unit Testing - Overview
PDF
The evolution of redux action creators
PDF
Redux saga: managing your side effects. Also: generators in es6
AngularJS Testing Strategies
Β 
Redux Sagas - React Alicante
React hooks
The redux saga begins
activity_and_fragment_may_2020_lakopi
Angular JS Unit Testing - Overview
The evolution of redux action creators
Redux saga: managing your side effects. Also: generators in es6

What's hot (20)

PDF
Testing AngularJS
PDF
Workshop 23: ReactJS, React & Redux testing
PDF
React new features and intro to Hooks
Β 
PPTX
LinkedIn TBC JavaScript 100: Functions
PDF
Functional Core, Reactive Shell
PPTX
Firebase ng2 zurich
PPTX
Typescript barcelona
PDF
UI λͺ¨λ“ˆν™”λ‘œ μ›ŒλΌλ°Έ μ§€ν‚€κΈ°
PPTX
Full Stack Unit Testing
PDF
Understanding react hooks
PDF
Stop Making Excuses and Start Testing Your JavaScript
PPTX
Testing in airflow
PPTX
Rxjs swetugg
PDF
Unit Testing Express and Koa Middleware in ES2015
PDF
Martin Anderson - threads v actors
PPTX
Avoiding callback hell in Node js using promises
PPTX
Javascript: master this
PDF
Cocoa heads 09112017
PDF
Douglas Crockford: Serversideness
PDF
JavaScript Functions
Testing AngularJS
Workshop 23: ReactJS, React & Redux testing
React new features and intro to Hooks
Β 
LinkedIn TBC JavaScript 100: Functions
Functional Core, Reactive Shell
Firebase ng2 zurich
Typescript barcelona
UI λͺ¨λ“ˆν™”λ‘œ μ›ŒλΌλ°Έ μ§€ν‚€κΈ°
Full Stack Unit Testing
Understanding react hooks
Stop Making Excuses and Start Testing Your JavaScript
Testing in airflow
Rxjs swetugg
Unit Testing Express and Koa Middleware in ES2015
Martin Anderson - threads v actors
Avoiding callback hell in Node js using promises
Javascript: master this
Cocoa heads 09112017
Douglas Crockford: Serversideness
JavaScript Functions
Ad

Viewers also liked (20)

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

Similar to Unit Testing Front End JavaScript (20)

PDF
Unit Testing - The Whys, Whens and Hows
PDF
Angularjs - Unit testing introduction
PDF
Angularjs Test Driven Development (TDD)
PDF
Test-Driven Development of AngularJS Applications
Β 
PDF
Describe's Full of It's
PDF
Unit-testing and E2E testing in JS
PPTX
AngularJS Unit Testing
PDF
Angular testing
PDF
BDD Testing and Automating from the trenches - Presented at Into The Box June...
PDF
ITB2016 -BDD testing and automation from the trenches
PDF
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
PDF
Intro to Unit Testing in AngularJS
PDF
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
PPTX
Unit testing in JavaScript with Jasmine and Karma
PDF
An Introduction to the World of Testing for Front-End Developers
Β 
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
PPTX
Javascript Testing with Jasmine 101
Β 
PPTX
JS Frameworks Day April,26 of 2014
Β 
PDF
Js fwdays unit tesing javascript(by Anna Khabibullina)
Unit Testing - The Whys, Whens and Hows
Angularjs - Unit testing introduction
Angularjs Test Driven Development (TDD)
Test-Driven Development of AngularJS Applications
Β 
Describe's Full of It's
Unit-testing and E2E testing in JS
AngularJS Unit Testing
Angular testing
BDD Testing and Automating from the trenches - Presented at Into The Box June...
ITB2016 -BDD testing and automation from the trenches
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
Intro to Unit Testing in AngularJS
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Intro To JavaScript Unit Testing - Ran Mizrahi
Unit testing in JavaScript with Jasmine and Karma
An Introduction to the World of Testing for Front-End Developers
Β 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Javascript Testing with Jasmine 101
Β 
JS Frameworks Day April,26 of 2014
Β 
Js fwdays unit tesing javascript(by Anna Khabibullina)

More from FITC (20)

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

Recently uploaded (20)

PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
Β 
PDF
Introduction to the IoT system, how the IoT system works
PPTX
SAP Ariba Sourcing PPT for learning material
PPTX
Funds Management Learning Material for Beg
PPTX
innovation process that make everything different.pptx
PPT
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
PPTX
PptxGenJS_Demo_Chart_20250317130215833.pptx
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
Introduction to Information and Communication Technology
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPT
tcp ip networks nd ip layering assotred slides
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
Exploring VPS Hosting Trends for SMBs in 2025
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PDF
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
PPTX
newyork.pptxirantrafgshenepalchinachinane
international classification of diseases ICD-10 review PPT.pptx
Power Point - Lesson 3_2.pptx grad school presentation
Β 
Introduction to the IoT system, how the IoT system works
SAP Ariba Sourcing PPT for learning material
Funds Management Learning Material for Beg
innovation process that make everything different.pptx
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
PptxGenJS_Demo_Chart_20250317130215833.pptx
Tenda Login Guide: Access Your Router in 5 Easy Steps
Introduction to Information and Communication Technology
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
tcp ip networks nd ip layering assotred slides
SASE Traffic Flow - ZTNA Connector-1.pdf
Slides PDF The World Game (s) Eco Economic Epochs.pdf
Exploring VPS Hosting Trends for SMBs in 2025
Job_Card_System_Styled_lorem_ipsum_.pptx
introduction about ICD -10 & ICD-11 ppt.pptx
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
newyork.pptxirantrafgshenepalchinachinane

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: yuri@rangle.io 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