Node JS Unit Testing (Mocha & Chai)

June Chung
3 min readAug 8, 2020

--

Installation of Mocha & Chai

# How to Check Node JS Version
node -v

>> Make a directory and npm init
mkdir mocha_test
npm init
(and enter all in through the default project config — except <entry point: (index.js) app.js> , after it will create a package.js and the relevant project config files)

>> Install Mocha and Chai
in project directory
npm install mocha chai --save-dev
this means saving mocha & chai in the ‘dev’ dependencies ( you can see it in package.json file)

>> change scripts.tests in package.json
“test”: “mocha”
"test": "mocha || true"
this deletes all the crap in the result and only gives you the gist (what failed and what succeeded)

>>Create app.js (entry point) & test directory
!!! When creating test directory, everything in your actual source directory should match your name & structure. For example, if you have happy/hey.js file in your source, under test directory should have happy/heyTest.js

Left — Follow a predictable directory within the test directory / Right — The name for test files should usually be predictable as well

>>create your app.js file (as you want — can be a function, etc)

>> write your appTest.js file
# bring in ASSERTION LIBRARY
const assert = require(‘chai’).assert;
# bring in THE ACTUAL APP
const app = require(‘../app’);
OR bring in the individual functions
const sayHello = require(‘../app’).sayHello;

# write down the actual test code under
describe(‘App’s name’, function(){ … });

* How does a basic Unit Test structure look like?
describe(‘App’, function(){ … }); or describe(‘App’, ( ) => { … });
describe → grouping of testing
it → is the actual test cases

>> run the test
npm run test

# How to remove the npm errors when a test fails?
When a test fails it throws all the npm errors which is a mess. How do you remove these?
under package.json .. script.test : “mocha”“mocha || true”
this will remove all the unnecessary logs for npm

# how to add multiple functions in one file
export = {
function1: function() { …}
function2: function() { …}
}

CF. What is “=>” this arrow mean?
ES6 Arrow Function Expression
app.post('/add-item', (req, res) => {
// TODO: add an item to be posted
});

EQUALS
app.post('/add-item', function(req, res) {
// TODO: add an item to be posted
});

In conclusion, function = ()

HOW TO TEST WITH mocha.expect() ?

The full list of ASSERTION STYLEs

Please refer to the following page : https://www.chaijs.com/guide/styles/#expect

--

--