Skip to content

Unit Test

Erfan Mostafiz edited this page Sep 5, 2021 · 8 revisions

Testing Tool: Mocha and Chai

Overview

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.

Test Case and Test Suite

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.

Advantages of Mocha integrated with Chai

  • 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

Getting Started

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: package.json

Testing Example

Sample program to test:
Example

Sample Test Case:
Testcase

Result in Terminal:
Result

Clone this wiki locally