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

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

What's hot (20)

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDB
 
Run Node Run
Run Node RunRun Node Run
Run Node Run
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Node ppt
Node pptNode ppt
Node ppt
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Celery introduction
Celery introductionCelery introduction
Celery introduction
 
Performance and stability testing \w Gatling
Performance and stability testing \w GatlingPerformance and stability testing \w Gatling
Performance and stability testing \w Gatling
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
GPerf Using Jesque
GPerf Using JesqueGPerf Using Jesque
GPerf Using Jesque
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Background processing with Resque
Background processing with ResqueBackground processing with Resque
Background processing with Resque
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronous
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Node child process
Node child processNode child process
Node child process
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.js
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task Queue
 

Viewers also liked

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

Viewers also liked (13)

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

Similar to Testing NodeJS with Mocha, Should, Sinon, and JSCoverage

Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
Gil Fink
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
Matt Stine
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
 
Declarative Infrastructure Tools
Declarative Infrastructure Tools Declarative Infrastructure Tools
Declarative Infrastructure Tools
Yulia Shcherbachova
 
DevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopDevOpsDays InSpec Workshop
DevOpsDays InSpec Workshop
Mandi Walls
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
Deepak Garg
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
Yana Gusti
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
Jarrod Overson
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
Yevgeniy Brikman
 
BuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec WorkshopBuildStuff.LT 2018 InSpec Workshop
BuildStuff.LT 2018 InSpec Workshop
Mandi Walls
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
Arthur Freyman
 
Strategies for Puppet code upgrade and refactoring
Strategies for Puppet code upgrade and refactoringStrategies for Puppet code upgrade and refactoring
Strategies for Puppet code upgrade and refactoring
Alessandro Franceschi
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
InSpec Workshop at Velocity London 2018
InSpec Workshop at Velocity London 2018InSpec Workshop at Velocity London 2018
InSpec Workshop at Velocity London 2018
Mandi Walls
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоны
Timur Safin
 
InSpec For DevOpsDays Amsterdam 2017
InSpec For DevOpsDays Amsterdam 2017InSpec For DevOpsDays Amsterdam 2017
InSpec For DevOpsDays Amsterdam 2017
Mandi Walls
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
Birol Efe
 
Introduction to InSpec and 1.0 release update
Introduction to InSpec and 1.0 release updateIntroduction to InSpec and 1.0 release update
Introduction to InSpec and 1.0 release update
Alex Pop
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Sencha
 

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

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

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 

Testing NodeJS with Mocha, Should, Sinon, and JSCoverage

  • 1. 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
  • 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