SlideShare a Scribd company logo
Introduction to 
{ JavaScript Testing } 
Ran Mizrahi (@ranm8) 
Founder and CEO @ CoCycles
About { Me } 
• Founder and CEO of CoCycles. 
• Former Open Source Dpt. Leader of CodeOasis. 
• Architected and lead the development of the Wix App Market. 
• Full-stack and hands-on software engineer.
Why Do Software Projects { Fail } ? 
Production Maintenance 
• Deliver late or over budget. 
• Deliver the wrong thing. 
• Unstable in production. 
• Expensive maintenance. 
• Long adjustment to market 
needs. 
• Long development cycles.
Why Do Software Projects { Fail } ?
Untestable { Code }… 
function createUser(properties) { 
var user = { 
firstName: properties.firstName, 
lastName: properties.lastName, 
username: properties.username, 
mail: properties.mail 
}; 
var fullName = User.firstName + ' ' + User.lastName; 
// Make sure user is valid 
if (!user.firstName || !user.lastName) { 
throw new Error('First or last name are not valid!'); 
} else if(typeof user.mail === 'string' && user.mail.match(new RegExp(/^w+@[a-zA-Z_]+?.[a-zA-Z]{ 
2,3}$/)) === null) { 
throw new Error('Mail is not valid'); 
} else if (!user.username) { 
throw new Error('Username is not valid'); 
} 
$.post('/user', { 
fullName: fullName, 
userName: user.username, 
mail: user.mail 
}, function(data) { 
var message; 
if (data.code === 200) { 
message = 'User saved successfully!'; 
} else { 
message = 'Operation was failed!'; 
} 
$('#some-div').animate({ 
'margin-left': $(window).width() 
}, 1000, function() { 
$(this).html(message); 
}); 
}); 
}
The problems with untestable code: 
• Tightly coupled. 
• No separation of concerns. 
• Not readable. 
• Not predictable. 
> 
• Global states. 
• Long methods. 
• Large classes/objects. 
• Hard to maintain. 
• High learning curve. 
• Stability issues. 
• You can never expect 
problems before they 
occur 
Why Test Your { Code } ?
{ Test-Driven Development } To The Rescue 
Methodology for using automated unit 
tests to drive software design, quality 
and stability.
{ Test-Driven Development } To The Rescue 
How it’s done : 
• First the developer writes 
a failing test case that 
defines a desired 
functionality to the 
software. 
• Makes the code pass 
those tests. 
• Refactor the code to meet 
standards.
Seems Great But How Much Longer Does { TDD Take } ? 
My experience: 
• Initial progress will be slower. 
• Greater consistency. 
• Long tern cost is drastically 
lower 
• After getting used to it, you 
can write TDD faster (-: 
Studies: 
• Takes 15-30% longer. 
• 45-80% less bugs. 
• Fixing bugs later on is 
dramatically faster.
The { Three Rules } of TDD 
Rule #1 
Your code should always fail before you implement the code 
Rule #2 
Implement the simplest code possible to pass your tests. 
Rule #3 
Refactor, refactor and refractor - There is no shame in refactoring.
{ BDD } Behaviour-Driven Development 
What exactly are we testing?! 
Test-Driven Development
{ BDD } Behaviour-Driven Development 
• Originally started in 2003 by Dan North, author of JBehave, the 
first BDD tool. 
• Based on the TDD methodology. 
• Aims to provide tools for both developers and business (e.g. 
product manager, etc.) to share development process together. 
• The steps of BDD : 
• Developers and business personas write specification together. 
• Developer writes tests based on specs and make them fail. 
• Write code to pass those tests. 
• Refactor, refactor, refactor...
{ BDD } Behaviour-Driven Development 
Feature: ls 
In order to see the directory structure 
As a UNIX user 
I need to be able to list the current directory's contents 
Scenario: List 2 files in a directory 
Given I am in a directory "test" 
And I have a file named "foo" 
And I have a file named "bar" 
When I run "ls" 
Then I should get: 
""" 
bar 
foo 
"""
Main { Test Types } 
• Unit Testing 
• Integration Testing 
• Functional Testing
{ Challenges } Testing JavaScript 
• Async tests: 
• Testing async methods can be tricky. 
• Define tests timeout. 
• Indicate when test is completed in callback. 
• Assert on callback. 
• DOM: 
• Testing DOM is a difficult task. 
• The key is to separate your controller and model logic from 
DOM and test those only. 
• Testing DOM is done using functional testing (e.g. WebDriver, 
etc.)
TDD/BDD Using { Mocha and ChaiJS } 
Mocha 
Mocha is a feature-rich JavaScript test frameworks running on 
node and the browser, making asynchronies tests easy. 
Main features: 
• Supports both TDD and BDD styles. 
• Simple async testing. 
• Both browser and node support. 
• Proper exit status for CI support. 
• node.js debugger support. 
• Highly flexible, choose and join the pieces yourself (spy library, 
assertion library, etc.).
TDD/BDD Using { Mocha and ChaiJS } 
ChaiJS 
Chai is a BDD / TDD assertion library for node and the browser 
that can be paired with any JavaScript testing framework. 
Main features: 
• BDD/TDD style. 
• Compatible with all test frameworks. 
• Both node.js and browser compatible. 
• Standalone assertion library. 
• Extendable
TDD/BDD Using { Mocha and ChaiJS } 
Installing Mocha and Chai 
Install mocha globally using npm: 
$ npm install mocha -g 
Install Chai (Locally): 
$ npm install chai
TDD/BDD Using { Mocha and ChaiJS } 
“Normal” test: 
var expect = require(‘chai').expect; 
describe('Array', function() { 
describe('#indexOf()', function() { 
it('expect -1 when the value is not present', function() { 
var array = [1, 2, 3]; 
expect(array.indexOf(4)).to.be(-1); 
}); 
}); 
}); 
Run it.. 
$ mocha --reporter spec 
Array 
#indexOf() 
✓ Expect -1 when the value is not present 
1 test complete (5 ms)
TDD/BDD Using { Mocha and ChaiJS } 
Async test: 
var expect = require(‘chai').expect; 
function asyncCall(val ,callback) { 
var prefix = ' - '; 
setTimeout(function() { 
var newString = val + prefix + 'OK'; 
callback(newString); 
}, 500); 
} 
describe('asyncCall', function() { 
it('Add suffix that prefixed with - to the given string', function(done) { 
var testVal = 'Foo'; 
asyncCall(testVal, function(response) { 
expect(response).to.contain(testVal + ' - OK'); 
done(); 
}); 
}); 
}); 
Let’s run it...
Back To { Our Code }
First, Let’s { Write The Tests } 
function createUser(properties) { 
var user = { 
firstName: properties.firstName, 
lastName: properties.lastName, 
username: properties.username, 
mail: properties.mail 
}; 
var fullName = User.firstName + ' ' + User.lastName; 
// Make sure user is valid 
if (!user.firstName || !user.lastName) { 
throw new Error('First or last name are not valid!'); 
} else if(typeof user.mail === 'string' && user.mail.match(new RegExp(/^w+@[a-zA-Z_]+?.[a-zA-Z]{ 
2,3}$/)) === null) { 
throw new Error('Mail is not valid'); 
} else if (!user.username) { 
throw new Error('Username is not valid'); 
} 
$.post('/user', { 
fullName: fullName, 
userName: user.username, 
mail: user.mail 
}, function(data) { 
var message; 
if (data.code === 200) { 
message = 'User saved successfully!'; 
} else { 
message = 'Operation was failed!'; 
} 
$('#some-div').animate({ 
'margin-left': $(window).width() 
}, 1000, function() { 
$(this).html(message); 
}); 
}); 
}
First, Let’s { Write The Tests } 
What to test in our case: 
• Full name concatenation. 
• API call data. 
• Request callback. 
What not to test : 
• DOM manipulations - Functional testing (e.g. WebDriver). 
• API requests - Integration testing.
First, Let’s { Write The Unit Tests } 
describe('#saveUser()', function() { 
it('should call http service with method POST, path /user, and the user object', function() { 
}); 
it('should compose the full name in to the user object', function() { 
}); 
it('should only return the payload from the response object', function() { 
}); 
}); 
});
The { Implementation } 
function userService($http, baseUrl) { 
baseUrl = baseUrl || 'http://google.com/api'; 
function composeFullName(firstName, lastName) { 
return firstName + ' ' + lastName; 
} 
function returnPayload(response) { 
return response.payload; 
} 
function execute(path, body, method) { 
return $http({ 
url: baseUrl + path, 
method: method || 'GET', 
data: body 
}); 
} 
return { 
saveUser: function(user) { 
user.fullName = composeFullName(user.firstName, user.lastName); 
return execute('/user', user, 'POST').then(returnPayload); 
} 
}; 
}
Implement { Our Unit Tests } 
describe('user service', function() { 
var userService, 
httpMock, 
thenFunc; 
function createHttpMock() { 
thenFunc = sinon.stub(); 
httpMock = sinon.stub().returns({ then: thenFunc }); 
} 
beforeEach(function() { 
createHttpMock(); 
userService = UserService(httpMock); 
}); 
function getUser() { 
return { firstName: 'Ran', lastName: 'Mizrahi' }; 
}
Implement { Our Unit Tests } 
describe('#saveUser()', function() { 
var user; 
beforeEach(function() { 
user = getUser(); 
userService.saveUser(user); 
}); 
it('should call http service with method POST, path /user, and the user object', function() { 
expect(httpMock).to.have.been.calledWith({ 
url: 'http://google.com/api/user', 
method: 'POST', 
data: user 
}); 
}); 
it('should compose the full name in to the user object', function() { 
expect(user.fullName).to.equal('Ran Mizrahi'); 
}); 
it('should only return the payload from the response object', function() { 
var returnPayload = thenFunc.args[0][0]; 
expect(returnPayload({ payload: 'Hello!!!' })).to.equal('Hello!!!'); 
}); 
}); 
});
Run Those { Tests Again }
Running The { Tests } 
mocha tests can run in different environments and formats: 
• Browser - using mocha.js (see example) 
• For CI automation use JSTestDriver. 
• CLI - as demonstrated before using the “mocha” command. 
• CI (e.g. xunit) - $ mocha test/asyncTest.js --reporter xunit. 
• Many other formats (JSON, HTML, list, Spec, etc.)
Benefits of { Testing The Code } 
• Short feedback/testing cycle. 
• High code coverage of tests that can be at run any time to 
provide feedback that the software is functioning. 
• Provides detailed spec/docs of the application. 
• Less time spent on debugging and refactoring. 
• Know what breaks early on. 
• Enforces code quality and simplicity. 
• Helps separating units to responsibilities.
Thank you! 
Questions?

More Related Content

What's hot (20)

JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
Yakov Fain
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
Christian Heilmann
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
Unit and functional testing with Siesta
Unit and functional testing with SiestaUnit and functional testing with Siesta
Unit and functional testing with Siesta
Grgur Grisogono
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
Addy Osmani
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
Peter Drinnan
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
Oren Farhi
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
Jie-Wei Wu
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)
Deutsche Post
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
Frederic CABASSUT
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
Juho Vepsäläinen
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
Fabien Potencier
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
Yakov Fain
 
