SlideShare a Scribd company logo
1 of 49
В поисках качества
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

Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricksOri Calvo
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript TestingThomas Fuchs
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit TestingWen-Tien Chang
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma Christopher Bartling
 
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 MizrahiRan Mizrahi
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 

What's hot (18)

Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
 
Runtime
RuntimeRuntime
Runtime
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript Testing
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Google Dart
Google DartGoogle Dart
Google Dart
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
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
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 

Viewers also liked

อ.ทรงพล เจริญคำ กลุ่ม 6ภาค2
อ.ทรงพล เจริญคำ  กลุ่ม  6ภาค2อ.ทรงพล เจริญคำ  กลุ่ม  6ภาค2
อ.ทรงพล เจริญคำ กลุ่ม 6ภาค2monrudeesinchai
 
28.03.2014 odf crimea_occupation_eng
28.03.2014 odf crimea_occupation_eng28.03.2014 odf crimea_occupation_eng
28.03.2014 odf crimea_occupation_engodfoundation
 
Tech talk Angular 2
Tech talk Angular 2Tech talk Angular 2
Tech talk Angular 2DA-14
 
Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.
Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.
Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.odfoundation
 
TechTalk#2: Принципы управления временем
TechTalk#2: Принципы управления временемTechTalk#2: Принципы управления временем
TechTalk#2: Принципы управления временемDA-14
 
Kunstinwerking @ skills21kunst
Kunstinwerking @ skills21kunstKunstinwerking @ skills21kunst
Kunstinwerking @ skills21kunstKirsten_lkca
 
25 08-2014-odf-report-case-of-nadezhda-savchenko-eng 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-eng 125 08-2014-odf-report-case-of-nadezhda-savchenko-eng 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-eng 1odfoundation
 
Pascal Gielen @ skills21kunst
Pascal Gielen @ skills21kunstPascal Gielen @ skills21kunst
Pascal Gielen @ skills21kunstKirsten_lkca
 
Data-Driven Marketing Roadshow DataSift - March 27, 2014
Data-Driven Marketing Roadshow DataSift - March 27, 2014Data-Driven Marketing Roadshow DataSift - March 27, 2014
Data-Driven Marketing Roadshow DataSift - March 27, 2014DDM Alliance
 
Krymskaya voyna 1853-1856
Krymskaya voyna 1853-1856Krymskaya voyna 1853-1856
Krymskaya voyna 1853-1856alkinanadia
 
03.07.2014 odf oleg_sentsov_case_ua
03.07.2014 odf oleg_sentsov_case_ua03.07.2014 odf oleg_sentsov_case_ua
03.07.2014 odf oleg_sentsov_case_uaodfoundation
 
Basilica cistern, Istanbul
Basilica cistern, IstanbulBasilica cistern, Istanbul
Basilica cistern, Istanbulmhr56
 
К. Скобеев: "Точки роста проекта без ссылок"
К. Скобеев: "Точки роста проекта без ссылок"К. Скобеев: "Точки роста проекта без ссылок"
К. Скобеев: "Точки роста проекта без ссылок"Скобеев и Партнеры
 
High quality medical monitoring devices at low price
High quality medical monitoring devices at low priceHigh quality medical monitoring devices at low price
High quality medical monitoring devices at low priceMadison102
 
Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009odfoundation
 
25 08-2014-odf-report-case-of-nadezhda-savchenko-ru 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-ru 125 08-2014-odf-report-case-of-nadezhda-savchenko-ru 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-ru 1odfoundation
 
Windows group policy_editor
Windows group policy_editorWindows group policy_editor
Windows group policy_editorDonatas Bukelis
 
Raport euromajdan pl
Raport euromajdan plRaport euromajdan pl
Raport euromajdan plodfoundation
 

Viewers also liked (20)

อ.ทรงพล เจริญคำ กลุ่ม 6ภาค2
อ.ทรงพล เจริญคำ  กลุ่ม  6ภาค2อ.ทรงพล เจริญคำ  กลุ่ม  6ภาค2
อ.ทรงพล เจริญคำ กลุ่ม 6ภาค2
 
28.03.2014 odf crimea_occupation_eng
28.03.2014 odf crimea_occupation_eng28.03.2014 odf crimea_occupation_eng
28.03.2014 odf crimea_occupation_eng
 
Tech talk Angular 2
Tech talk Angular 2Tech talk Angular 2
Tech talk Angular 2
 
Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.
Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.
Yd1305161 sprawozdanie finansowe_2010_z_us-eng done.
 
TechTalk#2: Принципы управления временем
TechTalk#2: Принципы управления временемTechTalk#2: Принципы управления временем
TechTalk#2: Принципы управления временем
 
Kunstinwerking @ skills21kunst
Kunstinwerking @ skills21kunstKunstinwerking @ skills21kunst
Kunstinwerking @ skills21kunst
 
25 08-2014-odf-report-case-of-nadezhda-savchenko-eng 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-eng 125 08-2014-odf-report-case-of-nadezhda-savchenko-eng 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-eng 1
 
Pascal Gielen @ skills21kunst
Pascal Gielen @ skills21kunstPascal Gielen @ skills21kunst
Pascal Gielen @ skills21kunst
 
