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

More Related Content

PDF
Unit tests in node.js
PDF
Developers Testing - Girl Code at bloomon
PDF
Unit Testing - The Whys, Whens and Hows
PDF
The Many Ways to Test Your React App
PPTX
Java script unit testing
PPT
Unit testing with Spock Framework
PPTX
Testing Ext JS and Sencha Touch
PDF
Testing Angular
Unit tests in node.js
Developers Testing - Girl Code at bloomon
Unit Testing - The Whys, Whens and Hows
The Many Ways to Test Your React App
Java script unit testing
Unit testing with Spock Framework
Testing Ext JS and Sencha Touch
Testing Angular

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

PDF
The Future is Now: Writing Automated Tests To Grow Your Code
PPTX
Automation - web testing with selenium
PDF
Quick tour to front end unit testing using jasmine
PDF
PresentationqwertyuiopasdfghUnittest.pdf
PDF
Testing Django Applications
PDF
TDD super mondays-june-2014
PDF
Jest: Frontend Testing leicht gemacht @EnterJS2018
PPTX
Continuous feature-development
PDF
Node.js Development Workflow Automation with Grunt.js
PDF
Automated Developer Testing: Achievements and Challenges
PDF
Token Testing Slides
PPTX
Full Stack Unit Testing
PDF
Making the most of your Test Suite
PDF
Angular Intermediate
PDF
Javascript tdd byandreapaciolla
PDF
Into The Box 2018 | Assert control over your legacy applications
PPT
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
PDF
Devday2016 real unittestingwithmockframework-phatvu
PDF
Efficient JavaScript Unit Testing, May 2012
PDF
Getting Started with Selenium
The Future is Now: Writing Automated Tests To Grow Your Code
Automation - web testing with selenium
Quick tour to front end unit testing using jasmine
PresentationqwertyuiopasdfghUnittest.pdf
Testing Django Applications
TDD super mondays-june-2014
Jest: Frontend Testing leicht gemacht @EnterJS2018
Continuous feature-development
Node.js Development Workflow Automation with Grunt.js
Automated Developer Testing: Achievements and Challenges
Token Testing Slides
Full Stack Unit Testing
Making the most of your Test Suite
Angular Intermediate
Javascript tdd byandreapaciolla
Into The Box 2018 | Assert control over your legacy applications
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Devday2016 real unittestingwithmockframework-phatvu
Efficient JavaScript Unit Testing, May 2012
Getting Started with Selenium
Ad

More from Goa App (20)

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

Recently uploaded (20)

PPTX
additive manufacturing of ss316l using mig welding
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
DOCX
573137875-Attendance-Management-System-original
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
PPT on Performance Review to get promotions
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPT
introduction to datamining and warehousing
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Safety Seminar civil to be ensured for safe working.
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Construction Project Organization Group 2.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Artificial Intelligence
additive manufacturing of ss316l using mig welding
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
CH1 Production IntroductoryConcepts.pptx
573137875-Attendance-Management-System-original
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT on Performance Review to get promotions
Foundation to blockchain - A guide to Blockchain Tech
introduction to datamining and warehousing
Internet of Things (IOT) - A guide to understanding
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Automation-in-Manufacturing-Chapter-Introduction.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
bas. eng. economics group 4 presentation 1.pptx
Safety Seminar civil to be ensured for safe working.
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
CYBER-CRIMES AND SECURITY A guide to understanding
Construction Project Organization Group 2.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Artificial Intelligence

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