SlideShare a Scribd company logo
1 of 19
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 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

The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeIsaac Murchie
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with seleniumTzirla Rozental
 
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
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsHonza Král
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014Alex Kavanagh
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Holger Grosse-Plankermann
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jskiyanwang
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesTao Xie
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slidesericholscher
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suiteericholscher
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Puneet Kala
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuPhat VU
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Hazem Saleh
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with SeleniumDave Haeffner
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesTriTAUG
 

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

The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your Code
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
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
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.js
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and Challenges
 

More from Goa App

web development in 2024 - website development
web development in 2024 - website developmentweb development in 2024 - website development
web development in 2024 - website developmentGoa App
 
web development full stack
web development full stackweb development full stack
web development full stackGoa App
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questionsGoa App
 
Spectrofluorimetry (www.redicals.com)
Spectrofluorimetry (www.redicals.com)Spectrofluorimetry (www.redicals.com)
Spectrofluorimetry (www.redicals.com)Goa App
 
UV rays
UV rays UV rays
UV rays Goa App
 
UV ray spectrophotometer
UV ray spectrophotometerUV ray spectrophotometer
UV ray spectrophotometerGoa App
 
Spectrofluorimetry or fluorimetry (www.Redicals.com)
Spectrofluorimetry or fluorimetry (www.Redicals.com)Spectrofluorimetry or fluorimetry (www.Redicals.com)
Spectrofluorimetry or fluorimetry (www.Redicals.com)Goa App
 
Atomic Absorption Spectroscopy (www.Redicals.com)
Atomic Absorption Spectroscopy (www.Redicals.com)Atomic Absorption Spectroscopy (www.Redicals.com)
Atomic Absorption Spectroscopy (www.Redicals.com)Goa App
 
Hidden Markov Model Toolkit (HTK) www.redicals.com
Hidden Markov Model Toolkit (HTK) www.redicals.comHidden Markov Model Toolkit (HTK) www.redicals.com
Hidden Markov Model Toolkit (HTK) www.redicals.comGoa App
 
Cash Budget
Cash BudgetCash Budget
Cash BudgetGoa App
 
Speech Recognition
Speech Recognition Speech Recognition
Speech Recognition Goa App
 
Social Network Analysis Using Gephi
Social Network Analysis Using Gephi Social Network Analysis Using Gephi
Social Network Analysis Using Gephi Goa App
 
Binomial Heap
Binomial HeapBinomial Heap
Binomial HeapGoa App
 
Memory cards
Memory cardsMemory cards
Memory cardsGoa App
 
Magnetic memory
Magnetic memoryMagnetic memory
Magnetic memoryGoa App
 
E governance
E governanceE governance
E governanceGoa App
 
Mobile phones
Mobile phonesMobile phones
Mobile phonesGoa App
 
Enterprise resource planning in manufacturing
Enterprise resource planning in manufacturingEnterprise resource planning in manufacturing
Enterprise resource planning in manufacturingGoa App
 
Enterprise application integration
Enterprise application integrationEnterprise application integration
Enterprise application integrationGoa App
 

More from Goa App (20)

web development in 2024 - website development
web development in 2024 - website developmentweb development in 2024 - website development
web development in 2024 - website development
 
web development full stack
web development full stackweb development full stack
web development full stack
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
Spectrofluorimetry (www.redicals.com)
Spectrofluorimetry (www.redicals.com)Spectrofluorimetry (www.redicals.com)
Spectrofluorimetry (www.redicals.com)
 
UV rays
UV rays UV rays
UV rays
 
UV ray spectrophotometer
UV ray spectrophotometerUV ray spectrophotometer
UV ray spectrophotometer
 
Spectrofluorimetry or fluorimetry (www.Redicals.com)
Spectrofluorimetry or fluorimetry (www.Redicals.com)Spectrofluorimetry or fluorimetry (www.Redicals.com)
Spectrofluorimetry or fluorimetry (www.Redicals.com)
 
Atomic Absorption Spectroscopy (www.Redicals.com)
Atomic Absorption Spectroscopy (www.Redicals.com)Atomic Absorption Spectroscopy (www.Redicals.com)
Atomic Absorption Spectroscopy (www.Redicals.com)
 
Hidden Markov Model Toolkit (HTK) www.redicals.com
Hidden Markov Model Toolkit (HTK) www.redicals.comHidden Markov Model Toolkit (HTK) www.redicals.com
Hidden Markov Model Toolkit (HTK) www.redicals.com
 
Cash Budget
Cash BudgetCash Budget
Cash Budget
 
Speech Recognition
Speech Recognition Speech Recognition
Speech Recognition
 
Social Network Analysis Using Gephi
Social Network Analysis Using Gephi Social Network Analysis Using Gephi
Social Network Analysis Using Gephi
 
Binomial Heap
Binomial HeapBinomial Heap
Binomial Heap
 
Blu ray
Blu rayBlu ray
Blu ray
 
Memory cards
Memory cardsMemory cards
Memory cards
 
Magnetic memory
Magnetic memoryMagnetic memory
Magnetic memory
 
E governance
E governanceE governance
E governance
 
Mobile phones
Mobile phonesMobile phones
Mobile phones
 
Enterprise resource planning in manufacturing
Enterprise resource planning in manufacturingEnterprise resource planning in manufacturing
Enterprise resource planning in manufacturing
 
Enterprise application integration
Enterprise application integrationEnterprise application integration
Enterprise application integration
 

Recently uploaded

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 

Recently uploaded (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 

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