SlideShare a Scribd company logo
Testing NodeJS
(with Mocha, Should, Sinon, & JSCoverage)
Michael Lilley
michael.lilley@gmail.com
Melbourne NodeJS Meetup Group
Wednesday, 28 August 2013
Accompanying Sample Repository - https://github.com/mlilley/testing_nodejs_with_mocha.git
Which Framework?
• Popular
• Decent high level features
• Highly configurable to suit many tastes
• Been around for almost 2 years
• Can run in the browser also
Why Mocha?
Setting Up
1. Install mocha module
$ npm install mocha
2. Choose and install your assertion library (we’ll use should)
$ npm install should
3. Create a directory for your tests
$ mkdir test
Setting Up
REPORTER = dot
test:
@NODE_ENV=test ./node_modules/.bin/mocha
--reporter $(REPORTER) 
test-w:
@NODE_ENV=test ./node_modules/.bin/mocha 
--reporter $(REPORTER) 
--watch
.PHONY: test test-w
4. Create your Makefile
Remember the tabs!
Setting Up
{
...
"scripts": {
"test": "make test"
}
...
}
5. Configure package.json
Code To Be Tested
var Adder = exports.Adder = function() {};
Adder.prototype.add = function(a, b) {
return a + b;
};
sync_adder.js
var Adder = exports.Adder = function() {};
Adder.prototype.add = function(a, b, callback) {
setTimeout(function() {
callback(a + b);
}, 100);
};
async_adder.js
Tests - Synchronous
var should = require('should');
var Adder = require('../sync_adder').Adder;
describe('Synchronous Adder', function() {
describe('add()', function() {
it('should return 3 when adding 1 and 2', function() {
var adder = new Adder();
adder.add(1, 2).should.equal(3);
});
});
});
test/sync_adder.js
• NB: or use mocha option ‘--require’ to automatically require common deps (ie: Should)
Tests - Asynchronous
test/async_adder.js
• If done() not called, test fails • Default timeout is 2,000 ms
• Adjust with this.timeout(x)
var should = require('should');
var Adder = require('../async_adder').Adder;
describe('Asynchronous Adder', function() {
describe('add()', function() {
it('should callback with 3 when adding 1 and 2', function(done) {
var adder = new Adder();
adder.add(1, 2, function(result) {
result.should.equal(3);
done();
});
});
});
});
Hooks
• before(fn), after(fn), beforeEach(fn), afterEach(fn)
• Use within describe() at any nesting level
• Use outside describe() for global scope
• after/afterEach run on test fail too (unless --bail)
Should DSL
x.should.be.ok
x.should.be.true
x.should.be.false
x.should.be.empty
x.should.be.within(y,z)
x.should.be.a(y)
x.should.be[.an].instanceOf(y)
x.should.be.above(n)
x.should.be.below(n)
x.should.eql(y)
x.should.equal(y)
x.should.match(/y/)
x.should.have.length(y)
x.should.have.property(prop[, val])
x.should.have.ownProperty(prop[, val])
x.should.have.status(code)
x.should.have.header(field[, val])
x.should.include(y)
x.should.throw([string|/regexp/])
// truthiness
// === true
// === false
// length == 0
// range
// typeof
// instanceOf
// > val
// < val
// ==
// ===
// regexp match
// .length == y
// prop exists
// prop exists (immediate)
// .statusCode == y
// .header with field & val
// x.indexOf(y) != -1
// thrown exception
Negation:
• x.should.not.be.ok
Chaining:
• x.should.be.a(‘string’).and.have.length(5)
Implementation:
• should added to Object as property
• Therefore x must not be null or undefined
• Use should.exist(x) to test first where
needed.
Running Tests
• Run your tests
$ make test
or $ npm test
or $ ./node_modules/.bin/mocha <options> <path|files>
• Run your tests automatically when files change
$ make test-w
• Run multiple test suites / partial suite / specific tests
– Specify desired file or directory on cmd line
– Use “tagging” and --grep feature
• Tag test names with some unique string (ie “@slow” or “#API” or “APP”)
• Pass cmd line option --grep <pattern>
• Run Mocha programatically for more control
Mocha Configurability
• Change assertion library (require(…))
– Should, expect.js, Chai, Expectations, better-assert, Node’s assert lib, etc
• Change interface (--ui flag)
– for BDD style: describe, it, before, after, beforeEach, afterEach.
– for TDD style: suite, test, setup, teardown.
– others
• Change output Reporter (--reporter flag)
– For different styles of terminal output
– For output of docs (html, xml, documentation, …)
– For feeding into other programs (test coverage, …)
• … and more …
Sinon
• Sinon
– APIs for spies, stubs, mocks, and utils
– Framework agnostic
– To use:
• $ npm install sinon
• var sinon = require(‘sinon’);
– Don’t include via --require because need access to exports
Test Coverage
1. Install node-jscoverage binary
$ git clone https://github.com/visionmedia/node-jscoverage.git
$ ./configure && make && make install
2. Adjust Makefile to:
– invoke jscoverage on source to produce instrumented version
– run mocha on instrumented source with html-cov reporter to ourput coverage report.
...
test-cov: lib-cov
@MYPROJ_COVERAGE=1 $(MAKE) test REPORTER=html-cov > coverage.html
lib-cov:
@jscoverage lib lib-cov
...
Test Coverage
3. Adjust project structure (see example repo)
– index.js conditionally requires normal or instrumented source based on env var set in
makefile
module.exports = process.env.MYPROJ_COVERAGE
? require('./lib-cov/myproj')
: require('./lib/myproj')
4. Run it
$ make test-cov
For more…
• Mocha - http://visionmedia.github.io/mocha/
• Mocha Wiki - https://github.com/visionmedia/mocha/wiki
• Should - https://github.com/visionmedia/should.js/
• Sinon - http://sinonjs.org/
• Node-JSCoverage - https://github.com/visionmedia/node-jscoverage

More Related Content

What's hot (20)

KEY
Introduction to node.js
jacekbecela
 
PDF
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
PPTX
Run Node Run
Kevin Swiber
 
PPT
Node js presentation
martincabrera
 
PDF
Introduction to Node.js: What, why and how?
Christian Joudrey
 
PDF
Node ppt
Tamil Selvan R S
 
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
PDF
Celery introduction
Ionel Mărieș Cristian
 
PDF
Performance and stability testing \w Gatling
Dmitry Vrublevsky
 
PDF
ECMAScript 6
偉格 高
 
KEY
GPerf Using Jesque
ctoestreich
 
PDF
Spock: Test Well and Prosper
Ken Kousen
 
PDF
Background processing with Resque
Nicolas Blanco
 
PPTX
Javascript asynchronous
kang taehun
 
PPTX
Node.js System: The Approach
Haci Murat Yaman
 
PPTX
Node child process
LearningTech
 
PPTX
Debugging & profiling node.js
tomasperezv
 
KEY
Node.js - Best practices
Felix Geisendörfer
 
PPTX
Intro to Node.js (v1)
Chris Cowan
 
PDF
Celery: The Distributed Task Queue
Richard Leland
 
Introduction to node.js
jacekbecela
 
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
Run Node Run
Kevin Swiber
 
Node js presentation
martincabrera
 
Introduction to Node.js: What, why and how?
Christian Joudrey
 
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Celery introduction
Ionel Mărieș Cristian
 
Performance and stability testing \w Gatling
Dmitry Vrublevsky
 
ECMAScript 6
偉格 高
 
GPerf Using Jesque
ctoestreich
 
Spock: Test Well and Prosper
Ken Kousen
 
Background processing with Resque
Nicolas Blanco
 
Javascript asynchronous
kang taehun
 
Node.js System: The Approach
Haci Murat Yaman
 
Node child process
LearningTech
 
Debugging & profiling node.js
tomasperezv
 
Node.js - Best practices
Felix Geisendörfer
 
Intro to Node.js (v1)
Chris Cowan
 
Celery: The Distributed Task Queue
Richard Leland
 

Viewers also liked (13)

PPTX
Testing Javascript Apps with Mocha and Chai
Andrew Winder
 
PPT
Testing Javascript with Jasmine
Tim Tyrrell
 
PDF
Testing with Express, Mocha & Chai
Joerg Henning
 
PPTX
Test automation introduction training at Polteq
Martijn de Vrieze
 
PDF
Unit testing with mocha
Revath S Kumar
 
PPTX
Unit Testing TypeScript
Daniel Jimenez Garcia
 
PPTX
Agile scrum roles
David Tzemach
 
PDF
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
Anand Bagmar
 
PDF
Appium: Prime Cuts
Sauce Labs
 
PPTX
DevOps Pipelines and Metrics Driven Feedback Loops
Andreas Grabner
 
PDF
Alphorm.com Formation TypeScript
Alphorm
 
PPTX
Mudularity and Unit Testing in TypeScript (for ng-bkk #3)
Suthep Sangvirotjanaphat
 
PDF
Les Aventures d'Alice - la Révolte des Tests
Ly-Jia Goldstein
 
Testing Javascript Apps with Mocha and Chai
Andrew Winder
 
Testing Javascript with Jasmine
Tim Tyrrell
 
Testing with Express, Mocha & Chai
Joerg Henning
 
Test automation introduction training at Polteq
Martijn de Vrieze
 
Unit testing with mocha
Revath S Kumar
 
Unit Testing TypeScript
Daniel Jimenez Garcia
 
Agile scrum roles
David Tzemach
 
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
Anand Bagmar
 
Appium: Prime Cuts
Sauce Labs
 
DevOps Pipelines and Metrics Driven Feedback Loops
Andreas Grabner
 
Alphorm.com Formation TypeScript
Alphorm
 
Mudularity and Unit Testing in TypeScript (for ng-bkk #3)
Suthep Sangvirotjanaphat
 
Les Aventures d'Alice - la Révolte des Tests
Ly-Jia Goldstein
 
Ad

Similar to Testing NodeJS with Mocha, Should, Sinon, and JSCoverage (20)

PPT
Test innode
Davide Fiorello
 
PDF
Test driven node.js
Jay Harris
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PDF
Developers Testing - Girl Code at bloomon
Ineke Scheffers
 
PPTX
unit test in node js - test cases in node
Goa App
 
PDF
Unit Testing - The Whys, Whens and Hows
atesgoral
 
PPTX
Qunit Java script Un
akanksha arora
 
PDF
Unit Testing JavaScript Applications
Ynon Perek
 
PDF
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
PPTX
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
PPTX
Full Stack Unit Testing
GlobalLogic Ukraine
 
PDF
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
PPTX
Testing nodejs apps
felipefsilva
 
PDF
mocha sinon chai Dc jquery 4-24
Carson Banov
 
PDF
An Introduction to the World of Testing for Front-End Developers
FITC
 
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
PDF
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
PDF
Testing with Node.js
Jonathan Waller
 
PDF
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
Test innode
Davide Fiorello
 
Test driven node.js
Jay Harris
 
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Developers Testing - Girl Code at bloomon
Ineke Scheffers
 
unit test in node js - test cases in node
Goa App
 
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Qunit Java script Un
akanksha arora
 
Unit Testing JavaScript Applications
Ynon Perek
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
Full Stack Unit Testing
GlobalLogic Ukraine
 
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
Testing nodejs apps
felipefsilva
 
mocha sinon chai Dc jquery 4-24
Carson Banov
 
An Introduction to the World of Testing for Front-End Developers
FITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
Testing with Node.js
Jonathan Waller
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
Ad

Recently uploaded (20)

PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 

Testing NodeJS with Mocha, Should, Sinon, and JSCoverage

  • 1. Testing NodeJS (with Mocha, Should, Sinon, & JSCoverage) Michael Lilley [email protected] Melbourne NodeJS Meetup Group Wednesday, 28 August 2013 Accompanying Sample Repository - https://github.com/mlilley/testing_nodejs_with_mocha.git
  • 3. • Popular • Decent high level features • Highly configurable to suit many tastes • Been around for almost 2 years • Can run in the browser also Why Mocha?
  • 4. Setting Up 1. Install mocha module $ npm install mocha 2. Choose and install your assertion library (we’ll use should) $ npm install should 3. Create a directory for your tests $ mkdir test
  • 5. Setting Up REPORTER = dot test: @NODE_ENV=test ./node_modules/.bin/mocha --reporter $(REPORTER) test-w: @NODE_ENV=test ./node_modules/.bin/mocha --reporter $(REPORTER) --watch .PHONY: test test-w 4. Create your Makefile Remember the tabs!
  • 6. Setting Up { ... "scripts": { "test": "make test" } ... } 5. Configure package.json
  • 7. Code To Be Tested var Adder = exports.Adder = function() {}; Adder.prototype.add = function(a, b) { return a + b; }; sync_adder.js var Adder = exports.Adder = function() {}; Adder.prototype.add = function(a, b, callback) { setTimeout(function() { callback(a + b); }, 100); }; async_adder.js
  • 8. Tests - Synchronous var should = require('should'); var Adder = require('../sync_adder').Adder; describe('Synchronous Adder', function() { describe('add()', function() { it('should return 3 when adding 1 and 2', function() { var adder = new Adder(); adder.add(1, 2).should.equal(3); }); }); }); test/sync_adder.js • NB: or use mocha option ‘--require’ to automatically require common deps (ie: Should)
  • 9. Tests - Asynchronous test/async_adder.js • If done() not called, test fails • Default timeout is 2,000 ms • Adjust with this.timeout(x) var should = require('should'); var Adder = require('../async_adder').Adder; describe('Asynchronous Adder', function() { describe('add()', function() { it('should callback with 3 when adding 1 and 2', function(done) { var adder = new Adder(); adder.add(1, 2, function(result) { result.should.equal(3); done(); }); }); }); });
  • 10. Hooks • before(fn), after(fn), beforeEach(fn), afterEach(fn) • Use within describe() at any nesting level • Use outside describe() for global scope • after/afterEach run on test fail too (unless --bail)
  • 11. Should DSL x.should.be.ok x.should.be.true x.should.be.false x.should.be.empty x.should.be.within(y,z) x.should.be.a(y) x.should.be[.an].instanceOf(y) x.should.be.above(n) x.should.be.below(n) x.should.eql(y) x.should.equal(y) x.should.match(/y/) x.should.have.length(y) x.should.have.property(prop[, val]) x.should.have.ownProperty(prop[, val]) x.should.have.status(code) x.should.have.header(field[, val]) x.should.include(y) x.should.throw([string|/regexp/]) // truthiness // === true // === false // length == 0 // range // typeof // instanceOf // > val // < val // == // === // regexp match // .length == y // prop exists // prop exists (immediate) // .statusCode == y // .header with field & val // x.indexOf(y) != -1 // thrown exception Negation: • x.should.not.be.ok Chaining: • x.should.be.a(‘string’).and.have.length(5) Implementation: • should added to Object as property • Therefore x must not be null or undefined • Use should.exist(x) to test first where needed.
  • 12. Running Tests • Run your tests $ make test or $ npm test or $ ./node_modules/.bin/mocha <options> <path|files> • Run your tests automatically when files change $ make test-w • Run multiple test suites / partial suite / specific tests – Specify desired file or directory on cmd line – Use “tagging” and --grep feature • Tag test names with some unique string (ie “@slow” or “#API” or “APP”) • Pass cmd line option --grep <pattern> • Run Mocha programatically for more control
  • 13. Mocha Configurability • Change assertion library (require(…)) – Should, expect.js, Chai, Expectations, better-assert, Node’s assert lib, etc • Change interface (--ui flag) – for BDD style: describe, it, before, after, beforeEach, afterEach. – for TDD style: suite, test, setup, teardown. – others • Change output Reporter (--reporter flag) – For different styles of terminal output – For output of docs (html, xml, documentation, …) – For feeding into other programs (test coverage, …) • … and more …
  • 14. Sinon • Sinon – APIs for spies, stubs, mocks, and utils – Framework agnostic – To use: • $ npm install sinon • var sinon = require(‘sinon’); – Don’t include via --require because need access to exports
  • 15. Test Coverage 1. Install node-jscoverage binary $ git clone https://github.com/visionmedia/node-jscoverage.git $ ./configure && make && make install 2. Adjust Makefile to: – invoke jscoverage on source to produce instrumented version – run mocha on instrumented source with html-cov reporter to ourput coverage report. ... test-cov: lib-cov @MYPROJ_COVERAGE=1 $(MAKE) test REPORTER=html-cov > coverage.html lib-cov: @jscoverage lib lib-cov ...
  • 16. Test Coverage 3. Adjust project structure (see example repo) – index.js conditionally requires normal or instrumented source based on env var set in makefile module.exports = process.env.MYPROJ_COVERAGE ? require('./lib-cov/myproj') : require('./lib/myproj') 4. Run it $ make test-cov
  • 17. For more… • Mocha - http://visionmedia.github.io/mocha/ • Mocha Wiki - https://github.com/visionmedia/mocha/wiki • Should - https://github.com/visionmedia/should.js/ • Sinon - http://sinonjs.org/ • Node-JSCoverage - https://github.com/visionmedia/node-jscoverage