Data-Driven Marketing Roadshow DataSift - March 27, 2014
Data-Driven Marketing Roadshow DataSift - March 27, 2014Data-Driven Marketing Roadshow DataSift - March 27, 2014
Data-Driven Marketing Roadshow DataSift - March 27, 2014
 
Krymskaya voyna 1853-1856
Krymskaya voyna 1853-1856Krymskaya voyna 1853-1856
Krymskaya voyna 1853-1856
 
03.07.2014 odf oleg_sentsov_case_ua
03.07.2014 odf oleg_sentsov_case_ua03.07.2014 odf oleg_sentsov_case_ua
03.07.2014 odf oleg_sentsov_case_ua
 
Basilica cistern, Istanbul
Basilica cistern, IstanbulBasilica cistern, Istanbul
Basilica cistern, Istanbul
 
К. Скобеев: "Точки роста проекта без ссылок"
К. Скобеев: "Точки роста проекта без ссылок"К. Скобеев: "Точки роста проекта без ссылок"
К. Скобеев: "Точки роста проекта без ссылок"
 
Aaah 2
Aaah 2Aaah 2
Aaah 2
 
Firewall zone alarm
Firewall zone alarmFirewall zone alarm
Firewall zone alarm
 
High quality medical monitoring devices at low price
High quality medical monitoring devices at low priceHigh quality medical monitoring devices at low price
High quality medical monitoring devices at low price
 
Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009
 
25 08-2014-odf-report-case-of-nadezhda-savchenko-ru 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-ru 125 08-2014-odf-report-case-of-nadezhda-savchenko-ru 1
25 08-2014-odf-report-case-of-nadezhda-savchenko-ru 1
 
Windows group policy_editor
Windows group policy_editorWindows group policy_editor
Windows group policy_editor
 
Raport euromajdan pl
Raport euromajdan plRaport euromajdan pl
Raport euromajdan pl
 

Similar to JS Frameworks Day April,26 of 2014

In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeJosh Mock
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Security testing of YUI powered applications
Security testing of YUI powered applicationsSecurity testing of YUI powered applications
Security testing of YUI powered applicationsdimisec
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF SummitOrtus Solutions, Corp
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptdavejohnson
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineGil Fink
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmineGil Fink
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 

Similar to JS Frameworks Day April,26 of 2014 (20)

In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Security testing of YUI powered applications
Security testing of YUI powered applicationsSecurity testing of YUI powered applications
Security testing of YUI powered applications
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmine
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 

More from DA-14

Express js clean-controller
Express js clean-controllerExpress js clean-controller
Express js clean-controllerDA-14
 
Express js api-versioning
Express js api-versioningExpress js api-versioning
Express js api-versioningDA-14
 
AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood DA-14
 
Firebase not really_yohoho
Firebase not really_yohohoFirebase not really_yohoho
Firebase not really_yohohoDA-14
 
Techtalk#8: Design patterns in real life
Techtalk#8: Design patterns in real lifeTechtalk#8: Design patterns in real life
Techtalk#8: Design patterns in real lifeDA-14
 
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"DA-14
 
Mysql, MongoDb feat. Doctrine2
Mysql, MongoDb feat. Doctrine2Mysql, MongoDb feat. Doctrine2
Mysql, MongoDb feat. Doctrine2DA-14
 
Web Components: back to the future
Web Components: back to the futureWeb Components: back to the future
Web Components: back to the futureDA-14
 
Techtalk#6: NodeJs: pitfalls (based on game project)
Techtalk#6: NodeJs: pitfalls (based on game project)Techtalk#6: NodeJs: pitfalls (based on game project)
Techtalk#6: NodeJs: pitfalls (based on game project)DA-14
 
TechTalk#3: REST
TechTalk#3: RESTTechTalk#3: REST
TechTalk#3: RESTDA-14
 

More from DA-14 (10)

Express js clean-controller
Express js clean-controllerExpress js clean-controller
Express js clean-controller
 
Express js api-versioning
Express js api-versioningExpress js api-versioning
Express js api-versioning
 
AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood
 
Firebase not really_yohoho
Firebase not really_yohohoFirebase not really_yohoho
Firebase not really_yohoho
 
Techtalk#8: Design patterns in real life
Techtalk#8: Design patterns in real lifeTechtalk#8: Design patterns in real life
Techtalk#8: Design patterns in real life
 
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
 
Mysql, MongoDb feat. Doctrine2
Mysql, MongoDb feat. Doctrine2Mysql, MongoDb feat. Doctrine2
Mysql, MongoDb feat. Doctrine2
 
Web Components: back to the future
Web Components: back to the futureWeb Components: back to the future
Web Components: back to the future
 
Techtalk#6: NodeJs: pitfalls (based on game project)
Techtalk#6: NodeJs: pitfalls (based on game project)Techtalk#6: NodeJs: pitfalls (based on game project)
Techtalk#6: NodeJs: pitfalls (based on game project)
 
TechTalk#3: REST
TechTalk#3: RESTTechTalk#3: REST
TechTalk#3: REST
 

Recently uploaded

Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 

Recently uploaded (20)

Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 

JS Frameworks Day April,26 of 2014

  • 1. В поисках качества JavaScript: модульное тестирование Анна Хабибуллина DA-14 / da-14.com anna.khabibullina@da-14.com 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!