6.2 Mocha and Basic Testing

Setting up a Testing Suite

Example:

it('should add two numbers', ()=> {
var res = utils.add(33, 11);
});
"scripts": {
"test": "mocha **/*.test.js"
},

Note "mocha **/*.test.js" searches every sub-directory due to the globing pattern **/*.test.js.

Running npm test gets

> mocha **/*.test.js
√ should add two numbers
1 passing (4ms)

However, we haven’t asserted anything, which you might have noticed.

Example:

it('should add two numbers', ()=> {
var res = utils.add(33, 11);
throw new Error('Value not correct');
});
> mocha **/*.test.js
1) should add two numbers
0 passing (5ms)
1 failing
1) should add two numbers:
Error: Value not correct
at Context.it (utils\utils.test.js:5:11)

To enhance it, we change the above to be

const utils = require('./utils');
it('should add two numbers', ()=> {
var res = utils.add(33, 11);
if (res != 44)
throw new Error(`Expected 44, but got ${res}.`);
});

Exercise:
Make a square function. Write a test suite for it.

module.exports.square = (x)=>x*x;

it('should add two numbers', ()=> {
var res = utils.square(50);
if (res != 2500)
throw new Error(`Expected 250, but got ${res}.`);
});
√ should square two numbers
√ should square two numbers
2 passing (5ms)

OR

1) should sqare two numbers:
Error: Expected 250, but got 2499.
at Context.it (utils\utils.test.js:12:15)