How to write a test which expects an Error to be thrown in Jasmine? How to write a test which expects an Error to be thrown in Jasmine? javascript javascript

How to write a test which expects an Error to be thrown in Jasmine?


Try using an anonymous function instead:

expect( function(){ parser.parse(raw); } ).toThrow(new Error("Parsing is not possible"));

you should be passing a function into the expect(...) call. Your incorrect code:

// incorrect:expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));

is trying to actually call parser.parse(raw) in an attempt to pass the result into expect(...),


You are using:

expect(fn).toThrow(e)

But if you'll have a look on the function comment (expected is string):

294 /**295  * Matcher that checks that the expected exception was thrown by the actual.296  *297  * @param {String} expected298  */299 jasmine.Matchers.prototype.toThrow = function(expected) {

I suppose you should probably write it like this (using lambda - anonymous function):

expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");

This is confirmed in the following example:

expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");

Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):

throw {   name: "Error",   message: "Parsing is not possible"}


As mentioned previously, a function needs to be passed to toThrow as it is the function you're describing in your test: "I expect this function to throw x"

expect(() => parser.parse(raw))  .toThrow(new Error('Parsing is not possible'));

If using Jasmine-Matchers you can also use one of the following when they suit the situation;

// I just want to know that an error was// thrown and nothing more about itexpect(() => parser.parse(raw))  .toThrowAnyError();

or

// I just want to know that an error of // a given type was thrown and nothing moreexpect(() => parser.parse(raw))  .toThrowErrorOfType(TypeError);