I m trying to write unit test cases to handle error codes that are defined below. not sure how to achieve it.
module.exports = {
Error: Err,
BadRequest: function () {
return new Err(400, 'Bad Request');
},
NotAcceptable: function () {
return new Err(406, 'Not Acceptable');
},
NotAuthorized: function () {
return new Err(401, 'Not Authorized');
}
};
function Err(code, message) {
assert(code, 'code');
Error.call(this);
Error.captureStackTrace(this, this.constructor);
Object.defineProperty(this, 'code', {
enumerable: true,
value: code
});
this.reason = message;
}
You should have a better base error layer by extending the Error class which already provide most of the functions you would need (capturing the stack trace automatically):
class Err extends Error {
constructor(code, message) {
super(message);
this.code = code;
this.reason = message;
}
}
You can then performa your assertion using the throw expectation:
const errorFn = () => { throw new Err(401, 'Unauthorized') };
expect(errorFn).to.throw(Err).to.haveOwnProperty('code', 401).to.haveOwnProperty('reason', 'Unauthorized');
You should obviously update your sub-error accordingly to extend your generic error.