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

PPT
JavaScript Testing: Mocha + Chai
PDF
Unit tests in node.js
PDF
Painless JavaScript Testing with Jest
PDF
Testing JavaScript Applications
PDF
[React Native Tutorial] Lecture 3: More on ES6/ES2015
PDF
Running BabelJS on Windows (Try ES6 on Windows)
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
PPTX
ECMAScript 6 and the Node Driver
JavaScript Testing: Mocha + Chai
Unit tests in node.js
Painless JavaScript Testing with Jest
Testing JavaScript Applications
[React Native Tutorial] Lecture 3: More on ES6/ES2015
Running BabelJS on Windows (Try ES6 on Windows)
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
ECMAScript 6 and the Node Driver

What's hot (20)

KEY
Introduction to node.js
PDF
Introduction to asynchronous DB access using Node.js and MongoDB
PPTX
Run Node Run
PPT
Node js presentation
PDF
Introduction to Node.js: What, why and how?
PDF
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
PDF
Celery introduction
PDF
Performance and stability testing \w Gatling
PDF
ECMAScript 6
KEY
GPerf Using Jesque
PDF
Spock: Test Well and Prosper
PDF
Background processing with Resque
PPTX
Javascript asynchronous
PPTX
Node.js System: The Approach
PPTX
Node child process
PPTX
Debugging & profiling node.js
KEY
Node.js - Best practices
PPTX
Intro to Node.js (v1)
PDF
Celery: The Distributed Task Queue
Introduction to node.js
Introduction to asynchronous DB access using Node.js and MongoDB
Run Node Run
Node js presentation
Introduction to Node.js: What, why and how?
Matthew Eernisse, NodeJs, .toster {webdev}
Celery introduction
Performance and stability testing \w Gatling
ECMAScript 6
GPerf Using Jesque
Spock: Test Well and Prosper
Background processing with Resque
Javascript asynchronous
Node.js System: The Approach
Node child process
Debugging & profiling node.js
Node.js - Best practices
Intro to Node.js (v1)
Celery: The Distributed Task Queue
Ad

Viewers also liked (13)

PPTX
Testing Javascript Apps with Mocha and Chai
PPT
Testing Javascript with Jasmine
PDF
Testing with Express, Mocha & Chai
PPTX
Test automation introduction training at Polteq
PDF
Unit testing with mocha
PPTX
Unit Testing TypeScript
PPTX
Agile scrum roles
PDF
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
PDF
Appium: Prime Cuts
PPTX
DevOps Pipelines and Metrics Driven Feedback Loops
PDF
Alphorm.com Formation TypeScript
PPTX
Mudularity and Unit Testing in TypeScript (for ng-bkk #3)
PDF
Les Aventures d'Alice - la Révolte des Tests
Testing Javascript Apps with Mocha and Chai
Testing Javascript with Jasmine
Testing with Express, Mocha & Chai
Test automation introduction training at Polteq
Unit testing with mocha
Unit Testing TypeScript
Agile scrum roles
The What, Why and How of (Web) Analytics Testing (Web, IoT, Big Data)
Appium: Prime Cuts
DevOps Pipelines and Metrics Driven Feedback Loops
Alphorm.com Formation TypeScript
Mudularity and Unit Testing in TypeScript (for ng-bkk #3)
Les Aventures d'Alice - la Révolte des Tests
Ad

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

PDF
Quick tour to front end unit testing using jasmine
PDF
A Recovering Java Developer Learns to Go
PDF
Belvedere
PDF
TypeScript for Java Developers
PDF
Declarative Infrastructure Tools
PPTX
DevOpsDays InSpec Workshop
PDF
Bangpypers april-meetup-2012
PPTX
Make BDD great again
PDF
How to Reverse Engineer Web Applications
PDF
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
PPTX
BuildStuff.LT 2018 InSpec Workshop
PPTX
Unit testing presentation
PDF
Strategies for Puppet code upgrade and refactoring
PPTX
introduction to node.js
PPTX
InSpec Workshop at Velocity London 2018
PDF
Новый InterSystems: open-source, митапы, хакатоны
PPTX
InSpec For DevOpsDays Amsterdam 2017
PPTX
Java - A broad introduction
PPTX
Introduction to InSpec and 1.0 release update
PPTX
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Quick tour to front end unit testing using jasmine
A Recovering Java Developer Learns to Go
Belvedere
TypeScript for Java Developers
Declarative Infrastructure Tools
DevOpsDays InSpec Workshop
Bangpypers april-meetup-2012
Make BDD great again
How to Reverse Engineer Web Applications
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
BuildStuff.LT 2018 InSpec Workshop
Unit testing presentation
Strategies for Puppet code upgrade and refactoring
introduction to node.js
InSpec Workshop at Velocity London 2018
Новый InterSystems: open-source, митапы, хакатоны
InSpec For DevOpsDays Amsterdam 2017
Java - A broad introduction
Introduction to InSpec and 1.0 release update
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Spectroscopy.pptx food analysis technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
cuic standard and advanced reporting.pdf
A Presentation on Artificial Intelligence
Review of recent advances in non-invasive hemoglobin estimation
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Unlocking AI with Model Context Protocol (MCP)
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Advanced methodologies resolving dimensionality complications for autism neur...
Big Data Technologies - Introduction.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
MYSQL Presentation for SQL database connectivity
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx

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