SlideShare a Scribd company logo
6
Most read
11
Most read
12
Most read
Node.js Unit Tests
Nilkanth Shet Shirodkar
Software Engineer
Why test?
● Tests Reduce Bugs
● Tests are good documentation
● Tests allow safe refactoring
● Tests reduce the cost of change
● Testing forces you to think
● Tests gives confidence
● Tests reduce fear!
Unit Tests
● Isolate each part of the
program
● Show that the individual
parts are correct
Integration Tests
● Test the inter-operation
of multiple subsystems
● Test that “the nuts fit
the bolts”
What is NodeJS Unit Testing?
NodeJS unit testing refers to testing individual units or
components of a Node.js application using specialized
automation testing frameworks and libraries.
Popular NodeJS unit testing frameworks include Jest, Mocha,
and Chai.
chai vs jest vs mocha
Jest, Mocha and Chai have gained significant popularity
based on usage and monthly downloads, according to Github
and npmtrends,
https://npmtrends.com/chai-vs-jest-vs-mocha
Jest unit test
setup config run
Jest.js
setup config run
npm init -y
npm I –save-dev jest
Package.json
"scripts": {
"test": "jest"
}
"scripts": {
"test": "jest --coverage"
}
npm test
Jest.js - assertions
● expect( <this> ).toBe.<assertion>(that)
● Throws an Error if the assertion is false!
Examples:
● expect(sum(1, 2)).toBe(3)
● expect(subtract(1, 2)).toBe(-1)
● expect(cloneArray(array)).not.toBe(array)
● expect(cloneArray(array)).toEqual(array) // deep equality
Exercise: Write some tests
● Create a new node module (mkdir unit-test && npm init -y)
● Install devDeps (npm i --save-dev jest)
● Configure an “npm test” command
● Test these cases:
○ Sum Number -> returns a + b
○ Subtract Number -> returns a - b
○ Clone Array -> returns […array]
function isEven(n) { let
e = n % 2
if (Number.isNaN(e)) throw Error('Not a number!')
return !e
}
Gist
unit test in node js - test cases in node
Unit tests should come FIRST!
● Fast - 1K+ per second
● Isolated - Perform no I/O
● Repeatable - Run in any order, without intervention
● Self-validating - No external tool to evaluate results
● Timely - written before code
Source: http://agileinaflash.blogspot.co.il/2009/02/first.html
Tools of the trade
● Test Runner -> mocha.js
● Assertion Framework -> chai.js
● Stubbing/Mocking tools -> sinon.js
Testing Async Behavior
● Invoke the callback when your test is complete.
● By adding a callback (usually named done) to it(), Mocha will know that
it should wait for this function to be called to complete the test.
describe('Async behavior', function() {
before(function(done) {
somethingAsync(done)
})
it('should do ok', () => {})
})
Exercise: Test different calls to ipify.org
● ipify.org - has 3 formats, regular, json and jsonp
● Write a unit test which tests each type
● I use “axios” = request library with promises
const request = require('axios')
function getMyIP(fmt) {
fmt = typeof fmt == 'undefined' ? 'json' : fmt;
return request.get(`https://api.ipify.org?format=${fmt}`)
}
gist
Why are these tests bad?
● They test someone else’s code
● They make I/O!
Sinon.js - stubbing, mocking, spying
● sinon.stub(obj, ‘method’).returns(1)
What this does:
● Replaces obj.method() with function() { return 1 }
● Obj.method becomes a spy (gets special methods for
inspection)
● Gets a .reset() method which rolls counters back
● Gets a .restore() method which restores everything back
http://sinonjs.org/
Exercise: test our getMyIP’s different cases
● Stub axios.get
● Don’t forget to restore
● Test 3 cases:
○ No Input
○ JSON
○ JSONP
● Goals:
○ Test that Axios is called correctly
○ Don’t break the function’s signature
Bonus: pick your poison
● Testing Webservers
● Coverage reports with istanbul
● Syntactic sugar with sinon-as-promised, sinon-chai
● Integrating unit tests into CI/CD
Thank you
@_rtam

More Related Content

Similar to unit test in node js - test cases in node (20)

