Testing in NodeJS with Mocha

Testing in NodeJS with Mocha

Mocha is a popular testing framework for NodeJS. it can be installed using npm:

npm install mocha

Mocha works with files placed inside the test directory, which must be created:

mkdir test

Setting up npm run command

Normally, mocha is executed using the following command:

./node_modules/mocha/bin/mocha

To simplify things, package.json can be modified as such:

...
"scripts": {
  "test": "mocha"
},
...

Mocha can then be executed using the following command:

npm run test

test/test.js

var assert = require('assert');

function functionToTest(){
  return 2
}

describe('FunctionToTest', () => {
  describe('Squaring a number', () => {
    it("Should return 2", () => {
      assert.equal(functionToTest(), 2);
    })
  })
})

Which should output:

  FunctionToTest
    Squaring a number
      ✓ Should return 2

  1 passing (5ms)

Chai

The file test.js uses the assert module to evaluate whether a test passes or not. For this purpose, different assertion libraries exist. A popular choice is Chai.js