Night Watch with QA
Night Watch with QANight Watch with QA
Night Watch with QA
Carsten Sandtner
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
Mats Bryntse
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
Ran Mizrahi
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
Yakov Fain
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
Unit and functional testing with Siesta
Unit and functional testing with SiestaUnit and functional testing with Siesta
Unit and functional testing with Siesta
Grgur Grisogono
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
Addy Osmani
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
Peter Drinnan
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
Oren Farhi
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
Jie-Wei Wu
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)
Deutsche Post
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
Frederic CABASSUT
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
Juho Vepsäläinen
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
Fabien Potencier
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
Yakov Fain
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
Mats Bryntse
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
Ran Mizrahi
 

Viewers also liked (20)

Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application Framework
Ran Mizrahi
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
Ran Mizrahi
 
Bitcoin for humans
Bitcoin for humansBitcoin for humans
Bitcoin for humans
Itai Damti
 
Product development for startups
Product development for startupsProduct development for startups
Product development for startups
Itai Damti
 
Final Presentation
Final PresentationFinal Presentation
Final Presentation
guest6e724f
 
Jugaaad: Innovation book
Jugaaad: Innovation bookJugaaad: Innovation book
Jugaaad: Innovation book
Suhag Mistry
 
Studying at UNH: Education and Research Opportunities
Studying at UNH: Education and Research OpportunitiesStudying at UNH: Education and Research Opportunities
Studying at UNH: Education and Research Opportunities
Andrew Kun
 
