SlideShare a Scribd company logo
1 of 30
Download to read offline
JS Unit Testing
For both Backend and Frontend
Why is unit testing good for js?
● you can develop without a browser
● you can test your code automatically
● you don’t have to test manually
● you don’t have to test via E2E test
● you can develop without a browser
○ of course for view development you have to use
● you can test you BE code
Prerequisite (conditions)
● well separated code
○ like mvc (no spaghetti code)
○ small, testable parts (classes)
● zero or minimal dom dependency
○ dom is slow
○ very slow and you don’t want to mock it out
How to test JS?
● you need a library
○ mocha
○ jasmine
○ Qunit
○ etc
● you have to run your tests
○ browser
○ node
○ karma (odd one out)
○ etc
What I’m using
● Mocha
○ works with node
○ works with browser(s) (karma)
● Chai-TDD
○ closest to ruby expect
Example JS code - User Model
var User;
User = (function() {
function User(plainObject) {
this.parse(plainObject);
}
User.prototype.parse = function(plainObject) {
this.id = plainObject.id;
this.first_name = plainObject.first_name;
this.last_name = plainObject.last_name;
this.status = plainObject.status;
};
return User;
})();
How can we test Our Model?
describe('User/Model', function() {
var dummyUserData = {
id: 1,
first_name: 'First',
last_name: 'Last',
status: 'locked'
};
describe('#initialize', function() {
it('should set the provided fields', function() {
var user = new User(dummyUserData);
expect(user.first_name).to.eq('First');
expect(user.last_name).to.eq('Last');
expect(user.status).to.eq('locked');
});
});
});
Test with a browser
● Create a test.html
● Include
○ mocha.js
○ chai.js
○ user_model.js
○ user_model_test.js
● open test.html
open test.html
How to use xhr in your model?
User.prototype.get = function(cbSuccess, cbError) {
var self = this;
$.get("/users/" + this.id, function(data) {
self.parse(data);
cbSuccess();
}).fail(function(error, m) {
cbError();
});
};
In the browser you should
● include sinon.js
○ spy/stub/mock library
● include sinon server
○ xhr mocking server
How to test async call?
describe('with success xhr', function() {
beforeEach(function() {
var response = '{ "id": 1, "first_name": "Second First", "last_name": "Second Last", "status": "active" }';
server = sinon.fakeServer.create();
server.respondWith("GET", "/users/1", [200, { "Content-Type": "application/json" }, response ]);
});
afterEach(function() {
server.restore();
});
it('should set the newly provided data', function(done) {
user.get(function() {
expect(user.first_name).to.eq('Second First');
....
done();
});
server.respond();
});
});
open test.html
Test with multiple browsers (karma)
● open the browsers
(silently)
● run your tests
● close the browsers
(optional)
● rerun your tests on file
changes (optional)
● outputs results to your
console
karma.conf.js
{
frameworks: ['mocha', 'chai'],
files: [
'vendor/**/*.js',
'user_model.js',
'user_model_tests.js'
],
autoWatch: false,
browsers: ['Chrome', 'Firefox'],
singleRun: true
};
karma start
Test with node
● basically the same as in browsers
○ only difference is the module system require
(‘module’)
● faster than browsers
● you can test your BE and FE with the same
test runner
○ if you doesn’t use browser specific stuff (like xhr,
window, dom etc)
Test with node
var request = require("superagent");
var User;
User = (function() {
...
User.prototype.get = function(cbSuccess) {
var url = "/users/" + this.id;
request.get(url, function(res) {
this.parse(res);
cbSuccess();
}.bind(this));
};
return User;
})();
module.exports = User;
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var User = require('../src/user');
var request = require("superagent");
describe('User/Model', function() {
beforeEach(function() {
var response = var response = '{ "id": 1, "first_name":
"Second First", "last_name": "Second Last", "status":
"active" }';
sinon.stub(request, "get").yields(response);
});
});
....
mocha
● While I develop I want to to test my code via
node
○ a lot faster
○ easier to test partials
● When I build I want to test my code via karma
○ we have to know if something is wrong in IE
Same tests with node and karma
Browserify
● you can use nodejs module syntax on the
frontend
○ var UserModel = require(“Modules/User/Model”);
○ var userModel = new UserModel();
● generate one js file with all the dependencies
● you can use same libraries on the FE and on
the BE part
○ moment.js
○ schemata (js validation library)
○ your custom lib
Schemate schema def.
var schemata = require('schemata');
var UserSchema = schemata({
first_name: {
name: 'First Name',
type: String,
validators: { all: [req] }
},
last_name: {
name: 'Last Name',
type: String,
validators: { all: [req] }
},
status: {
type: String,
default: 'locked',
validators: { all: [req] }
}
});
module.exports = UserSchema;
REQUIRE VALIDATOR
var req = function(key, keyDisplayName, object, callback) {
var value = object[key];
if (typeof value !== “undefined” && value !== null){
return callback(null, undefined);
} else {
return callback(null, ' is required' );
}
};
FE
buttonClick = function(){
var json = this.toJson();
UserSchema.validate(json, function(errors){
if (Object.keys(errors).length === 0) return sendAjaxToTheServer(json);
showErrors(errors);
});
}
Use browserify with mocha
● everything is the
same as in the
node tests
● you have to use
karma
preprocessor
{
frameworks: ['mocha', 'browserify'],
preprocessors: {
'test/*': ['browserify']
}
....
};
Test with node / karma
var request = require("superagent");
var User;
User = (function() {
...
User.prototype.get = function(cbSuccess) {
var url = "/users/" + this.id;
request.get(url, function(res) {
this.parse(res);
cbSuccess();
}.bind(this));
};
return User;
})();
module.exports = User;
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var User = require('../src/user');
var request = require("superagent");
describe('User/Model', function() {
beforeEach(function() {
var response = var response = '{ "id": 1, "first_name":
"Second First", "last_name": "Second Last", "status":
"active" }';
sinon.stub(request, "get").yields(response);
});
});
....
karma start | mocha
Grunt - Config based Task runner
● There are a lot of contributed tasks
○ mochaTest, karma, browserify, concatenate, copy, ftp,
sass, less, etc
● you can define complex tasks
○ build (jshint, concatenate, test:unit, test:e2e)
○ test (jshint, test:unit)
○ deploy (build, ftp)
Grunt example
You can create complex tasks
test:
- 'karma'
- 'mochaTest'
build:
- 'jshint'
- 'test'
- 'browserify'
- 'concatenate'
- 'minify'
- 'sass'
- 'copy'
Simple task, using grunt-contrib-mocha
configuration file:
mochaTest:
feTest:
options:
clearRequireCache: true
reporter: 'spec'
src: ['test/fe/**/*.js']
beTest:
options:
clearRequireCache: true
reporter: 'dots'
src: ['test/be/**/*.js']
grunt test
Grunt watch
● watches for file
changes
● runs tasks if one of
the specified files
have changed
watch:
scripts:
files: ['test/unit/**/*.js', 'src/js/**/*.js']
tasks: ['jshint', 'mocha']
interrupt: true
options:
spawn: false
jade:
files: ['src/view/**/*.jade']
tasks: ['jade', ‘livereload:html’]
interrupt: true
options:
spawn: false
stylus:
files: ['src/style/**/*.styl']
tasks: ['stylus', ‘livereload:css’]
interrupt: false
options:
spawn: false
grunt watch
https://github.com/Valetudox/js_unit_testing
we are hiring :)

