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
The Future is Now: Writing Automated Tests To Grow Your Code
Isaac Murchie
 
PPTX
Automation - web testing with selenium
Tzirla Rozental
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
PDF
Testing Django Applications
Honza Král
 
PDF
TDD super mondays-june-2014
Alex Kavanagh
 
PDF
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
PPTX
Continuous feature-development
nhm taveer hossain khan
 
PDF
Node.js Development Workflow Automation with Grunt.js
kiyanwang
 
PDF
Automated Developer Testing: Achievements and Challenges
Tao Xie
 
PDF
Token Testing Slides
ericholscher
 
PPTX
Full Stack Unit Testing
GlobalLogic Ukraine
 
PDF
Making the most of your Test Suite
ericholscher
 
PDF
Angular Intermediate
LinkMe Srl
 
PDF
Javascript tdd byandreapaciolla
Andrea Paciolla
 
PDF
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
PPT
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Puneet Kala
 
PDF
Devday2016 real unittestingwithmockframework-phatvu
Phat VU
 
PDF
Efficient JavaScript Unit Testing, May 2012
Hazem Saleh
 
PDF
Getting Started with Selenium
Dave Haeffner
 
The Future is Now: Writing Automated Tests To Grow Your Code
Isaac Murchie
 
Automation - web testing with selenium
Tzirla Rozental
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
Testing Django Applications
Honza Král
 
TDD super mondays-june-2014
Alex Kavanagh
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
Continuous feature-development
nhm taveer hossain khan
 
Node.js Development Workflow Automation with Grunt.js
kiyanwang
 
Automated Developer Testing: Achievements and Challenges
Tao Xie
 
Token Testing Slides
ericholscher
 
Full Stack Unit Testing
GlobalLogic Ukraine
 
Making the most of your Test Suite
ericholscher
 
Angular Intermediate
LinkMe Srl
 
Javascript tdd byandreapaciolla
Andrea Paciolla
 
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Puneet Kala
 
Devday2016 real unittestingwithmockframework-phatvu
Phat VU
 
Efficient JavaScript Unit Testing, May 2012
Hazem Saleh
 
Getting Started with Selenium
Dave Haeffner
 

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)

PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
MRRS Strength and Durability of Concrete
CivilMythili
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Thermal runway and thermal stability.pptx
godow93766
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
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