Founders Fund Manifesto
Founders Fund ManifestoFounders Fund Manifesto
Founders Fund Manifesto
Razin Mustafiz
 
Cheeky Carbon Presentation
Cheeky Carbon PresentationCheeky Carbon Presentation
Cheeky Carbon Presentation
pauljl
 
Wemagazine
WemagazineWemagazine
Wemagazine
Kathlyn05
 
Publish2 Tour
Publish2 TourPublish2 Tour
Publish2 Tour
scottkarp
 
Sticky Information - Von Hippel
Sticky Information - Von HippelSticky Information - Von Hippel
Sticky Information - Von Hippel
Jonas Rolo
 
Don't make my eyes bleed - Neil Davidson
Don't make my eyes bleed - Neil DavidsonDon't make my eyes bleed - Neil Davidson
Don't make my eyes bleed - Neil Davidson
Razin Mustafiz
 
Jornada de motivacion y busqueda de opciones
Jornada de motivacion y busqueda de opcionesJornada de motivacion y busqueda de opciones
Jornada de motivacion y busqueda de opciones
Luis Montalvan
 
Ad

Similar to Intro To JavaScript Unit Testing - Ran Mizrahi (20)

3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
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
Ortus Solutions, Corp
 
How do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and ClientHow do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and Client
ColdFusionConference
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientHow do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
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
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & Chai
Joerg Henning
 