More Related Content

What's hot

Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Dennis Byrne
 
Rx java testing patterns
Rx java testing patternsRx java testing patterns
Rx java testing patterns彥彬 洪
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorDavid Rodenas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interfaceJoakim Gustin
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in OdooOdoo
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperJon Kruger
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]JavaScript Meetup HCMC
 
Testable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScriptTestable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScriptJon Kruger
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React NativeSoftware Guru
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2Eyal Vardi
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 

What's hot (20)

Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)
 
Server1
Server1Server1
Server1
 
Rx java testing patterns
Rx java testing patternsRx java testing patterns
Rx java testing patterns
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD Calculator
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
java script
java scriptjava script
java script
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
JS and patterns
JS and patternsJS and patterns
JS and patterns
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
 
Testable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScriptTestable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScript
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 

Viewers also liked

Ruby meetup 7_years_in_testing
Ruby meetup 7_years_in_testingRuby meetup 7_years_in_testing
Ruby meetup 7_years_in_testingDigital Natives
 
Evolution of the Software Development Process ad Digital Natives
Evolution of the Software Development Process ad Digital NativesEvolution of the Software Development Process ad Digital Natives
Evolution of the Software Development Process ad Digital NativesDigital Natives
 
Basics of Metaprogramming in Ruby
Basics of Metaprogramming in RubyBasics of Metaprogramming in Ruby
Basics of Metaprogramming in RubyDigital Natives
 
