Unit testing is an inevitable part of software development for those who aim for code quality. In this article, we are going to discuss unit testing in javascript language. Unit testing in javascript starts with choosing a framework. The most convenient framework varies depending on the project, work approach/technique (TDD, BDD,..) and the tested unit etc. In this tutorial, we will be using mocha library.

Mocha is the core framework, that you can define test cases and has its own cute reporting. Unlike other unit test frameworks, in mocha, you have to add external test assertion, stubbing libraries. That makes it more flexible.

Now let’s begin with creating a project (assuming you already have node.js installed).

Then create a directory for our test with below command:

mkdir mocha

Then, go to this folder with

cd mocha

and start to create a project with below command:

npm init

Note: Do not forget to make test command ‘mocha’.

Let’s define some functions for testing. Create a file under the created mocha directory for your functions and name it as you wish ( I called it index.js). And make a very simple function that multiplies two numbers.

function multiplyNumbers(x, y) {
    return x * y;
}

For using this function outside this file, we need to export it. Though it can be done in many ways, I will export them with module.exports:

module.exports = {
          multiplyNumbers : multiplyNumbers
}

Now, create a test folder. And inside it, create the test file (it should be named as index.test.js).

Of course, we need the test libraries. Let’s install them with below commands.

Install Mocha:  npm install –g mocha

For assertions, we will use chai library.

Install Chai: npm install chai

Within chai, different assertion styles might be used. You can find the differences between them here. I chose expect for no specific reason.

Let’s define expect to use it in our test.index.js file:

const expect = require(‘chai’).expect;

And the function to test:

const multiplyNumbers = require(‘../index.js’).multiplyNumbers;

Now, we can move on with our first test. In mocha, a test group is defined within describe blocks and tests are written inside it blocks.

Since we are testing index.js ( or the name you have opted), we will group all the test as index.js tests and inside this block each function tested will be another group.

Note: I opted for the naming convention from the official mocha documentation.

describe(‘Index’, function () {
    describe(‘#multiplyNumbers()’, function () {
        it(‘should return the result of multiplication’, function () {
            let result = multiplyNumbers(4, 6);
            expect(result).to.equal(24);
        });
    });
});

Our, index.test.js test file will be like that:

And, let’s go to the mocha folder and run below command to start our test.

npm test

Congrats! You wrote and run your first test!

Repo: https://github.com/savatagean/unittesting

Thanks.
Ege Aksöz