SlideShare a Scribd company logo
1 of 32
Download to read offline
Introduction to
JavaScript Testing
Ran Mizrahi (@ranm8)
Open Source Dpt. Leader @ CodeOasis
Saturday, April 27, 13
About CodeOasis
• CodeOasis specializes in cutting-edge web solutions.
• Large variety of customers (from startups to enterprises).
• Technologies we love:
• PHP - Symfony2 and Drupal
• node.js
• HTML5
• CSS3
• AngularJS
• Our Microsoft department works with C#, WPF, etc.
Saturday, April 27, 13
Why Do Software Projects Fail?!
• Deliver late or over budget.
• Deliver the wrong thing.
• Unstable in production.
Production Maintenance
• Expensive maintenance.
• Long adjustment to market
needs.
• Long development cycles.
Saturday, April 27, 13
Why Do Software Projects Fail?!
Saturday, April 27, 13
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);
});
});
}
Saturday, April 27, 13
Why Test Your Code???
The problems with untestable code:
• Tightly coupled.
• No separation of concerns.
• Not readable.
• Not predictable.
• Global states.
• Long methods.
• Large classes/objects.
Saturday, April 27, 13
Why Test Your Code???
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
Saturday, April 27, 13
Test-Driven Development To The Recuse!
Methodology for using automated unit
tests to drive software design, quality
and stability.
Saturday, April 27, 13
Test-Driven Development To The Recuse!
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.
Saturday, April 27, 13
Seems Great But How Much Longer Does TDD Takes???
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.
Saturday, April 27, 13
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.
Saturday, April 27, 13
BDD (Behavior-Driven Development)
Test-Driven Development
Saturday, April 27, 13
BDD (Behavior-Driven Development)
Test-Driven Development
What exactly are we testing?!
Saturday, April 27, 13
BDD (Behavior-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...
Saturday, April 27, 13
BDD (Behavior-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
"""
Saturday, April 27, 13
Main Test Types
• Unit Testing
• Integration Testing
• Functional Testing
Saturday, April 27, 13
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.)
Saturday, April 27, 13
TDD/BDD using Mocha and Expect.js
Mocha is a feature-rich JavaScript test frameworks running on
node and the browser, making asynchronies tests easy.
Mocha
Main features:
• Supports both TDD and BDD styles.
• 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.).
Saturday, April 27, 13
TDD/BDD using Mocha and Expect.js
Expect.js is a minimalistic assertion library based on should.js
Expect.js
Main features:
• BDD style.
• Compatible with all test frameworks.
• Both node.js and browser compatible.
• Standalone assertion library.
Saturday, April 27, 13
TDD/BDD using Mocha and Expect.js
Installing Mocha and Expect.js
$ npm install mocha -g
$ npm install expect.js -g
Install mocha globally using npm:
Install Expect.js:
Saturday, April 27, 13
TDD/BDD using Mocha and Expect.js
var expect = require('expect.js');
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);
});
});
});
“Normal” test:
Run it..
$ mocha --reporter spec
Array
#indexOf()
✓ Expect -1 when the value is not present
1 test complete (5 ms)
Saturday, April 27, 13
TDD/BDD using Mocha and Expect.js
“Async” test:
var expect = require('expect.js');
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...
Saturday, April 27, 13
Back to our code
Saturday, April 27, 13
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);
});
});
}
Saturday, April 27, 13
First, Let’s Write The Tests!
What to test in our case:
• Validations.
• Full name getter.
• User save callback
What not to test :
• DOM manipulations - for that, we should use functional testing for
that cause (e.g. WebDriver)
• AJAX requests - Leaving integration testing aside.
Saturday, April 27, 13
First, Let’s Write The Tests!
describe('User', function() {
var user;
beforeEach(function() {
// Create the user obj
user = new User({
firstName: 'Ran',
lastName: 'Mizrahi',
mail: 'ranm@codeoasis.com',
username: 'ranm'
});
});
afterEach(function() {
// clean-up
user = {};
});
describe('#fullName()', function() {
it('Should return firstName and lastName separated by space', function() {
expect(user.fullName).to.be('Ran Mizrahi');
});
});
describe('#save()', function() {
it('Should save user without any errors', function(done) {
user.save(function(error) {
if (error) {
throw error;
} else {
done();
}
});
});
});
describe('#mail()', function() {
it('Should set mail correctly after mail validation', function() {
expect(user.mail).to.be('ranm@codeoasis.com');
});
});
});
Saturday, April 27, 13
Run those tests
Saturday, April 27, 13
Now, Let’s Write The Code
var User = (function() {
'use strict';
var User = function(properties) {
// Set some data
this.firstName = properties.firstName || '';
this.lastName = properties.lastName || '';
this.username = properties.username || '';
this.mail = properties.mail || '';
};
User.__defineGetter__('fullName', function() {
return this.firstName + ' ' + this.lastName;
});
User.__defineSetter__('mail', function(mail) {
var matcher = new RegExp(/^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/);
if (mail.match(matcher) === null) {
throw 'Mail is not valid';
}
this._mail = mail;
});
User.prototype.save = function(callback) {
setTimeout(function() {
callback();
}, 1000);
return this;
};
return User;
}());
Saturday, April 27, 13
Run those tests,
again!
Saturday, April 27, 13
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.)
Saturday, April 27, 13
Benefits of Testing Your 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 (decoupled) and simplicity.
• Help you focus on writing one job code units.
Saturday, April 27, 13
Questions?
Thank you!
Saturday, April 27, 13

More Related Content

What's hot

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
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
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaChristopher Bartling
 
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
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQueryKnoldus Inc.
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksJuho Vepsäläinen
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma Christopher Bartling
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaAndrey Kolodnitsky
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsVisual Engineering
 

What's hot (20)

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
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
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
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
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Angular testing
Angular testingAngular testing
Angular testing
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 

Viewers also liked

Getting merged
Getting mergedGetting merged
Getting mergedLin Yo-An
 
Understanding Your Content
Understanding Your ContentUnderstanding Your Content
Understanding Your ContentChiara Fox Ogan
 
Me, write an exam?
Me, write an exam?Me, write an exam?
Me, write an exam?JoAnn MIller
 
My Carnegie Mellon University Master\'s Thesis
My Carnegie Mellon University Master\'s ThesisMy Carnegie Mellon University Master\'s Thesis
My Carnegie Mellon University Master\'s ThesisJonas Rolo
 
Cloud gate_tramping in china
Cloud gate_tramping in chinaCloud gate_tramping in china
Cloud gate_tramping in chinabliaou
 
Founders Fund Manifesto
Founders Fund ManifestoFounders Fund Manifesto
Founders Fund ManifestoRazin Mustafiz
 
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 DavidsonRazin Mustafiz
 
Snowflakes
SnowflakesSnowflakes
Snowflakesh0nnie
 
A framework for measuring social media
A framework for measuring social mediaA framework for measuring social media
A framework for measuring social mediaJenni Lloyd
 
ярмарка инноваций в образовании для веб
ярмарка инноваций в образовании для вебярмарка инноваций в образовании для веб
ярмарка инноваций в образовании для вебssjaspb
 
Idiazabal gazta on linen satzeko marketin-plana
Idiazabal gazta on linen satzeko marketin-planaIdiazabal gazta on linen satzeko marketin-plana
Idiazabal gazta on linen satzeko marketin-planaItxaso Ferreras
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application FrameworkRan Mizrahi
 
Mappeoppgave 2 2003
Mappeoppgave 2   2003Mappeoppgave 2   2003
Mappeoppgave 2 2003Anniken
 
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
 

Viewers also liked (20)

Getting merged
Getting mergedGetting merged
Getting merged
 
Understanding Your Content
Understanding Your ContentUnderstanding Your Content
Understanding Your Content
 
Introduction
IntroductionIntroduction
Introduction
 
Me, write an exam?
Me, write an exam?Me, write an exam?
Me, write an exam?
 
My Carnegie Mellon University Master\'s Thesis
My Carnegie Mellon University Master\'s ThesisMy Carnegie Mellon University Master\'s Thesis
My Carnegie Mellon University Master\'s Thesis
 
1112
11121112
1112
 
Cloud gate_tramping in china
Cloud gate_tramping in chinaCloud gate_tramping in china
Cloud gate_tramping in china
 
Founders Fund Manifesto
Founders Fund ManifestoFounders Fund Manifesto
Founders Fund Manifesto
 
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
 
Snowflakes
SnowflakesSnowflakes
Snowflakes
 
Gita ch 3
Gita ch 3Gita ch 3
Gita ch 3
 
A framework for measuring social media
A framework for measuring social mediaA framework for measuring social media
A framework for measuring social media
 
What's a Wiki?
What's a Wiki?What's a Wiki?
What's a Wiki?
 
Euskara Motibazioak
Euskara MotibazioakEuskara Motibazioak
Euskara Motibazioak
 
ярмарка инноваций в образовании для веб
ярмарка инноваций в образовании для вебярмарка инноваций в образовании для веб
ярмарка инноваций в образовании для веб
 
Idiazabal gazta on linen satzeko marketin-plana
Idiazabal gazta on linen satzeko marketin-planaIdiazabal gazta on linen satzeko marketin-plana
Idiazabal gazta on linen satzeko marketin-plana
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application Framework
 
Mappeoppgave 2 2003
Mappeoppgave 2   2003Mappeoppgave 2   2003
Mappeoppgave 2 2003
 
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)
 
P2 Tour
P2 TourP2 Tour
P2 Tour
 

Similar to Intro to JavaScript Testing

Intro to PHP Testing
Intro to PHP TestingIntro to PHP Testing
Intro to PHP TestingRan Mizrahi
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"GeeksLab Odessa
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jskiyanwang
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profilerIhor Bobak
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Testing iOS Apps
Testing iOS AppsTesting iOS Apps
Testing iOS AppsC4Media
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OTgetch123
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesTriTAUG
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014Alex Kavanagh
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptdavejohnson
 
Unit tests in node.js
Unit tests in node.jsUnit tests in node.js
Unit tests in node.jsRotem Tamir
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 

Similar to Intro to JavaScript Testing (20)

Intro to PHP Testing
Intro to PHP TestingIntro to PHP Testing
Intro to PHP Testing
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.js
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Testing iOS Apps
Testing iOS AppsTesting iOS Apps
Testing iOS Apps
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OT
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
How we're building Wercker
How we're building WerckerHow we're building Wercker
How we're building Wercker
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and Challenges
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 
Unit tests in node.js
Unit tests in node.jsUnit tests in node.js
Unit tests in node.js
 
Java scriptforjavadev part2a
Java scriptforjavadev part2aJava scriptforjavadev part2a
Java scriptforjavadev part2a
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Spring IO 2015 Spock Workshop
Spring IO 2015 Spock WorkshopSpring IO 2015 Spock Workshop
Spring IO 2015 Spock Workshop
 

Recently uploaded

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Intro to JavaScript Testing

  • 1. Introduction to JavaScript Testing Ran Mizrahi (@ranm8) Open Source Dpt. Leader @ CodeOasis Saturday, April 27, 13
  • 2. About CodeOasis • CodeOasis specializes in cutting-edge web solutions. • Large variety of customers (from startups to enterprises). • Technologies we love: • PHP - Symfony2 and Drupal • node.js • HTML5 • CSS3 • AngularJS • Our Microsoft department works with C#, WPF, etc. Saturday, April 27, 13
  • 3. Why Do Software Projects Fail?! • Deliver late or over budget. • Deliver the wrong thing. • Unstable in production. Production Maintenance • Expensive maintenance. • Long adjustment to market needs. • Long development cycles. Saturday, April 27, 13
  • 4. Why Do Software Projects Fail?! Saturday, April 27, 13
  • 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); }); }); } Saturday, April 27, 13
  • 6. Why Test Your Code??? The problems with untestable code: • Tightly coupled. • No separation of concerns. • Not readable. • Not predictable. • Global states. • Long methods. • Large classes/objects. Saturday, April 27, 13
  • 7. Why Test Your Code??? 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 Saturday, April 27, 13
  • 8. Test-Driven Development To The Recuse! Methodology for using automated unit tests to drive software design, quality and stability. Saturday, April 27, 13
  • 9. Test-Driven Development To The Recuse! 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. Saturday, April 27, 13
  • 10. Seems Great But How Much Longer Does TDD Takes??? 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. Saturday, April 27, 13
  • 11. 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. Saturday, April 27, 13
  • 12. BDD (Behavior-Driven Development) Test-Driven Development Saturday, April 27, 13
  • 13. BDD (Behavior-Driven Development) Test-Driven Development What exactly are we testing?! Saturday, April 27, 13
  • 14. BDD (Behavior-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... Saturday, April 27, 13
  • 15. BDD (Behavior-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 """ Saturday, April 27, 13
  • 16. Main Test Types • Unit Testing • Integration Testing • Functional Testing Saturday, April 27, 13
  • 17. 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.) Saturday, April 27, 13
  • 18. TDD/BDD using Mocha and Expect.js Mocha is a feature-rich JavaScript test frameworks running on node and the browser, making asynchronies tests easy. Mocha Main features: • Supports both TDD and BDD styles. • 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.). Saturday, April 27, 13
  • 19. TDD/BDD using Mocha and Expect.js Expect.js is a minimalistic assertion library based on should.js Expect.js Main features: • BDD style. • Compatible with all test frameworks. • Both node.js and browser compatible. • Standalone assertion library. Saturday, April 27, 13
  • 20. TDD/BDD using Mocha and Expect.js Installing Mocha and Expect.js $ npm install mocha -g $ npm install expect.js -g Install mocha globally using npm: Install Expect.js: Saturday, April 27, 13
  • 21. TDD/BDD using Mocha and Expect.js var expect = require('expect.js'); 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); }); }); }); “Normal” test: Run it.. $ mocha --reporter spec Array #indexOf() ✓ Expect -1 when the value is not present 1 test complete (5 ms) Saturday, April 27, 13
  • 22. TDD/BDD using Mocha and Expect.js “Async” test: var expect = require('expect.js'); 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... Saturday, April 27, 13
  • 23. Back to our code Saturday, April 27, 13
  • 24. 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); }); }); } Saturday, April 27, 13
  • 25. First, Let’s Write The Tests! What to test in our case: • Validations. • Full name getter. • User save callback What not to test : • DOM manipulations - for that, we should use functional testing for that cause (e.g. WebDriver) • AJAX requests - Leaving integration testing aside. Saturday, April 27, 13
  • 26. First, Let’s Write The Tests! describe('User', function() { var user; beforeEach(function() { // Create the user obj user = new User({ firstName: 'Ran', lastName: 'Mizrahi', mail: 'ranm@codeoasis.com', username: 'ranm' }); }); afterEach(function() { // clean-up user = {}; }); describe('#fullName()', function() { it('Should return firstName and lastName separated by space', function() { expect(user.fullName).to.be('Ran Mizrahi'); }); }); describe('#save()', function() { it('Should save user without any errors', function(done) { user.save(function(error) { if (error) { throw error; } else { done(); } }); }); }); describe('#mail()', function() { it('Should set mail correctly after mail validation', function() { expect(user.mail).to.be('ranm@codeoasis.com'); }); }); }); Saturday, April 27, 13
  • 28. Now, Let’s Write The Code var User = (function() { 'use strict'; var User = function(properties) { // Set some data this.firstName = properties.firstName || ''; this.lastName = properties.lastName || ''; this.username = properties.username || ''; this.mail = properties.mail || ''; }; User.__defineGetter__('fullName', function() { return this.firstName + ' ' + this.lastName; }); User.__defineSetter__('mail', function(mail) { var matcher = new RegExp(/^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/); if (mail.match(matcher) === null) { throw 'Mail is not valid'; } this._mail = mail; }); User.prototype.save = function(callback) { setTimeout(function() { callback(); }, 1000); return this; }; return User; }()); Saturday, April 27, 13
  • 30. 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.) Saturday, April 27, 13
  • 31. Benefits of Testing Your 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 (decoupled) and simplicity. • Help you focus on writing one job code units. Saturday, April 27, 13