Repository navigation
Unit Test
Mocha.js is an open-source JavaScript test framework that runs on Node.js and in the browser. It is]s designed for testing both synchronous and asynchronous code with a very simple interface. It provides functions that execute in a specific order and logs the results in the terminal window. It also cleans the state of the software being tested to ensure that test cases run independently of each other.
Chai.Js is an assertion library for Node.js and the browser and it is one of the most commonly used assertion libraries of Mocha.Js.
A test case or a unit test is used to define the expected behavior of the code and validate if the system is working correctly or not. A test suite is a collection of test cases that are grouped and executed together all relating to a single functionality.
In Mocha, Test Suites are defined using the describe() function while Test Cases are defined using the it() function.
- Supports any assertion library
- Mocha makes Asynchronous Testing Easy and Fun
- Mocha tests run serially, allowing for flexible and accurate reporting
- It Maps uncaught exceptions to the correct test cases
- Integrates fairly well with NodeJS
- Supports both Behavior Driven Development (BDD) and Test Driven Development (TDD)
- Is compatible with most web browsers
Install Mocha and Chai by running the following Commands in the terminal:
npm install mocha chai --save-dev
Install chai-http package:
npm install chai-http --save-dev
Mocha.js automatically looks for tests inside the test directory of your project. Create this directory in your project root:
mkdir test
Inititalize the application using the following command line/terminal prompts which will create the package.json file:
npn init
Just Enter through the questions asked next. As we are using Mocha, so in the package.json file edit the following in the "scripts":
"scripts": {
"test": "mocha"
}
And keep the rest of the package as it is:

Sample program to test:

Sample Test Case:

Result in Terminal:
