SlideShare a Scribd company logo
1 of 13
JavaScript unit testing
with QUnit and Sinon
Lars Thorup
ZeaLake Software Consulting
June, 2013
Who is Lars Thorup?
● Software developer/architect
● JavaScript, C# and C++
● Test Driven Development
● Coaching teams in agile
engineering practices
● Assessing software projects
and companies
● Founder and CEO of
BestBrains and ZeaLake
Resources
● Tools
● http://qunitjs.com/
● http://sinonjs.org/
● Sample code
● https://github.com/larsthorup/jsdevenv-qunit
● Slides
● http://www.slideshare.net/larsthorup
● @larsthorup, lars@zealake.com
● What is unit testing about?
● Express expected behaviour of the code we write
● Why is unit testing a good thing?
● Faster development
● Find and fix bugs faster
● Prevent bugs from reappearing
● Improve the design of our software
● Reliable documentation
● How do we do unit testing?
● Write test code
● Run the tests automatically
Why are we here today?
QUnit - tests and fixtures
module('module name', {
setup: function () {
this.account = new Account(4711);
}
});
test('test name, function () {
equal(this.account.id, 4711);
});
test('...', function () {
...
});
QUnit - assertions
ok(account.isValid, 'isValid'); // !
equal(account.id, 4711, 'id'); // ==
notEqual(account.state, CLOSED, 'state'); // !=
strictEqual(account.user, user, 'user'); // ===
deepEqual(account.privs, [1, 2], 'privs');
throws(function () {
account.close()
}, /failed/, 'close');
Sinon - spies, stubs and mocks
Math.randomBelow = function (n) {
return Math.floor(Math.random() * n);
};
module('util.random', {
setup: function () {
sinon.stub(Math, 'random').returns(0.85);
},
teardown: function () {
Math.random.restore();
}
});
test('randomBelow', function () {
equal(Math.randomBelow(6), 5, '6');
});
DOM
module('Control.Button', {
setup: function () {
$('<button id="next"></button>')
.appendTo('#qunit-fixture');
this.button = new Control.Button('#next', {
text: 'Next'
});
}
});
test('constructor', function () {
equal($('#next').attr('text'), 'Next', '.text');
});
● #qunit-fixture is emptied before each test
Asynchronous code
test('delayHide', function () {
expect(2);
stop();
this.button.delayHide(function () {
equal($('#next').is(':visible'), false, '!visible');
start();
});
equal($('#next').is(':visible'), true, 'visible');
});
Button.prototype.delayHide = function (callback) {
var self = this;
setTimeout(function () {
self.element.hide();
callback();
}, 100);
};
Workflow of Test Driven Development
Failing
test
Succeeding
test
Good
design Refactor
Code
Write a
test
Idea
Think, talk
Continuous Integration with Jenkins
Unit testing philosophy
● Behaviour first
● makes more sense than "Test first"
● Structure of test programs
● Given <precondition>
● When <invocation>
● Then <expectation>
● High level as well as low level
● Test user stories and requirements
● Test class design and algorithms
● Communicate intent
● Fast feedback
Advanced mocking
● Constructors
● Time: new Date()
● Timers: setTimeout(), setInterval()
● Ajax
● Events
● DOM
● CSS transitions
● Sinon sessions

More Related Content

Similar to Javascript unit testing with QUnit and Sinon

Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
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
Ran Mizrahi
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
Miguel González-Fierro
 
Google: Drive, Documents and Apps Script - How to work efficiently and happily
Google:  Drive, Documents  and Apps Script - How to work efficiently and happilyGoogle:  Drive, Documents  and Apps Script - How to work efficiently and happily
Google: Drive, Documents and Apps Script - How to work efficiently and happily
Alessandra Santi
 

Similar to Javascript unit testing with QUnit and Sinon (20)

Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance Testing
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement BardejovTesting in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
 