Digital natives incubation process_2011-11-23_v09
Digital natives incubation process_2011-11-23_v09Digital natives incubation process_2011-11-23_v09
Digital natives incubation process_2011-11-23_v09Digital Natives
 
JRuby talk / 26.03.2014 / @vbalazs
JRuby talk / 26.03.2014 / @vbalazsJRuby talk / 26.03.2014 / @vbalazs
JRuby talk / 26.03.2014 / @vbalazsBalázs Varga
 
Kanban Basics for Beginners
Kanban Basics for BeginnersKanban Basics for Beginners
Kanban Basics for BeginnersZsolt Fabok
 

Viewers also liked (6)

Ruby meetup 7_years_in_testing
Ruby meetup 7_years_in_testingRuby meetup 7_years_in_testing
Ruby meetup 7_years_in_testing
 
Evolution of the Software Development Process ad Digital Natives
Evolution of the Software Development Process ad Digital NativesEvolution of the Software Development Process ad Digital Natives
Evolution of the Software Development Process ad Digital Natives
 
Basics of Metaprogramming in Ruby
Basics of Metaprogramming in RubyBasics of Metaprogramming in Ruby
Basics of Metaprogramming in Ruby
 
Digital natives incubation process_2011-11-23_v09
Digital natives incubation process_2011-11-23_v09Digital natives incubation process_2011-11-23_v09
Digital natives incubation process_2011-11-23_v09
 
JRuby talk / 26.03.2014 / @vbalazs
JRuby talk / 26.03.2014 / @vbalazsJRuby talk / 26.03.2014 / @vbalazs
JRuby talk / 26.03.2014 / @vbalazs
 
Kanban Basics for Beginners
Kanban Basics for BeginnersKanban Basics for Beginners
Kanban Basics for Beginners
 

Similar to Testing in JavaScript

Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Browser testing with nightwatch.js - Drupal Europe
Browser testing with nightwatch.js - Drupal EuropeBrowser testing with nightwatch.js - Drupal Europe
Browser testing with nightwatch.js - Drupal EuropeSalvador Molina (Slv_)
 
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsDrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsVladimir Roudakov
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
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
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013Laurent_VB
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with exampleshadabgilani
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
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
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance testBryan Liu
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with WebpackThiago Temple
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with JestMichał Pierzchała
 

Similar to Testing in JavaScript (20)

Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Browser testing with nightwatch.js - Drupal Europe
Browser testing with nightwatch.js - Drupal EuropeBrowser testing with nightwatch.js - Drupal Europe
Browser testing with nightwatch.js - Drupal Europe
 
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsDrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
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
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Testing in airflow
Testing in airflowTesting in airflow
Testing in airflow
 
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
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
AngularJS and SPA
AngularJS and SPAAngularJS and SPA
AngularJS and SPA
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 

More from Digital Natives

How to support innovation in organisations @ Startup Safary
How to support innovation in organisations @ Startup SafaryHow to support innovation in organisations @ Startup Safary
How to support innovation in organisations @ Startup SafaryDigital Natives
 
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...Digital Natives
 
Agile és lean workshop @ Startup Safary
Agile és lean workshop @ Startup SafaryAgile és lean workshop @ Startup Safary
Agile és lean workshop @ Startup SafaryDigital Natives
 
Introduction to GraphQL with Ruby
Introduction to GraphQL with RubyIntroduction to GraphQL with Ruby
Introduction to GraphQL with RubyDigital Natives
 
A visual introduction to concurrency and parallellism patterns
A visual introduction to concurrency and parallellism patternsA visual introduction to concurrency and parallellism patterns
A visual introduction to concurrency and parallellism patternsDigital Natives
 
How flat organisations support the innovation
How flat organisations support the innovationHow flat organisations support the innovation
How flat organisations support the innovationDigital Natives
 
Mixgar in Volt festival 2011
Mixgar in Volt festival 2011Mixgar in Volt festival 2011
Mixgar in Volt festival 2011Digital Natives
 
Budapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails DeploymentBudapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails DeploymentDigital Natives
 

More from Digital Natives (11)

How to support innovation in organisations @ Startup Safary
How to support innovation in organisations @ Startup SafaryHow to support innovation in organisations @ Startup Safary
How to support innovation in organisations @ Startup Safary
 
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
 
