Javascript testing with Mocha: A Series

Cedric Damian
Practical Software Testing
4 min readApr 28, 2021

Part 1: Introduction and running a sample test with Mocha and Chai

Mocha is an open-source Javascript test framework that runs on Nodejs and on the browser and is used for testing Synchronous and Asynchronous code. Being my favorite type of coffee and also one of the most depended upon modules on npm according to Libraries.io, I thought it would be a good idea to write a series of articles about it. This first article will give you a solid introduction to Mocha and using it with Node.js. For this series, you will need to have Node and npm installed.

Mocha provides functions that are executed in a specific order and logs their results to a terminal window. Mocha uses hooks to organize its structure. They include:

  • describe(): Used to group one or more test cases and can be nested.
  • it(): the test case is laid down here
  • before(): It’s a hook to run before the first it() or describe();
  • beforeEach(): It’s a hook to run before each it() or describe();
  • after(): It’s a hook to run after it() or describe();
  • afterEach(): It’s a hook to run after each it() or describe();

The keywords describe and it provide structure to the tests by grouping them into Test cases and Test suites. A Test case is a set of actions executed to validate a feature or functionality of your software. A Test Suite is a collection of tests all relating to a similar functionality or behavior.

Mocha can be used with any assertion library but for this series, we will use Chai(local for Tea), a popular assertion library for Node.js and the browser. It provides functions and methods which help you compare the output of a test with the expected result. Chai provides clean syntax that reads almost like English. An example of a Chai assertion is expect(exampleArray).to.have.lengthOf(3);

This simply validates whether the variable ‘exampleArray’ has a length of 3 or not. Alright, enough talk, let us dive into the code already.

Setting up Mocha and Chai

The code for this tutorial will be updated here. First things first, you will need to install Mocha. To install globally, fire up your terminal and run this:

npm i — global mocha

This will make the mocha CLI binary available for use in your command line terminal. You can now run tests in your terminal with the command mocha . Next, we will write a unit test for a simple functionality and configure a script to run it with Mocha. Mocha.js automatically looks for tests inside the test folder of your project so go ahead and create this in your project root.

mkdir test

Configure the test script in your package.jsonto run tests in mocha. It should look like this:

{
"scripts": {
"test": "mocha"
}
}

Now you can simply run your tests with this simple command:

npm test

Next, we will install Chai. Simply run:

npm install chai

Writing tests using Mocha and Chai

Now the Setup is all done, let us create a test case of A calculator which will perform the basic arithmetic operations:

  • Addition
  • Subtraction
  • Division
  • Multiplication

We will need to first set up a file to store the configuration of our arithmetic methods. Create a file src/calculator.js and add the following code:

const add = (a, b) => a + b
const subtract = (a, b) => a - b
const multiply = (a, b) => a * b
const divide = (a, b) => b !== 0 ? (a / b) : undefined module.exports = {
add,
subtract,
multiply,
divide,
}

Here, we define the rules that our functions will follow. Notice that in divide, we create a condition to check whether the denominator passed is 0 and return undefined in that case.

Create a test.js file inside your test directory and add the following code:

const chai = require('chai')const expect = chai.expectconst calculator = require('../src/calculator')
describe('Calculator', () => { describe('Addition', () => { it('should sum two numbers', () => { expect(calculator.add(2, 2)).to.equal(4) expect(calculator.add(50, 39)).to.equal(89) }) }) describe('Subtraction', () => { it('should subtract two numbers', () => { expect(calculator.subtract(6, 2)).to.equal(4) expect(calculator.subtract(50, 39)).to.equal(11) }) }) describe('Multiplication', () => { it('should multiply two numbers', () => { expect(calculator.multiply(3, 2)).to.equal(6) expect(calculator.multiply(-31, 32)).to.equal(-992) expect(calculator.multiply(-5, -2)).to.equal(10) }) })
describe('Division', () => {
it('should divide two numbers', () => { expect(calculator.divide(4, 2)).to.equal(2) expect(calculator.divide(50, 5)).to.equal(10) }) it('should return NaN if the denominator is zero', () => { expect(calculator.divide(4, 0)).to.equal(undefined) expect(calculator.divide(-15, 0)).to.equal(undefined) }) })})

The code, in Addition, Subtraction and Multiplication is pretty straightforward. You describe what the test case does in English and inside that function, describe the assertions using Chai syntax, passing in sample inputs. More about Chai assertions can be found in the Chai documentation.

Note that under Division, we have nested two it functions. I want to emphasize the second function which handles the division in case the denominator is 0. This is an important feature to note.

You can now run your test case using:

npm test

This should return the following results:

And that’s all for the first tutorial of this series! You have successfuly run your first test suite with Mocha and Chai.

Since you’ve made it this far, please consider following me for other articles on this series.

Cheers.

--

--

Cedric Damian
Practical Software Testing

QA Automation Engineer || Frontend Developer || Lover of Life