SlideShare a Scribd company logo
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
Ad

More Related Content

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
Isaac Murchie
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
Tzirla 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 jasmine
Gil Fink
 
PresentationqwertyuiopasdfghUnittest.pdf
PresentationqwertyuiopasdfghUnittest.pdfPresentationqwertyuiopasdfghUnittest.pdf
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
Honza Král
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
Alex Kavanagh
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
nhm taveer hossain khan
 
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
kiyanwang
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
Tao Xie
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
ericholscher
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
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
ericholscher
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea 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 applications
Ortus 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-phatvu
Phat VU
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
Hazem Saleh
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
Dave Haeffner
 
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
Isaac Murchie
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
Tzirla 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 jasmine
Gil Fink
 
PresentationqwertyuiopasdfghUnittest.pdf
PresentationqwertyuiopasdfghUnittest.pdfPresentationqwertyuiopasdfghUnittest.pdf
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
Honza Král
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
Alex Kavanagh
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger 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.js
kiyanwang
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
Tao Xie
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
ericholscher
 
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
ericholscher
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea 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 applications
Ortus 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-phatvu
Phat VU
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
Hazem Saleh
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
Dave Haeffner
 

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
Goa App
 
web development full stack
web development full stackweb development full stack
web development full stack
Goa App
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
Goa 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 spectrophotometer
Goa 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.com
Goa App
 
Cash Budget
Cash BudgetCash Budget
Cash Budget
Goa 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 Heap
Goa App
 
Blu ray
Blu rayBlu ray
Blu ray
Goa App
 
Memory cards
Memory cardsMemory cards
Memory cards
Goa App
 
Magnetic memory
Magnetic memoryMagnetic memory
Magnetic memory
Goa App
 
E governance
E governanceE governance
E governance
Goa App
 
Mobile phones
Mobile phonesMobile phones
Mobile phones
Goa App
 
Enterprise resource planning in manufacturing
Enterprise resource planning in manufacturingEnterprise resource planning in manufacturing
Enterprise resource planning in manufacturing
Goa App
 
Enterprise application integration
Enterprise application integrationEnterprise application integration
Enterprise application integration
Goa App
 
web development in 2024 - website development
web development in 2024 - website developmentweb development in 2024 - website development
web development in 2024 - website development
Goa App
 
web development full stack
web development full stackweb development full stack
web development full stack
Goa App
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
Goa 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 spectrophotometer
Goa 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.com
Goa App
 
Cash Budget
Cash BudgetCash Budget
Cash Budget
Goa 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 Heap
Goa App
 
Memory cards
Memory cardsMemory cards
Memory cards
Goa App
 
Magnetic memory
Magnetic memoryMagnetic memory
Magnetic memory
Goa App
 
E governance
E governanceE governance
E governance
Goa App
 
Mobile phones
Mobile phonesMobile phones
Mobile phones
Goa App
 
Enterprise resource planning in manufacturing
Enterprise resource planning in manufacturingEnterprise resource planning in manufacturing
Enterprise resource planning in manufacturing
Goa App
 
Enterprise application integration
Enterprise application integrationEnterprise application integration
Enterprise application integration
Goa App
 
Ad

Recently uploaded (20)

DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
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