How to write Testable Javascript
How to write Testable JavascriptHow to write Testable Javascript
How to write Testable Javascript
ColdFusionConference
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
Understanding TDD - theory, practice, techniques and tips.
Understanding TDD - theory, practice, techniques and tips.Understanding TDD - theory, practice, techniques and tips.
Understanding TDD - theory, practice, techniques and tips.
Malinda Kapuruge
 
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
 
Introduction to bdd
Introduction to bddIntroduction to bdd
Introduction to bdd
antannatna
 
ES3-2020-06 Test Driven Development (TDD)
ES3-2020-06 Test Driven Development (TDD)ES3-2020-06 Test Driven Development (TDD)
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
Test Driven Development - a Practitioner’s Perspective
Test Driven Development - a Practitioner’s PerspectiveTest Driven Development - a Practitioner’s Perspective
Test Driven Development - a Practitioner’s Perspective
Malinda Kapuruge
 
How do I write Testable Javascript
How do I write Testable JavascriptHow do I write Testable Javascript
How do I write Testable Javascript
ColdFusionConference
 
How do I write testable javascript?
How do I write testable javascript?How do I write testable javascript?
How do I write testable javascript?
devObjective
 
How do I write Testable Javascript?
How do I write Testable Javascript?How do I write Testable Javascript?
How do I write Testable Javascript?
Gavin Pickin
 
JavaScript development methodology
JavaScript development methodologyJavaScript development methodology
JavaScript development methodology
Aleksander Fabijan
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
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
Ortus Solutions, Corp
 
How do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and ClientHow do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and Client
ColdFusionConference
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientHow do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
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
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & Chai
Joerg Henning
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
Understanding TDD - theory, practice, techniques and tips.
Understanding TDD - theory, practice, techniques and tips.Understanding TDD - theory, practice, techniques and tips.
Understanding TDD - theory, practice, techniques and tips.
Malinda Kapuruge
 
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
 
Introduction to bdd
Introduction to bddIntroduction to bdd
Introduction to bdd
antannatna
 
ES3-2020-06 Test Driven Development (TDD)
ES3-2020-06 Test Driven Development (TDD)ES3-2020-06 Test Driven Development (TDD)
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
Test Driven Development - a Practitioner’s Perspective
Test Driven Development - a Practitioner’s PerspectiveTest Driven Development - a Practitioner’s Perspective
Test Driven Development - a Practitioner’s Perspective
Malinda Kapuruge
 
How do I write Testable Javascript
How do I write Testable JavascriptHow do I write Testable Javascript
How do I write Testable Javascript
ColdFusionConference
 
How do I write testable javascript?
How do I write testable javascript?How do I write testable javascript?
How do I write testable javascript?
devObjective
 
How do I write Testable Javascript?
How do I write Testable Javascript?How do I write Testable Javascript?
How do I write Testable Javascript?
Gavin Pickin
 
JavaScript development methodology
JavaScript development methodologyJavaScript development methodology
JavaScript development methodology
Aleksander Fabijan
 
Ad

Recently uploaded (20)

Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 