PDF
An Introduction to the World of Testing for Front-End Developers
FITC
 
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
PPTX
Zero to Testing in JavaScript
pamselle
 
PPTX
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
mlilley
 
PDF
The Many Ways to Test Your React App
All Things Open
 
PDF
Front-End Testing: Demystified
Seth McLaughlin
 
PPTX
Full Stack Unit Testing
GlobalLogic Ukraine
 
PPTX
Qunit Java script Un
akanksha arora
 
PPTX
Testing nodejs apps
felipefsilva
 
PPTX
How to write test in node.js
Jason Lin
 
PPT
Test innode
Davide Fiorello
 
PDF
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
PDF
Js fwdays unit tesing javascript(by Anna Khabibullina)
Anna Khabibullina
 
PPTX
JS Frameworks Day April,26 of 2014
DA-14
 
PDF
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
PDF
Testing most things in JavaScript - LeedsJS 31/05/2017
Colin Oakley
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PDF
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
PPT
JavaScript Testing: Mocha + Chai
James Cryer
 
PDF
JavaScript Unit Testing
Mihail Gaberov
 
An Introduction to the World of Testing for Front-End Developers
FITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
Zero to Testing in JavaScript
pamselle
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
mlilley
 
The Many Ways to Test Your React App
All Things Open
 
Front-End Testing: Demystified
Seth McLaughlin
 
Full Stack Unit Testing
GlobalLogic Ukraine
 
Qunit Java script Un
akanksha arora
 
Testing nodejs apps
felipefsilva
 
How to write test in node.js
Jason Lin
 
Test innode
Davide Fiorello
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Anna Khabibullina
 
JS Frameworks Day April,26 of 2014
DA-14
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Colin Oakley
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
JavaScript Testing: Mocha + Chai
James Cryer
 
JavaScript Unit Testing
Mihail Gaberov
 

More from Goa App (20)

PPTX
web development in 2024 - website development
Goa App
 
PPTX
web development full stack
Goa App
 
PPTX
Angular interview questions
Goa App
 
PDF
Spectrofluorimetry (www.redicals.com)
Goa App
 
PDF
UV rays
Goa App
 
PPTX
UV ray spectrophotometer
Goa App
 
PPTX
Spectrofluorimetry or fluorimetry (www.Redicals.com)
Goa App
 
PPTX
Atomic Absorption Spectroscopy (www.Redicals.com)
Goa App
 
DOCX
Hidden Markov Model Toolkit (HTK) www.redicals.com
Goa App
 
PPT
Cash Budget
Goa App
 
PPTX
Speech Recognition
Goa App
 
PPTX
Social Network Analysis Using Gephi
Goa App
 
PPTX
Binomial Heap
Goa App
 
PPT
Blu ray
Goa App
 
PPTX
Memory cards
Goa App
 
PPTX
Magnetic memory
Goa App
 
PPTX
E governance
Goa App
 
PPTX
Mobile phones
Goa App
 
PPTX
Enterprise resource planning in manufacturing
Goa App
 
PPT
Enterprise application integration
Goa App
 
web development in 2024 - website development
Goa App
 
web development full stack
Goa App
 
Angular interview questions
Goa App
 
Spectrofluorimetry (www.redicals.com)
Goa App
 
UV rays
Goa App
 
UV ray spectrophotometer
Goa App
 
Spectrofluorimetry or fluorimetry (www.Redicals.com)
Goa App
 
Atomic Absorption Spectroscopy (www.Redicals.com)
Goa App
 
Hidden Markov Model Toolkit (HTK) www.redicals.com
Goa App
 
Cash Budget
Goa App
 
Speech Recognition
Goa App
 
Social Network Analysis Using Gephi
Goa App
 
Binomial Heap
Goa App
 
Blu ray
Goa App
 
Memory cards
Goa App
 
Magnetic memory
Goa App
 
E governance
Goa App
 
Mobile phones
Goa App
 
Enterprise resource planning in manufacturing
Goa App
 
Enterprise application integration
Goa App
 
Ad

Recently uploaded (20)

PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
PPTX
Distribution reservoir and service storage pptx
dhanashree78
 
