This works in Mocha/Chai:
describe('Chai throw() with old-style custom errors', ()=> {
// old way
function ES5Error(message = 'todo', value) {
this.name = 'ES5Error';
this.message = message;
}
ES5Error.prototype = new Error();
it('catches ES5Errors', ()=> {
var err = new ES5Error('This is a bad function.');
var fn = function () { throw err; }
expect(fn).to.throw(ES5Error);
expect(fn).to.throw(Error);
expect(fn).to.throw(/bad function/);
expect(fn).to.not.throw('good function');
expect(fn).to.throw(ES5Error, /bad function/);
expect(fn).to.throw(err);
});
});
While a class based approach does not:
describe('Chai throw() with new-style custom errors', ()=> {
// New way
class ExtendError extends Error {
constructor(message = 'todo', value) {
super(message);
this.name = 'ExtendError';
this.message = message;
}
}
it('catches ExtendError', ()=> {
var err = new ExtendError('This is a bad function.');
var fn = function () { throw err; }
expect(fn).to.throw(ExtendError);
expect(fn).to.throw(Error);
expect(fn).to.throw(/bad function/);
expect(fn).to.not.throw('good function');
expect(fn).to.throw(ExtendError, /bad function/);
expect(fn).to.throw(err);
});
});
I also implemented the related SO answer here. Though interesting, it still didn't work with mocha throws()
. I'm basically happy to go with the ES5 style Errors, but I'm just unsure what the actual problem is. When I transpile the code for ExtendError
I can't immediately see anything that would trip up the expect clause:
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var ExtendError = function (_Error) {
_inherits(ExtendError, _Error);
function ExtendError() {
var message = arguments.length <= 0 || arguments[0] === undefined ? 'todo' : arguments[0];
var value = arguments[1];
_classCallCheck(this, ExtendError);
var _this = _possibleConstructorReturn(this, _Error.call(this, message));
_this.name = 'ExtendError';
_this.message = message;
return _this;
}
return ExtendError;
}(Error);
What is Mocha/Chai's problem?