Intro To JavaScript Unit Testing - Ran Mizrahi

  • 1. Introduction to { JavaScript Testing } Ran Mizrahi (@ranm8) Founder and CEO @ CoCycles
  • 2. About { Me } • Founder and CEO of CoCycles. • Former Open Source Dpt. Leader of CodeOasis. • Architected and lead the development of the Wix App Market. • Full-stack and hands-on software engineer.
  • 3. Why Do Software Projects { Fail } ? Production Maintenance • Deliver late or over budget. • Deliver the wrong thing. • Unstable in production. • Expensive maintenance. • Long adjustment to market needs. • Long development cycles.
  • 4. Why Do Software Projects { Fail } ?
  • 5. Untestable { Code }… function createUser(properties) { var user = { firstName: properties.firstName, lastName: properties.lastName, username: properties.username, mail: properties.mail }; var fullName = User.firstName + ' ' + User.lastName; // Make sure user is valid if (!user.firstName || !user.lastName) { throw new Error('First or last name are not valid!'); } else if(typeof user.mail === 'string' && user.mail.match(new RegExp(/^w+@[a-zA-Z_]+?.[a-zA-Z]{ 2,3}$/)) === null) { throw new Error('Mail is not valid'); } else if (!user.username) { throw new Error('Username is not valid'); } $.post('/user', { fullName: fullName, userName: user.username, mail: user.mail }, function(data) { var message; if (data.code === 200) { message = 'User saved successfully!'; } else { message = 'Operation was failed!'; } $('#some-div').animate({ 'margin-left': $(window).width() }, 1000, function() { $(this).html(message); }); }); }
  • 6. The problems with untestable code: • Tightly coupled. • No separation of concerns. • Not readable. • Not predictable. > • Global states. • Long methods. • Large classes/objects. • Hard to maintain. • High learning curve. • Stability issues. • You can never expect problems before they occur Why Test Your { Code } ?
  • 7. { Test-Driven Development } To The Rescue Methodology for using automated unit tests to drive software design, quality and stability.
  • 8. { Test-Driven Development } To The Rescue How it’s done : • First the developer writes a failing test case that defines a desired functionality to the software. • Makes the code pass those tests. • Refactor the code to meet standards.
  • 9. Seems Great But How Much Longer Does { TDD Take } ? My experience: • Initial progress will be slower. • Greater consistency. • Long tern cost is drastically lower • After getting used to it, you can write TDD faster (-: Studies: • Takes 15-30% longer. • 45-80% less bugs. • Fixing bugs later on is dramatically faster.
  • 10. The { Three Rules } of TDD Rule #1 Your code should always fail before you implement the code Rule #2 Implement the simplest code possible to pass your tests. Rule #3 Refactor, refactor and refractor - There is no shame in refactoring.
  • 11. { BDD } Behaviour-Driven Development What exactly are we testing?! Test-Driven Development
  • 12. { BDD } Behaviour-Driven Development • Originally started in 2003 by Dan North, author of JBehave, the first BDD tool. • Based on the TDD methodology. • Aims to provide tools for both developers and business (e.g. product manager, etc.) to share development process together. • The steps of BDD : • Developers and business personas write specification together. • Developer writes tests based on specs and make them fail. • Write code to pass those tests. • Refactor, refactor, refactor...
  • 13. { BDD } Behaviour-Driven Development Feature: ls In order to see the directory structure As a UNIX user I need to be able to list the current directory's contents Scenario: List 2 files in a directory Given I am in a directory "test" And I have a file named "foo" And I have a file named "bar" When I run "ls" Then I should get: """ bar foo """
  • 14. Main { Test Types } • Unit Testing • Integration Testing • Functional Testing
  • 15. { Challenges } Testing JavaScript • Async tests: • Testing async methods can be tricky. • Define tests timeout. • Indicate when test is completed in callback. • Assert on callback. • DOM: • Testing DOM is a difficult task. • The key is to separate your controller and model logic from DOM and test those only. • Testing DOM is done using functional testing (e.g. WebDriver, etc.)
  • 16. TDD/BDD Using { Mocha and ChaiJS } Mocha Mocha is a feature-rich JavaScript test frameworks running on node and the browser, making asynchronies tests easy. Main features: • Supports both TDD and BDD styles. • Simple async testing. • Both browser and node support. • Proper exit status for CI support. • node.js debugger support. • Highly flexible, choose and join the pieces yourself (spy library, assertion library, etc.).
  • 17. TDD/BDD Using { Mocha and ChaiJS } ChaiJS Chai is a BDD / TDD assertion library for node and the browser that can be paired with any JavaScript testing framework. Main features: • BDD/TDD style. • Compatible with all test frameworks. • Both node.js and browser compatible. • Standalone assertion library. • Extendable
  • 18. TDD/BDD Using { Mocha and ChaiJS } Installing Mocha and Chai Install mocha globally using npm: $ npm install mocha -g Install Chai (Locally): $ npm install chai
  • 19. TDD/BDD Using { Mocha and ChaiJS } “Normal” test: var expect = require(‘chai').expect; describe('Array', function() { describe('#indexOf()', function() { it('expect -1 when the value is not present', function() { var array = [1, 2, 3]; expect(array.indexOf(4)).to.be(-1); }); }); }); Run it.. $ mocha --reporter spec Array #indexOf() ✓ Expect -1 when the value is not present 1 test complete (5 ms)
  • 20. TDD/BDD Using { Mocha and ChaiJS } Async test: var expect = require(‘chai').expect; function asyncCall(val ,callback) { var prefix = ' - '; setTimeout(function() { var newString = val + prefix + 'OK'; callback(newString); }, 500); } describe('asyncCall', function() { it('Add suffix that prefixed with - to the given string', function(done) { var testVal = 'Foo'; asyncCall(testVal, function(response) { expect(response).to.contain(testVal + ' - OK'); done(); }); }); }); Let’s run it...
  • 21. Back To { Our Code }
  • 22. First, Let’s { Write The Tests } function createUser(properties) { var user = { firstName: properties.firstName, lastName: properties.lastName, username: properties.username, mail: properties.mail }; var fullName = User.firstName + ' ' + User.lastName; // Make sure user is valid if (!user.firstName || !user.lastName) { throw new Error('First or last name are not valid!'); } else if(typeof user.mail === 'string' && user.mail.match(new RegExp(/^w+@[a-zA-Z_]+?.[a-zA-Z]{ 2,3}$/)) === null) { throw new Error('Mail is not valid'); } else if (!user.username) { throw new Error('Username is not valid'); } $.post('/user', { fullName: fullName, userName: user.username, mail: user.mail }, function(data) { var message; if (data.code === 200) { message = 'User saved successfully!'; } else { message = 'Operation was failed!'; } $('#some-div').animate({ 'margin-left': $(window).width() }, 1000, function() { $(this).html(message); }); }); }
  • 23. First, Let’s { Write The Tests } What to test in our case: • Full name concatenation. • API call data. • Request callback. What not to test : • DOM manipulations - Functional testing (e.g. WebDriver). • API requests - Integration testing.
  • 24. First, Let’s { Write The Unit Tests } describe('#saveUser()', function() { it('should call http service with method POST, path /user, and the user object', function() { }); it('should compose the full name in to the user object', function() { }); it('should only return the payload from the response object', function() { }); }); });
  • 25. The { Implementation } function userService($http, baseUrl) { baseUrl = baseUrl || 'http://google.com/api'; function composeFullName(firstName, lastName) { return firstName + ' ' + lastName; } function returnPayload(response) { return response.payload; } function execute(path, body, method) { return $http({ url: baseUrl + path, method: method || 'GET', data: body }); } return { saveUser: function(user) { user.fullName = composeFullName(user.firstName, user.lastName); return execute('/user', user, 'POST').then(returnPayload); } }; }
  • 26. Implement { Our Unit Tests } describe('user service', function() { var userService, httpMock, thenFunc; function createHttpMock() { thenFunc = sinon.stub(); httpMock = sinon.stub().returns({ then: thenFunc }); } beforeEach(function() { createHttpMock(); userService = UserService(httpMock); }); function getUser() { return { firstName: 'Ran', lastName: 'Mizrahi' }; }
  • 27. Implement { Our Unit Tests } describe('#saveUser()', function() { var user; beforeEach(function() { user = getUser(); userService.saveUser(user); }); it('should call http service with method POST, path /user, and the user object', function() { expect(httpMock).to.have.been.calledWith({ url: 'http://google.com/api/user', method: 'POST', data: user }); }); it('should compose the full name in to the user object', function() { expect(user.fullName).to.equal('Ran Mizrahi'); }); it('should only return the payload from the response object', function() { var returnPayload = thenFunc.args[0][0]; expect(returnPayload({ payload: 'Hello!!!' })).to.equal('Hello!!!'); }); }); });
  • 28. Run Those { Tests Again }
  • 29. Running The { Tests } mocha tests can run in different environments and formats: • Browser - using mocha.js (see example) • For CI automation use JSTestDriver. • CLI - as demonstrated before using the “mocha” command. • CI (e.g. xunit) - $ mocha test/asyncTest.js --reporter xunit. • Many other formats (JSON, HTML, list, Spec, etc.)
  • 30. Benefits of { Testing The Code } • Short feedback/testing cycle. • High code coverage of tests that can be at run any time to provide feedback that the software is functioning. • Provides detailed spec/docs of the application. • Less time spent on debugging and refactoring. • Know what breaks early on. • Enforces code quality and simplicity. • Helps separating units to responsibilities.