PPTX
Biosensors, BioDevices, Biomediccal.pptx
AsimovRiyaz
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
Distribution reservoir and service storage pptx
dhanashree78
 
Biosensors, BioDevices, Biomediccal.pptx
AsimovRiyaz
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Ad

unit test in node js - test cases in node

  • 1. Node.js Unit Tests Nilkanth Shet Shirodkar Software Engineer
  • 2. Why test? ● Tests Reduce Bugs ● Tests are good documentation ● Tests allow safe refactoring ● Tests reduce the cost of change ● Testing forces you to think ● Tests gives confidence ● Tests reduce fear!
  • 3. Unit Tests ● Isolate each part of the program ● Show that the individual parts are correct Integration Tests ● Test the inter-operation of multiple subsystems ● Test that “the nuts fit the bolts”
  • 4. What is NodeJS Unit Testing? NodeJS unit testing refers to testing individual units or components of a Node.js application using specialized automation testing frameworks and libraries. Popular NodeJS unit testing frameworks include Jest, Mocha, and Chai.
  • 5. chai vs jest vs mocha Jest, Mocha and Chai have gained significant popularity based on usage and monthly downloads, according to Github and npmtrends, https://npmtrends.com/chai-vs-jest-vs-mocha
  • 6. Jest unit test setup config run
  • 7. Jest.js setup config run npm init -y npm I –save-dev jest Package.json "scripts": { "test": "jest" } "scripts": { "test": "jest --coverage" } npm test
  • 8. Jest.js - assertions ● expect( <this> ).toBe.<assertion>(that) ● Throws an Error if the assertion is false! Examples: ● expect(sum(1, 2)).toBe(3) ● expect(subtract(1, 2)).toBe(-1) ● expect(cloneArray(array)).not.toBe(array) ● expect(cloneArray(array)).toEqual(array) // deep equality
  • 9. Exercise: Write some tests ● Create a new node module (mkdir unit-test && npm init -y) ● Install devDeps (npm i --save-dev jest) ● Configure an “npm test” command ● Test these cases: ○ Sum Number -> returns a + b ○ Subtract Number -> returns a - b ○ Clone Array -> returns […array] function isEven(n) { let e = n % 2 if (Number.isNaN(e)) throw Error('Not a number!') return !e } Gist
  • 11. Unit tests should come FIRST! ● Fast - 1K+ per second ● Isolated - Perform no I/O ● Repeatable - Run in any order, without intervention ● Self-validating - No external tool to evaluate results ● Timely - written before code Source: http://agileinaflash.blogspot.co.il/2009/02/first.html
  • 12. Tools of the trade ● Test Runner -> mocha.js ● Assertion Framework -> chai.js ● Stubbing/Mocking tools -> sinon.js
  • 13. Testing Async Behavior ● Invoke the callback when your test is complete. ● By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test. describe('Async behavior', function() { before(function(done) { somethingAsync(done) }) it('should do ok', () => {}) })
  • 14. Exercise: Test different calls to ipify.org ● ipify.org - has 3 formats, regular, json and jsonp ● Write a unit test which tests each type ● I use “axios” = request library with promises const request = require('axios') function getMyIP(fmt) { fmt = typeof fmt == 'undefined' ? 'json' : fmt; return request.get(`https://api.ipify.org?format=${fmt}`) } gist
  • 15. Why are these tests bad? ● They test someone else’s code ● They make I/O!
  • 16. Sinon.js - stubbing, mocking, spying ● sinon.stub(obj, ‘method’).returns(1) What this does: ● Replaces obj.method() with function() { return 1 } ● Obj.method becomes a spy (gets special methods for inspection) ● Gets a .reset() method which rolls counters back ● Gets a .restore() method which restores everything back http://sinonjs.org/
  • 17. Exercise: test our getMyIP’s different cases ● Stub axios.get ● Don’t forget to restore ● Test 3 cases: ○ No Input ○ JSON ○ JSONP ● Goals: ○ Test that Axios is called correctly ○ Don’t break the function’s signature
  • 18. Bonus: pick your poison ● Testing Webservers ● Coverage reports with istanbul ● Syntactic sugar with sinon-as-promised, sinon-chai ● Integrating unit tests into CI/CD