Advanced Javascript Unit Testing
Advanced Javascript Unit TestingAdvanced Javascript Unit Testing
Advanced Javascript Unit Testing
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
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
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Google: Drive, Documents and Apps Script - How to work efficiently and happily
Google:  Drive, Documents  and Apps Script - How to work efficiently and happilyGoogle:  Drive, Documents  and Apps Script - How to work efficiently and happily
Google: Drive, Documents and Apps Script - How to work efficiently and happily
 

More from Lars Thorup

More from Lars Thorup (16)

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to choose
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-tests
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-level
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit TestingAdvanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema Evolution
 
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
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
 
Agile Contracts
Agile ContractsAgile Contracts
Agile Contracts
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering Teams
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant Carpaccio
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
 
Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
 

Recently uploaded

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Javascript unit testing with QUnit and Sinon

  • 1. JavaScript unit testing with QUnit and Sinon Lars Thorup ZeaLake Software Consulting June, 2013
  • 2. Who is Lars Thorup? ● Software developer/architect ● JavaScript, C# and C++ ● Test Driven Development ● Coaching teams in agile engineering practices ● Assessing software projects and companies ● Founder and CEO of BestBrains and ZeaLake
  • 3. Resources ● Tools ● http://qunitjs.com/ ● http://sinonjs.org/ ● Sample code ● https://github.com/larsthorup/jsdevenv-qunit ● Slides ● http://www.slideshare.net/larsthorup ● @larsthorup, lars@zealake.com
  • 4. ● What is unit testing about? ● Express expected behaviour of the code we write ● Why is unit testing a good thing? ● Faster development ● Find and fix bugs faster ● Prevent bugs from reappearing ● Improve the design of our software ● Reliable documentation ● How do we do unit testing? ● Write test code ● Run the tests automatically Why are we here today?
  • 5. QUnit - tests and fixtures module('module name', { setup: function () { this.account = new Account(4711); } }); test('test name, function () { equal(this.account.id, 4711); }); test('...', function () { ... });
  • 6. QUnit - assertions ok(account.isValid, 'isValid'); // ! equal(account.id, 4711, 'id'); // == notEqual(account.state, CLOSED, 'state'); // != strictEqual(account.user, user, 'user'); // === deepEqual(account.privs, [1, 2], 'privs'); throws(function () { account.close() }, /failed/, 'close');
  • 7. Sinon - spies, stubs and mocks Math.randomBelow = function (n) { return Math.floor(Math.random() * n); }; module('util.random', { setup: function () { sinon.stub(Math, 'random').returns(0.85); }, teardown: function () { Math.random.restore(); } }); test('randomBelow', function () { equal(Math.randomBelow(6), 5, '6'); });
  • 8. DOM module('Control.Button', { setup: function () { $('<button id="next"></button>') .appendTo('#qunit-fixture'); this.button = new Control.Button('#next', { text: 'Next' }); } }); test('constructor', function () { equal($('#next').attr('text'), 'Next', '.text'); }); ● #qunit-fixture is emptied before each test
  • 9. Asynchronous code test('delayHide', function () { expect(2); stop(); this.button.delayHide(function () { equal($('#next').is(':visible'), false, '!visible'); start(); }); equal($('#next').is(':visible'), true, 'visible'); }); Button.prototype.delayHide = function (callback) { var self = this; setTimeout(function () { self.element.hide(); callback(); }, 100); };
  • 10. Workflow of Test Driven Development Failing test Succeeding test Good design Refactor Code Write a test Idea Think, talk
  • 12. Unit testing philosophy ● Behaviour first ● makes more sense than "Test first" ● Structure of test programs ● Given <precondition> ● When <invocation> ● Then <expectation> ● High level as well as low level ● Test user stories and requirements ● Test class design and algorithms ● Communicate intent ● Fast feedback
  • 13. Advanced mocking ● Constructors ● Time: new Date() ● Timers: setTimeout(), setInterval() ● Ajax ● Events ● DOM ● CSS transitions ● Sinon sessions