0

Using Jasmine, how do I test that a constructor throws an exception when given an invalid parameter? Given the constructor below,

class Obj {
    constructor(name) {
        if (!name) {
            throw new TypeError('\'name\' must be a valid, non-empty string');
        }
        this._name = name;
    }
}
exports.Obj = Obj;

how would I test that this:

var test = new Obj(null);

throws the expected exception?

James
  • 389
  • 2
  • 17
  • Difference here is that the error is thrown on new and not a method invocation. I tried just invoking the constructor on prototype but I get an "Class constructors cannot be invoked without 'new'" error. – James Mar 04 '16 at 22:41
  • Invoking a constructor vs calling a function makes no difference though, they are both things you call that throw exceptions. e.g. `expect(() => new Obj(null)).toThrow(new TypeError())` just like in the question I linked to. – loganfsmyth Mar 05 '16 at 01:06
  • You were absolutely right... just needed to wrap the new in a function call. Wanna add that as an answer so I can mark it? Or close this as a dupe? – James Mar 05 '16 at 16:54
  • Happy to help. I still feel like this is a dupe though. – loganfsmyth Mar 05 '16 at 17:30

0 Answers0