Unit Testing in Javascript - Part 1: Basics

dev javascript, tdd, unit_testing

There are so many names of tools and frameworks are flying around in JavaScript if you’re a beginner it’s easy to get lost.

First things first: Identify what’s what

Basically we need the following key components to write and run unit tests:

  • Assertions: We run a method in subject under test and compare the result with some known expected value
  • Mocking: We need to mock the external dependencies (network services, database, file system etc) so that we can reliably test subject under test and the tests can run everywhere and without requiring any credentials or permissions.
  • Test runner: Our test is some block of code. Something needs to make sense of the unit tests we wrote, execute them and show the results (fail/pass)

Choosing the weapons: Mocha and Chai

In this example I’m going to use Mocha as my test runner and Chai as my assertion library.

They can simply be installed via NPM:

npm install --save-dev chai

To be able use Mocha in the Integrated Terminal inside Visual Studio we have to install Mocha as a global package:

npm install -g mocha

To put these to test I created this simple Maths service that calculates the factorial of an integer.

module.exports = class MathsService {
    factorial(num) {
        if (num < 0) 
            return -1;
        else if (num == 0) 
            return 1;
        else {
            return (num * this.factorial(num - 1));
        }
    }
};

And my unit test to test this method looks like this:

const MathsService = require('../maths-service.js');
const chai = require('chai');
const expect = chai.expect; 

describe('Factorial', function() {
    it('factorial should return correct value', function() {
        const mathsService = new MathsService();
    
        expect(mathsService.factorial(-1)).to.equal(-1);
        expect(mathsService.factorial(0)).to.equal(1);
        expect(mathsService.factorial(1)).to.equal(1);
        expect(mathsService.factorial(3)).to.equal(6);
        expect(mathsService.factorial(5)).to.equal(120);
    });
});

Chai supports 3 styles:

  • Should
  • Expect
  • Assert

They all server the same purpose so it’s just a matter of taste at the end of the day. For this demo I used expect style.

By default Mocha searches test folder. So you can run mocha without parameters if you put your tests under test folder or you can specify the folder. For example, in the screenshot below I moved the test to the root folder and entered “mocha .” and that worked fine as well.

Conclusion

In this post I want to show the very basics of unit testing in JavaScript just enough to see a passing test. In future posts I’ll build on this and explore other frameworks and other aspects of TDD.

Resources