Mocha — Simple, flexible and fun testing framework for JavaScript
2 min readNov 15, 2023
Here’s a simple example of a Mocha test:
Install Mocha
$ npm install mocha
$ mkdir test
$ $EDITOR test/test.js # or open with your favorite editor
Write your test
const assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
Set up a test script in package.json
"scripts": {
"test": "mocha"
}
Run you test
$ npm test
In this example, we’re testing the `indexOf` method of an array to ensure it returns -1 when the value is not present.
To use Mocha, you typically install it via npm (Node Package Manager) and then run your test files using the `mocha` command. Mocha is often used in combination with assertion libraries like Node.js’s built-in `assert` module, or third-party libraries like Chai.