Introduction to Mocha
Testing is an important aspect of the SDLC (software development life cycle). You really cannot say that you have developed a viable or reliable application if you have not tested it. Today we will introduce you to a very popular test framework, you most likely have seen it as a testing option when creating a Node powered application, be it Angular, Vue, Express etc.
So what is Mocha: Mocha is a feature-rich JavaScript test framework that runs on Node.js and in the browser, it makes asynchronous testing simple and fun. All Mocha test run serially, enabling flexible and accurate reporting, while at the same time mapping uncaught exceptions to the correct test cases
Mocha has lots of features which you will learn about in this tutorial series, they are:
Installation
You can install mocha globally using npm by running:
npm install --global mocha

or you can add it as a development dependency for your project like this:
npm install --save-dev mocha
It should be noted that Mocha requires Node.js V6.0.0 or newer as from Mocha v6.0.0
Getting started
In this section we will help you create your first test file.
npm install mocha
mkdir test
//creates a folder called test
$EDITOR test/test.js # or you open with your favorite editor
edit the test.js file in your editor to have the content below:
var assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('has to return -1 when the value is not present', function() {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
Back inside your terminal run:
./node_modules/mocha/bin/mocha
Array
#indexOf()
? has to return -1 when the value is not present
1 passing (9ms)
Then you should set up a test script in package.json:
"scripts": {
"test": "mocha"
}
Finally run tests with:
npm test
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook