- Mocha is a JavaScript testing framework for running on NodeJS in asynchronous mode.
- In this demo,”We will learn to install and run Mocha test framework”.
- The Mocha test framework can be installed using npm install mocha –save-dev command.The following screenshot shows the installation of Mocha framework.
- To demonstrate Mocha framework we have creates MochaTestDemo project.The structure of this project is as follows.
- The number-operation.js file contains the javascript code for exporting operation object which contains a method named addTwoNumber() for adding 2 input numbers and returns the result.The code content of number-operation.js file are as follows:-
var operation ={ addTwoNumber : function(number1, number2){ return number1 + number2; } }; module.exports = operation;
- The index.js file contains the code to import number-operation.js file using require statement and calls the addTwoNumber() for 5 and 10.The code content of index.js file are as follows:-
var operation = require('./number-operation'), result = operation.addTwoNumber(5,10); console.log("Result: ",result);
- The demo code can be run using node index.js command.The following screenshot shows the terminal with index.js in execution.
- Now we can create a test directory and a test.js file for writing Mocha test cases.The following screenshot shows the terminal with test directory and test.js file creation.
- The test.js file contains test case using describe and assert method.The code content of test.js file are as follows:-
var assert = require("assert"), operation = require('../number-operation'); describe('Testing addTwoNumber', function() { it('should return 4 when the input number are 1 and 3', function () { assert.equal(4, operation.addTwoNumber(1,3)); }); });
- As we have installed Mocha as local dependency to the project we need add a script entry in package.json file to run Mocha.The code content of package.json file are as follows:-
{ "name": "mocha-test-demo", "version": "1.0.0", "main": "index.js", "scripts": { "test": "mocha" }, "license": "ISC", "devDependencies": { "mocha": "^2.3.2" } }
- No we can run the Mocha using npm run test command.The following screenshot shows the terminal with Mocha in execution and test case is passed.
- you can download this demo using following link:-
https://github.com/saan1984/MochaTestDemo