Setup Mocha Chai Unit Tests

Unit tests are a huge part of a modern developers workflow. When I was looking into what tools I should use for javascript unit tests I asked my peers and they all went for mocha and chai. 

What are mocha and chai?

Mocha is a testing framework and chai is an assertion library, together they give the developer a great tool to start writing unit tests. 

Setup 

First install the node packages.


1
2
 npm install chai
 npm install mocha

Add the packages into your project


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
  "name": "Demo",
  "description": "",
  "version": "0.0.1",
  "private": true,
  "scripts": {
      "test": "mocha"
  },
  "dependencies": {
    "applicationinsights": "^0.17.0",
    "body-parser": "^1.18.3",
  },
  "devDependencies": {
    "chai": "^3.5.0",
    "mocha": "^5.2.0"
  }
}

Once this is done start your application


1
npm start

Setup up a test directory in the root of your project where we will keep our unit tests. 

Create a test script called unitTests.js and copy/paste the following code to include both mocha and chai. 


1
2
3
4
5
6
7
8
9
const describe = require('mocha').describe;
const it = require('mocha').it;
const expect = require('chai').expect;

describe('test function', function () {
        it('should check if string equals string', function () {
            expect("string").to.equal("string");
        });
});

To run this test just enter the following into a terminal. 


1
npm test

All tests should pass 🙂 

Now have a go including your actual functions into the expect parameter and the return in the equals. 

Happy testing 🙂