Agile és lean workshop @ Startup Safary
Agile és lean workshop @ Startup SafaryAgile és lean workshop @ Startup Safary
Agile és lean workshop @ Startup Safary
 
Introduction to GraphQL with Ruby
Introduction to GraphQL with RubyIntroduction to GraphQL with Ruby
Introduction to GraphQL with Ruby
 
A visual introduction to concurrency and parallellism patterns
A visual introduction to concurrency and parallellism patternsA visual introduction to concurrency and parallellism patterns
A visual introduction to concurrency and parallellism patterns
 
How flat organisations support the innovation
How flat organisations support the innovationHow flat organisations support the innovation
How flat organisations support the innovation
 
CULTURE OF INNOVATION
CULTURE OF INNOVATIONCULTURE OF INNOVATION
CULTURE OF INNOVATION
 
Mixgar in Volt festival 2011
Mixgar in Volt festival 2011Mixgar in Volt festival 2011
Mixgar in Volt festival 2011
 
Mixgar prezi v1.2
Mixgar prezi v1.2Mixgar prezi v1.2
Mixgar prezi v1.2
 
Budapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails DeploymentBudapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails Deployment
 
Budapest.rb 201010
Budapest.rb 201010Budapest.rb 201010
Budapest.rb 201010
 

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
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

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
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

