SlideShare une entreprise Scribd logo
1  sur  17
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

Contenu connexe

Tendances

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
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 MongoDBAdrien Joly
 
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
 
Performance and stability testing \w Gatling
Performance and stability testing \w GatlingPerformance and stability testing \w Gatling
Performance and stability testing \w GatlingDmitry Vrublevsky
 
GPerf Using Jesque
GPerf Using JesqueGPerf Using Jesque
GPerf Using Jesquectoestreich
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Background processing with Resque
Background processing with ResqueBackground processing with Resque
Background processing with ResqueNicolas Blanco
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronouskang taehun
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Node child process
Node child processNode child process
Node child processLearningTech
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.jstomasperezv
 
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 QueueRichard Leland
 

Tendances (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
 

En vedette

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 ChaiAndrew Winder
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & ChaiJoerg Henning
 
Test automation introduction training at Polteq
Test automation   introduction training at PolteqTest automation   introduction training at Polteq
Test automation introduction training at PolteqMartijn de Vrieze
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mochaRevath S Kumar
 
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 CutsSauce 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 LoopsAndreas Grabner
 
Alphorm.com Formation TypeScript
Alphorm.com Formation TypeScriptAlphorm.com Formation TypeScript
Alphorm.com Formation TypeScriptAlphorm
 
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 TestsLy-Jia Goldstein
 

En vedette (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
 

Similaire à 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 jasmineGil 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 GoMatt Stine
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov 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 WorkshopMandi Walls
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Deepak Garg
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great againYana Gusti
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsJarrod 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 WorkshopMandi Walls
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentationArthur 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 refactoringAlessandro Franceschi
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
InSpec Workshop at Velocity London 2018
InSpec Workshop at Velocity London 2018InSpec Workshop at Velocity London 2018
InSpec Workshop at Velocity London 2018Mandi 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 2017Mandi Walls
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol 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 updateAlex 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 GriffinSencha
 

Similaire à 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
 

Dernier

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 TerraformAndrey Devyatkin
 
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 AutomationSafe Software
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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 Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
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 DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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...Drew Madelung
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

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
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 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