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
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework