Unit Test Node.js Apps Using Mocha

Here’s the definition from Mocha website that gives a high level overview of Mocha framework.

Mocha is a feature-rich JavaScript test framework running on Node.js and the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

I am using Sublime editor for developing Node.js applications. Feel free to use any text editor which you are comfortable.

Before working on the demo app, make sure to install Node.js. Please refer the following article for installing Node.js on Windows platform.

Here’s our Prime number application on Sublime editor. You can see below, there is a folder for node_module where all the application specific packages are installed. Packages are installed by running the following command “npm install <packagename>”.


We are going to run the following command to install Mocha as a global package so all the applications can make use of.


Create a JavaScript file named “Prime.js” and code a function to check whether the number is prime or not. Do not forget to export the same, else we won’t be able to access the function.

  1. /* 
  2.   Function to test whether a number is prime 
  3.   https://blog.nraboy.com/2015/04/determine-if-a-number-is-prime-using-javascript/ 
  4. */  
  5. function isPrime(value) {  
  6.     for(var i = 2; i < value; i++) {  
  7.         if(value % i === 0) {  
  8.             return false;  
  9.         }  
  10.     }  
  11.     return value > 1;  
  12. }  
  14. module.exports.isPrime = isPrime;  
For unit testing the above function using Mocha, here’s what we do. It’s a good practice to create a “Test” folder, where you can keep all your unit tests. Create a file name “PrimeTest.js” and then we will start writing code for unit testing. Firstly, we have to import the modules. Assert is required for asserting or confirming the output of the function and make sure the output of the function is as expected. There are methods that you can call on assert and verify the results after execution.
  1. var assert = require('assert')  
  2.   , isPrime = require('../Prime').isPrime;  
  4. describe('isPrime Demo', function()  
  5. {  
  6.   it('isPrime should return true for prime number. Else it should return false', function()   
  7.   {  
  8.       assert.equal(false, isPrime(1));  
  9.       assert.equal(true, isPrime(3));  
  10.   });  
  11. });  
The “describe” function is nothing but a test suit, which groups the tests. You can have any levels of describe functions and within it, you can have one or more unit tests using “it” function.

In order to run the unit test, all you have to do is, open up command prompt and navigate to the folder where you have Prime demo. Key in “mocha” and hit enter; that should trigger running the unit test and you should be able to see the unit test result either pass or fail.


Next, we are going to write few more prime number related functionalities and perform unit test on the same. The following is the code snippet, reused from the following github.

We have two methods, both are used to calculate or return the next prime number. The only difference between the two is, one run synchronously and the other asynchronously using setTimeout function.
  1. /*  
  2.  Function to return next prime number 
  3.  https://github.com/alexyoung/ 
  4. */  
  5. function nextPrime(n) {  
  6.   var smaller;  
  7.   n = Math.floor(n);  
  9.   if (n >= 2) {  
  10.     smaller = 1;  
  11.     while (smaller * smaller <= n) {  
  12.       n++;  
  13.       smaller = 2;  
  14.       while ((n % smaller > 0) && (smaller * smaller <= n)) {  
  15.         smaller++;  
  16.       }  
  17.     }  
  18.     return n;  
  19.   } else {  
  20.     return 2;  
  21.   }  
  22. }  
  24. function asyncPrime(n, fn) {  
  25.   setTimeout(function() {  
  26.     fn(nextPrime(n));  
  27.   }, 10);  
  28. }  
Let us now write some unit test code and verify the above functionalities. The following is the code snippet where you can see we have grouped the sync and async tests together under one “describe” function. An asset is being made to verify the result after execution.
  1. describe('Next Prime Demo', function ()   
  2. {  
  3.     it('zero and one are not prime numbers', function ()   
  4.     {  
  5.        assert.equal(2, nextPrime(0));  
  6.        assert.equal(2, nextPrime(1));  
  7.     });  
  9.     it('asyncPrime should return the next prime number', function(done)   
  10.     {  
  11.         asyncPrime(128, function(n) {  
  12.           assert.equal(131, n, 'Wrong number');  
  13.           done();  
  14.          });  
  15.     });  
  16. });  
result after execution

There are other useful functions or hooks of mocha that you can use within your unit tests. Please take a look into the following articles for more understanding on the same.



Mocha is a tiny and easy to use powerful unit testing framework that one can use to perform unit or integrated tests. In this article, we have seen a tiny bit of mocha’s feature. There’s a lot one can learn and use.