SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
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?

Mais conteúdo relacionado

Mais procurados

JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
Unit and functional testing with Siesta
Unit and functional testing with SiestaUnit and functional testing with Siesta
Unit and functional testing with SiestaGrgur 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 KarmaExoLeaders.com
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksAddy Osmani
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJSPeter 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 JourneyOren Farhi
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to ProtractorJie-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 frontendFrederic CABASSUT
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksJuho Vepsäläinen
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend TestingNeil 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.3Fabien Potencier
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practicesYoni Goldberg
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats 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 MizrahiRan Mizrahi
 

Mais procurados (20)

JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
Unit and functional testing with Siesta
Unit and functional testing with SiestaUnit and functional testing with Siesta
Unit and functional testing with Siesta
 
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
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
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
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 
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)
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
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
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Night Watch with QA
Night Watch with QANight Watch with QA
Night Watch with QA
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
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
 

Destaque (20)

Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application Framework
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
Bitcoin for humans
Bitcoin for humansBitcoin for humans
Bitcoin for humans
 
Product development for startups
Product development for startupsProduct development for startups
Product development for startups
 
1119
11191119
1119
 
Final Presentation
Final PresentationFinal Presentation
Final Presentation
 
Jugaaad: Innovation book
Jugaaad: Innovation bookJugaaad: Innovation book
Jugaaad: Innovation book
 
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
 
Founders Fund Manifesto
Founders Fund ManifestoFounders Fund Manifesto
Founders Fund Manifesto
 
Microworlds pro
Microworlds proMicroworlds pro
Microworlds pro
 
Cheeky Carbon Presentation
Cheeky Carbon PresentationCheeky Carbon Presentation
Cheeky Carbon Presentation
 
4. prosegizontas tin ekpadeutiki omada
4. prosegizontas tin ekpadeutiki omada4. prosegizontas tin ekpadeutiki omada
4. prosegizontas tin ekpadeutiki omada
 
Wemagazine
WemagazineWemagazine
Wemagazine
 
Publish2 Tour
Publish2 TourPublish2 Tour
Publish2 Tour
 
G earth
G earthG earth
G earth
 
1104
11041104
1104
 
Sticky Information - Von Hippel
Sticky Information - Von HippelSticky Information - Von Hippel
Sticky Information - Von Hippel
 
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
 
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
 
Diadrastikoi a theoritiko plaisio
Diadrastikoi a theoritiko plaisioDiadrastikoi a theoritiko plaisio
Diadrastikoi a theoritiko plaisio
 

Semelhante a Intro To JavaScript Unit Testing - Ran Mizrahi

SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
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
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanizecoreygoldberg
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance testBryan Liu
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
SwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupSwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupErnest Jumbe
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
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
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 

Semelhante a Intro To JavaScript Unit Testing - Ran Mizrahi (20)

SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
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
 
Testing in JavaScript
Testing in JavaScriptTesting in JavaScript
Testing in JavaScript
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
SwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupSwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup Group
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
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 -
 
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
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 

Último

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Último (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

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.