SlideShare a Scribd company logo
В поисках качества
JavaScript:
модульное тестирование
Анна Хабибуллина
DA-14 / da-14.com
anna.khabibullina@da-14.com
akhabibullina
_khabibullina
ZE QUALITYS?
“Any feature without a test doesn’t exist”
Steve Loughran HP Laboratories
AGENDA
 Unit Testing Concept
 Pros & Cons
 Basic Terms & Structure
 TDD &/vs. BDD
 Tools & Libraries
 Unit Testing Specifics
in JavaScript
 Best Practices
UNIT TESTING CONCEPT
Unit testing is a method by which individual
units of source code are tested to determine
if they are fit for use.
WHY UNIT TESTING?
Unit tests find problems early in the
development cycle (TDD & BDD)
Refactoring
Integration
Documentation
Better design
IS UNIT TESTING A GOOD INVESTMENT?
 slow down the development process
 share the same blind spots with the code
 doesn’t prove that they’re compatible with
one another or configured correctly
BASIC TERMS
In simple words, the goal of assertion is to
forcefully define if the test fails or passes.
STATEMENT PASSES FAILS
x = 1 assert(x > 0) assert(x < 0)
expect(4+5).to.equal(9);
ASSERTION
function initialize() {
// The initialization was successful.
return true;
}
Given the function initialize():
ASSERTION: EXAMPLE
ASSERTION: EXAMPLE
var isInitialized = initialize();
TDD assert.isTrue(isInitialized)
BDD expect(isInitialized).to.be.true
Check that function initialize() returns true
when called.
FIXTURE
A test fixture is a fixed state of the software
under test used as a baseline for running
tests.
In JavaScript for client side:
simulate AJAX responses;
loading known set of data such as html
objects.
FIXTURE: EXAMPLE
Require the piece of markup stored in
myfixturemarkup.html file before each test:
beforeEach(function() {
loadFixtures('myfixturemarkup.html');
});
STUB
Method stubs
are functions
with pre-
programmed
behavior.
STUB: EXAMPLE
Forcing a method to throw an error in order
to test error handling.
var fn = foo.stub().throws(Error);
expect(fn).to.throw(Error);
SPY
A test spy is a
function that
records
arguments,
return value, the
value of this and
exception thrown
(if any) for all its
calls.
SPY: EXAMPLE
Test that a function cursor.hide() has been
only called once, and only once.
sinon.spy(cursor, "hide");
TDD sinon.assert.calledOnce(cursor.hide)
BDD expect(cursor.hide.calledOnce).to.be.true
MOCK
Mocks are fake objects with pre-
programmed behavior (like stubs) and
pre-programmed expectations.
They are like both stubs and spies – in
one.
MOCK: EXAMPLE
Create an expectation that jQuery.each is
called once, and only once, and also
instructs the mock to behave as we pre-
define.
var mock = sinon.mock(jQuery);
MOCK: EXAMPLE
#1 – which method?
#2 – how many times it is called?
#3 – what are the arguments when the
method called?
#4 – what the method returns?
TEST DRIVEN DEVELOPMENT(TDD)
TDD is a software
development
process that…
I’ll tell you the rest 
WHAT ARE THESE BDD?
ALRIGHT, WHAT IS BDD YOU ASK?
Terminology:
TDD BDD
Test Example
Assertion Expectation
Unit Behavior
BASIC STRUCTURE
#1. Setup/BeforeEach/Before
#2. Prepare an input
#3. Call a method
#4. Check an output
#5. Tear down/AfterEach/After
#1. Setup / Before
before(function(done) {
// Create a basic document.
document = jsdom.jsdom();
window = document.parentWindow;
done();
});
BASIC STRUCTURE: EXPLAINED
Before / BeforeEach
before(function() { console.log(‘before test’); });
test(‘first test’, function() { console.log(‘first test’); });
test(‘second test’, function() { console.log(‘second test’);});
afterEach(function() { console.log(‘after each test’); });
Result
before test
first test
after each test
second test
after each test
BASIC STRUCTURE: EXPLAINED
BASIC STRUCTURE: EXPLAINED
it('should initialize cursor if zoom level >= minimum zoom
level.',
#2. Prepare an input and predicted result.
var minZoomLevel = 1;
var zoomLevel = minZoomLevel + 0.1;
var expectedCursor = {‘color’: ‘white’, ‘height’: … };
#3. Call a method.
var actualCursor = cursor.init(zoomLevel);
#4. Check an output.
expect(actualCursor).to.deep.equal(expectedCursor);
done();
});
function(done) {
BASIC STRUCTURE: EXPLAINED
it('should initialize cursor if zoom level >= minimum zoom
level.',
#2. Prepare an input and predicted result.
var minZoomLevel = 1;
var zoomLevel = minZoomLevel + 0.1;
var expectedCursor = {‘color’: ‘white’, ‘height’: … };
#3. Call a method.
var actualCursor = cursor.init(zoomLevel);
#4. Check an output.
expect(actualCursor).to.deep.equal(expectedCursor);
done();
});
function(done) {
BASIC STRUCTURE: EXPLAINED
it('should initialize cursor if zoom level >= minimum zoom
level.',
#2. Prepare an input and predicted result.
var minZoomLevel = 1;
var zoomLevel = minZoomLevel + 0.1;
var expectedCursor = {‘color’: ‘white’, ‘height’: … };
#3. Call a method.
var actualCursor = cursor.init(zoomLevel);
#4. Check an output.
expect(actualCursor).to.deep.equal(expectedCursor);
done();
});
function(done) {
BASIC STRUCTURE: EXPLAINED
it('should initialize cursor if zoom level >= minimum zoom
level.',
#2. Prepare an input and predicted result.
var minZoomLevel = 1;
var zoomLevel = minZoomLevel + 0.1;
var expectedCursor = {‘color’: ‘white’, ‘height’: … };
#3. Call a method.
var actualCursor = cursor.init(zoomLevel);
#4. Check an output.
expect(actualCursor).to.deep.equal(expectedCursor);
done();
});
function(done) {
#5. TearDown / After
after(function(done) {
// Remove global objects document.
document = null;
window = null;
done();
});
BASIC STRUCTURE: EXPLAINED
OUTPUT
<testsuite name="Macchiato Tests" tests="13"
failures="0" errors="0" skipped="0"
timestamp="Mon, 02 Dec 2013 11:08:09 GMT"
time="0.114">
<testcase classname = "cursor #init ()"
name = "should initialize cursor if
zoom level &gt; minimum zoom level."
time="0.004"/>
</testsuite>
OUTPUT: SUCCESS
<failure classname="cursor #init()"
name="should initialize cursor if zoom level
&gt; minimum zoom level." time="0"
message="Cannot read property 'show' of
undefined"><![CDATA[TypeError: Cannot read
property 'show' of undefined
// ..... Exception Stack Trace .....
</failure>
OUTPUT: FAILURE
TOOLS
TOOLS
> 40 frameworks & libraries
qUnit(TDD) light-weight TDD framework
Jasmine(BDD) flexible BDD framework
Mocha / Karma test runner for async code
+ Chai TDD / BDD assertion library
+ Sinon test spies, stubs & mocks
ENTIRE SPACE OF FRAMEWORKS…
HOW DO I UNIT TEST
Known Frameworks / Libraries?
What to test? What to use?
Angular, React, Flight Karma + Jasmine
Backbone qUnit
Ember Karma + qUnit (ember-app-kit)
ExtJs Jasmine, Siesta (UI)
TypeScript tsUnit
CoffeeScript qUnit
Dart Unittest, Hop and Drone.io
NodeJs expresso and vows, Nodeunit
TOOLS: WHAT WE USE
 Run UT: Mocha
 Run UT in parallel: Macchiato
 Assert/Expect: Chai
 W3C DOM in JavaScript: Jsdom
 Mock, spy, stub: Sinon
 Code coverage tool: None
 Routine automation: make/Grunt
TOOLS: WHAT WE USE
TOOLS: WHAT WE USE
Project unit tested like a dream ♥
UNIT TESTING SPECIFICS IN JAVASCRIPT
UI
Load fake data via “fixtures”
Jsdom(W3C JavaScript implementation)
UNIT TESTING SPECIFICS IN JAVASCRIPT
AJAX
Stub jQuery.ajax
Fake XMLHttpRequest
(XMLHTTP ActiveXObject)
Fake server
UNIT TESTING SPECIFICS IN JAVASCRIPT
3rd-party scripts
Stubbing jQuery plugin functions
(mock jQuery.fn)
UNIT TESTING SPECIFICS IN JAVASCRIPT
Dependency Injection
Mocking deps in RequireJs sucks hard!
Squire.js lib / testr.js
UNIT TESTING SPECIFICS IN JAVASCRIPT
NodeJs
Server-side specifics
rewire: node.js dependency injection
BEST PRACTISES
Fast
Isolated
Consistent
Responsibility
Self-descriptive
No exception Handling
Use assertions when needed
WRAPPING UP
 Each test verifies a small chunk of code
 Unit tests work best in isolation
 Mocks, stubs and spies help to isolate test
 Don’t test everything but write many tests
 > 40 tools are available to ease unit testing
experience, so CHOOSE YOUR OWN!
SHWEEET
ありがとう

More Related Content

What's hot (18)

PPTX
Typescript tips & tricks
Ori Calvo
 
KEY
Runtime
Jorge Ortiz
 
PDF
Adventures In JavaScript Testing
Thomas Fuchs
 
PDF
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
PDF
Jasmine BDD for Javascript
Luis Alfredo Porras Páez
 
PPTX
Why TypeScript?
FITC
 
PDF
From dot net_to_rails
pythonandchips
 
PDF
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
PDF
Google Dart
Eberhard Wolff
 
PDF
Dart Workshop
Dmitry Buzdin
 
PDF
Introduction to Dart
RameshNair6
 
PDF
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
PDF
BDD style Unit Testing
Wen-Tien Chang
 
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PDF
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
PPTX
Javascript best practices
Manav Gupta
 
PDF
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
Typescript tips & tricks
Ori Calvo
 
Runtime
Jorge Ortiz
 
Adventures In JavaScript Testing
Thomas Fuchs
 
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
Jasmine BDD for Javascript
Luis Alfredo Porras Páez
 
Why TypeScript?
FITC
 
From dot net_to_rails
pythonandchips
 
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Google Dart
Eberhard Wolff
 
Dart Workshop
Dmitry Buzdin
 
Introduction to Dart
RameshNair6
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
BDD style Unit Testing
Wen-Tien Chang
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
Javascript best practices
Manav Gupta
 
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 

Similar to Js fwdays unit tesing javascript(by Anna Khabibullina) (20)

PPTX
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
ODP
Grails unit testing
pleeps
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
Javascript tdd byandreapaciolla
Andrea Paciolla
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PDF
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
PPTX
Security testing of YUI powered applications
dimisec
 
PPTX
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
PPTX
Understanding JavaScript Testing
Kissy Team
 
PPTX
Java script unit testing
Mats Bryntse
 
KEY
Javascript unit testing, yes we can e big
Andy Peterson
 
PDF
CBDW2014 - MockBox, get ready to mock your socks off!
Ortus Solutions, Corp
 
PPTX
TDD & BDD
Arvind Vyas
 
PPTX
JavaScript (without DOM)
Piyush Katariya
 
KEY
JavaScript Growing Up
David Padbury
 
PPT
Pragmatic Parallels: Java and JavaScript
davejohnson
 
PDF
Quick Tour to Front-End Unit Testing Using Jasmine
Gil Fink
 
PDF
Front end unit testing using jasmine
Gil Fink
 
PDF
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
PPTX
Building unit tests correctly
Dror Helper
 
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
Grails unit testing
pleeps
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
Javascript tdd byandreapaciolla
Andrea Paciolla
 
Unit testing JavaScript using Mocha and Node
Josh Mock
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Security testing of YUI powered applications
dimisec
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
Understanding JavaScript Testing
Kissy Team
 
Java script unit testing
Mats Bryntse
 
Javascript unit testing, yes we can e big
Andy Peterson
 
CBDW2014 - MockBox, get ready to mock your socks off!
Ortus Solutions, Corp
 
TDD & BDD
Arvind Vyas
 
JavaScript (without DOM)
Piyush Katariya
 
JavaScript Growing Up
David Padbury
 
Pragmatic Parallels: Java and JavaScript
davejohnson
 
Quick Tour to Front-End Unit Testing Using Jasmine
Gil Fink
 
Front end unit testing using jasmine
Gil Fink
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
Building unit tests correctly
Dror Helper
 
Ad

More from Anna Khabibullina (6)

PPTX
Key Challenges of Smart Home
Anna Khabibullina
 
PPTX
Influence without authority annakh@ slideshare
Anna Khabibullina
 
PPTX
Don’t forget to add doctype
Anna Khabibullina
 
PPTX
Web Accessibility: You can and You should
Anna Khabibullina
 
PPTX
SVG Accessibility
Anna Khabibullina
 
PDF
Typescript: A Story Of A Project
Anna Khabibullina
 
Key Challenges of Smart Home
Anna Khabibullina
 
Influence without authority annakh@ slideshare
Anna Khabibullina
 
Don’t forget to add doctype
Anna Khabibullina
 
Web Accessibility: You can and You should
Anna Khabibullina
 
SVG Accessibility
Anna Khabibullina
 
Typescript: A Story Of A Project
Anna Khabibullina
 
Ad

Recently uploaded (20)

PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
4 Tier Teamcenter Installation part1.pdf
VnyKumar1
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PDF
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
PDF
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PPTX
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
PPTX
cybersecurityandthe importance of the that
JayachanduHNJc
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
PPTX
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
4 Tier Teamcenter Installation part1.pdf
VnyKumar1
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
Inventory management chapter in automation and robotics.
atisht0104
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
cybersecurityandthe importance of the that
JayachanduHNJc
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 

Js fwdays unit tesing javascript(by Anna Khabibullina)

  • 1. В поисках качества JavaScript: модульное тестирование Анна Хабибуллина DA-14 / da-14.com [email protected] akhabibullina _khabibullina
  • 2. ZE QUALITYS? “Any feature without a test doesn’t exist” Steve Loughran HP Laboratories
  • 3. AGENDA  Unit Testing Concept  Pros & Cons  Basic Terms & Structure  TDD &/vs. BDD  Tools & Libraries  Unit Testing Specifics in JavaScript  Best Practices
  • 4. UNIT TESTING CONCEPT Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.
  • 5. WHY UNIT TESTING? Unit tests find problems early in the development cycle (TDD & BDD) Refactoring Integration Documentation Better design
  • 6. IS UNIT TESTING A GOOD INVESTMENT?  slow down the development process  share the same blind spots with the code  doesn’t prove that they’re compatible with one another or configured correctly
  • 8. In simple words, the goal of assertion is to forcefully define if the test fails or passes. STATEMENT PASSES FAILS x = 1 assert(x > 0) assert(x < 0) expect(4+5).to.equal(9); ASSERTION
  • 9. function initialize() { // The initialization was successful. return true; } Given the function initialize(): ASSERTION: EXAMPLE
  • 10. ASSERTION: EXAMPLE var isInitialized = initialize(); TDD assert.isTrue(isInitialized) BDD expect(isInitialized).to.be.true Check that function initialize() returns true when called.
  • 11. FIXTURE A test fixture is a fixed state of the software under test used as a baseline for running tests. In JavaScript for client side: simulate AJAX responses; loading known set of data such as html objects.
  • 12. FIXTURE: EXAMPLE Require the piece of markup stored in myfixturemarkup.html file before each test: beforeEach(function() { loadFixtures('myfixturemarkup.html'); });
  • 13. STUB Method stubs are functions with pre- programmed behavior.
  • 14. STUB: EXAMPLE Forcing a method to throw an error in order to test error handling. var fn = foo.stub().throws(Error); expect(fn).to.throw(Error);
  • 15. SPY A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls.
  • 16. SPY: EXAMPLE Test that a function cursor.hide() has been only called once, and only once. sinon.spy(cursor, "hide"); TDD sinon.assert.calledOnce(cursor.hide) BDD expect(cursor.hide.calledOnce).to.be.true
  • 17. MOCK Mocks are fake objects with pre- programmed behavior (like stubs) and pre-programmed expectations. They are like both stubs and spies – in one.
  • 18. MOCK: EXAMPLE Create an expectation that jQuery.each is called once, and only once, and also instructs the mock to behave as we pre- define. var mock = sinon.mock(jQuery);
  • 19. MOCK: EXAMPLE #1 – which method? #2 – how many times it is called? #3 – what are the arguments when the method called? #4 – what the method returns?
  • 20. TEST DRIVEN DEVELOPMENT(TDD) TDD is a software development process that… I’ll tell you the rest 
  • 22. ALRIGHT, WHAT IS BDD YOU ASK? Terminology: TDD BDD Test Example Assertion Expectation Unit Behavior
  • 23. BASIC STRUCTURE #1. Setup/BeforeEach/Before #2. Prepare an input #3. Call a method #4. Check an output #5. Tear down/AfterEach/After
  • 24. #1. Setup / Before before(function(done) { // Create a basic document. document = jsdom.jsdom(); window = document.parentWindow; done(); }); BASIC STRUCTURE: EXPLAINED
  • 25. Before / BeforeEach before(function() { console.log(‘before test’); }); test(‘first test’, function() { console.log(‘first test’); }); test(‘second test’, function() { console.log(‘second test’);}); afterEach(function() { console.log(‘after each test’); }); Result before test first test after each test second test after each test BASIC STRUCTURE: EXPLAINED
  • 26. BASIC STRUCTURE: EXPLAINED it('should initialize cursor if zoom level >= minimum zoom level.', #2. Prepare an input and predicted result. var minZoomLevel = 1; var zoomLevel = minZoomLevel + 0.1; var expectedCursor = {‘color’: ‘white’, ‘height’: … }; #3. Call a method. var actualCursor = cursor.init(zoomLevel); #4. Check an output. expect(actualCursor).to.deep.equal(expectedCursor); done(); }); function(done) {
  • 27. BASIC STRUCTURE: EXPLAINED it('should initialize cursor if zoom level >= minimum zoom level.', #2. Prepare an input and predicted result. var minZoomLevel = 1; var zoomLevel = minZoomLevel + 0.1; var expectedCursor = {‘color’: ‘white’, ‘height’: … }; #3. Call a method. var actualCursor = cursor.init(zoomLevel); #4. Check an output. expect(actualCursor).to.deep.equal(expectedCursor); done(); }); function(done) {
  • 28. BASIC STRUCTURE: EXPLAINED it('should initialize cursor if zoom level >= minimum zoom level.', #2. Prepare an input and predicted result. var minZoomLevel = 1; var zoomLevel = minZoomLevel + 0.1; var expectedCursor = {‘color’: ‘white’, ‘height’: … }; #3. Call a method. var actualCursor = cursor.init(zoomLevel); #4. Check an output. expect(actualCursor).to.deep.equal(expectedCursor); done(); }); function(done) {
  • 29. BASIC STRUCTURE: EXPLAINED it('should initialize cursor if zoom level >= minimum zoom level.', #2. Prepare an input and predicted result. var minZoomLevel = 1; var zoomLevel = minZoomLevel + 0.1; var expectedCursor = {‘color’: ‘white’, ‘height’: … }; #3. Call a method. var actualCursor = cursor.init(zoomLevel); #4. Check an output. expect(actualCursor).to.deep.equal(expectedCursor); done(); }); function(done) {
  • 30. #5. TearDown / After after(function(done) { // Remove global objects document. document = null; window = null; done(); }); BASIC STRUCTURE: EXPLAINED
  • 32. <testsuite name="Macchiato Tests" tests="13" failures="0" errors="0" skipped="0" timestamp="Mon, 02 Dec 2013 11:08:09 GMT" time="0.114"> <testcase classname = "cursor #init ()" name = "should initialize cursor if zoom level &gt; minimum zoom level." time="0.004"/> </testsuite> OUTPUT: SUCCESS
  • 33. <failure classname="cursor #init()" name="should initialize cursor if zoom level &gt; minimum zoom level." time="0" message="Cannot read property 'show' of undefined"><![CDATA[TypeError: Cannot read property 'show' of undefined // ..... Exception Stack Trace ..... </failure> OUTPUT: FAILURE
  • 34. TOOLS
  • 35. TOOLS > 40 frameworks & libraries qUnit(TDD) light-weight TDD framework Jasmine(BDD) flexible BDD framework Mocha / Karma test runner for async code + Chai TDD / BDD assertion library + Sinon test spies, stubs & mocks
  • 36. ENTIRE SPACE OF FRAMEWORKS…
  • 37. HOW DO I UNIT TEST Known Frameworks / Libraries? What to test? What to use? Angular, React, Flight Karma + Jasmine Backbone qUnit Ember Karma + qUnit (ember-app-kit) ExtJs Jasmine, Siesta (UI) TypeScript tsUnit CoffeeScript qUnit Dart Unittest, Hop and Drone.io NodeJs expresso and vows, Nodeunit
  • 38. TOOLS: WHAT WE USE  Run UT: Mocha  Run UT in parallel: Macchiato  Assert/Expect: Chai  W3C DOM in JavaScript: Jsdom  Mock, spy, stub: Sinon  Code coverage tool: None  Routine automation: make/Grunt
  • 40. TOOLS: WHAT WE USE Project unit tested like a dream ♥
  • 41. UNIT TESTING SPECIFICS IN JAVASCRIPT UI Load fake data via “fixtures” Jsdom(W3C JavaScript implementation)
  • 42. UNIT TESTING SPECIFICS IN JAVASCRIPT AJAX Stub jQuery.ajax Fake XMLHttpRequest (XMLHTTP ActiveXObject) Fake server
  • 43. UNIT TESTING SPECIFICS IN JAVASCRIPT 3rd-party scripts Stubbing jQuery plugin functions (mock jQuery.fn)
  • 44. UNIT TESTING SPECIFICS IN JAVASCRIPT Dependency Injection Mocking deps in RequireJs sucks hard! Squire.js lib / testr.js
  • 45. UNIT TESTING SPECIFICS IN JAVASCRIPT NodeJs Server-side specifics rewire: node.js dependency injection
  • 47. WRAPPING UP  Each test verifies a small chunk of code  Unit tests work best in isolation  Mocks, stubs and spies help to isolate test  Don’t test everything but write many tests  > 40 tools are available to ease unit testing experience, so CHOOSE YOUR OWN!