Node.js: Testing
Mocha
- for running the tests
Chai
- for asserting the results
Sinon
- for managing side effects and external dependencies
npm install --save-dev mocha chai
package.json
"scripts": {
"test": "mocha"
}
Then you can run tests with npm test
. Mocha is then looking for tests under folder test
.
Dummy test
test/start.js
const expect = require('chai').expect;
it('should add numbers correctly', function(){
const num1 = 2;
const num2 = 3;
expect(num1 + num2).to.equal(5);
})
it('should not give a result of 6', function(){
const num1 = 2;
const num2 = 3;
expect(num1 + num2).not.to.equal(6);
})
Real test
middleware/is-auth.js
module.exports = (req, res, next) => {
const authHeader = req.get('Authorization');
is (!authHeader) {
const error = new Error('Not authenticated.');
error.statusCode = 401;
throw error;
}
....
}
test/auth-middleware.js
const expect = require('chai').expect;
const authMiddleware = require('../middleware/is-auth');
it('should throw an error if no authorization header is present', function() {
const req = {
get: function(headerName) {
return null;
}
};
expect(authMiddleware.bind(req, {}, () => {})).to.throw('Not authenticated.');
});