Testing in JavaScript

  • 1. JS Unit Testing For both Backend and Frontend
  • 2. Why is unit testing good for js? ● you can develop without a browser ● you can test your code automatically ● you don’t have to test manually ● you don’t have to test via E2E test ● you can develop without a browser ○ of course for view development you have to use ● you can test you BE code
  • 3. Prerequisite (conditions) ● well separated code ○ like mvc (no spaghetti code) ○ small, testable parts (classes) ● zero or minimal dom dependency ○ dom is slow ○ very slow and you don’t want to mock it out
  • 4. How to test JS? ● you need a library ○ mocha ○ jasmine ○ Qunit ○ etc ● you have to run your tests ○ browser ○ node ○ karma (odd one out) ○ etc
  • 5. What I’m using ● Mocha ○ works with node ○ works with browser(s) (karma) ● Chai-TDD ○ closest to ruby expect
  • 6. Example JS code - User Model var User; User = (function() { function User(plainObject) { this.parse(plainObject); } User.prototype.parse = function(plainObject) { this.id = plainObject.id; this.first_name = plainObject.first_name; this.last_name = plainObject.last_name; this.status = plainObject.status; }; return User; })();
  • 7. How can we test Our Model? describe('User/Model', function() { var dummyUserData = { id: 1, first_name: 'First', last_name: 'Last', status: 'locked' }; describe('#initialize', function() { it('should set the provided fields', function() { var user = new User(dummyUserData); expect(user.first_name).to.eq('First'); expect(user.last_name).to.eq('Last'); expect(user.status).to.eq('locked'); }); }); });
  • 8. Test with a browser ● Create a test.html ● Include ○ mocha.js ○ chai.js ○ user_model.js ○ user_model_test.js ● open test.html
  • 10. How to use xhr in your model? User.prototype.get = function(cbSuccess, cbError) { var self = this; $.get("/users/" + this.id, function(data) { self.parse(data); cbSuccess(); }).fail(function(error, m) { cbError(); }); };
  • 11. In the browser you should ● include sinon.js ○ spy/stub/mock library ● include sinon server ○ xhr mocking server
  • 12. How to test async call? describe('with success xhr', function() { beforeEach(function() { var response = '{ "id": 1, "first_name": "Second First", "last_name": "Second Last", "status": "active" }'; server = sinon.fakeServer.create(); server.respondWith("GET", "/users/1", [200, { "Content-Type": "application/json" }, response ]); }); afterEach(function() { server.restore(); }); it('should set the newly provided data', function(done) { user.get(function() { expect(user.first_name).to.eq('Second First'); .... done(); }); server.respond(); }); });
  • 14. Test with multiple browsers (karma) ● open the browsers (silently) ● run your tests ● close the browsers (optional) ● rerun your tests on file changes (optional) ● outputs results to your console karma.conf.js { frameworks: ['mocha', 'chai'], files: [ 'vendor/**/*.js', 'user_model.js', 'user_model_tests.js' ], autoWatch: false, browsers: ['Chrome', 'Firefox'], singleRun: true };
  • 16. Test with node ● basically the same as in browsers ○ only difference is the module system require (‘module’) ● faster than browsers ● you can test your BE and FE with the same test runner ○ if you doesn’t use browser specific stuff (like xhr, window, dom etc)
  • 17. Test with node var request = require("superagent"); var User; User = (function() { ... User.prototype.get = function(cbSuccess) { var url = "/users/" + this.id; request.get(url, function(res) { this.parse(res); cbSuccess(); }.bind(this)); }; return User; })(); module.exports = User; var chai = require('chai'); var expect = chai.expect; var sinon = require('sinon'); var User = require('../src/user'); var request = require("superagent"); describe('User/Model', function() { beforeEach(function() { var response = var response = '{ "id": 1, "first_name": "Second First", "last_name": "Second Last", "status": "active" }'; sinon.stub(request, "get").yields(response); }); }); ....
  • 18. mocha
  • 19. ● While I develop I want to to test my code via node ○ a lot faster ○ easier to test partials ● When I build I want to test my code via karma ○ we have to know if something is wrong in IE Same tests with node and karma
  • 20. Browserify ● you can use nodejs module syntax on the frontend ○ var UserModel = require(“Modules/User/Model”); ○ var userModel = new UserModel(); ● generate one js file with all the dependencies ● you can use same libraries on the FE and on the BE part ○ moment.js ○ schemata (js validation library) ○ your custom lib
  • 21. Schemate schema def. var schemata = require('schemata'); var UserSchema = schemata({ first_name: { name: 'First Name', type: String, validators: { all: [req] } }, last_name: { name: 'Last Name', type: String, validators: { all: [req] } }, status: { type: String, default: 'locked', validators: { all: [req] } } }); module.exports = UserSchema; REQUIRE VALIDATOR var req = function(key, keyDisplayName, object, callback) { var value = object[key]; if (typeof value !== “undefined” && value !== null){ return callback(null, undefined); } else { return callback(null, ' is required' ); } }; FE buttonClick = function(){ var json = this.toJson(); UserSchema.validate(json, function(errors){ if (Object.keys(errors).length === 0) return sendAjaxToTheServer(json); showErrors(errors); }); }
  • 22. Use browserify with mocha ● everything is the same as in the node tests ● you have to use karma preprocessor { frameworks: ['mocha', 'browserify'], preprocessors: { 'test/*': ['browserify'] } .... };
  • 23. Test with node / karma var request = require("superagent"); var User; User = (function() { ... User.prototype.get = function(cbSuccess) { var url = "/users/" + this.id; request.get(url, function(res) { this.parse(res); cbSuccess(); }.bind(this)); }; return User; })(); module.exports = User; var chai = require('chai'); var expect = chai.expect; var sinon = require('sinon'); var User = require('../src/user'); var request = require("superagent"); describe('User/Model', function() { beforeEach(function() { var response = var response = '{ "id": 1, "first_name": "Second First", "last_name": "Second Last", "status": "active" }'; sinon.stub(request, "get").yields(response); }); }); ....
  • 24. karma start | mocha
  • 25. Grunt - Config based Task runner ● There are a lot of contributed tasks ○ mochaTest, karma, browserify, concatenate, copy, ftp, sass, less, etc ● you can define complex tasks ○ build (jshint, concatenate, test:unit, test:e2e) ○ test (jshint, test:unit) ○ deploy (build, ftp)
  • 26. Grunt example You can create complex tasks test: - 'karma' - 'mochaTest' build: - 'jshint' - 'test' - 'browserify' - 'concatenate' - 'minify' - 'sass' - 'copy' Simple task, using grunt-contrib-mocha configuration file: mochaTest: feTest: options: clearRequireCache: true reporter: 'spec' src: ['test/fe/**/*.js'] beTest: options: clearRequireCache: true reporter: 'dots' src: ['test/be/**/*.js']
  • 28. Grunt watch ● watches for file changes ● runs tasks if one of the specified files have changed watch: scripts: files: ['test/unit/**/*.js', 'src/js/**/*.js'] tasks: ['jshint', 'mocha'] interrupt: true options: spawn: false jade: files: ['src/view/**/*.jade'] tasks: ['jade', ‘livereload:html’] interrupt: true options: spawn: false stylus: files: ['src/style/**/*.styl'] tasks: ['stylus', ‘livereload:css’] interrupt: false options: spawn: false