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

JavascriptTestingnode.jsJasmine

Javascript Problem Overview


I'm trying to write a test for the Jasmine Test Framework which expects an error. At the moment I'm using a Jasmine Node.js integration from GitHub.

In my Node.js module I have the following code:

throw new Error("Parsing is not possible");

Now I try to write a test which expects this error:

describe('my suite...', function() {
    [..]
    it('should not parse foo', function() {
    [..]
        expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
    });
});

I tried also Error() and some other variants and just can't figure out how to make it work.

Javascript Solutions


Solution 1 - Javascript

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(...),

Solution 2 - Javascript

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} expected
298  */
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"
}

Solution 3 - Javascript

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 it
expect(() => parser.parse(raw))
  .toThrowAnyError();

or

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

Solution 4 - Javascript

A more elegant solution than creating an anonymous function whose sole purpose is to wrap another, is to use ES5's bind function. The bind function creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Instead of:

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

Consider:

expect(parser.parse.bind(parser, raw, config)).toThrow("Parsing is not possible");

The bind syntax allows you to test functions with different this values, and in my opinion makes the test more readable. See also:

https://stackoverflow.com/questions/9500586/does-jasmines-tothrow-matcher-require-the-argument-to-be-wrapped-in-an-anonymou/13233194#13233194

Solution 5 - Javascript

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

Solution 6 - Javascript

I know that is more code, but you can also do:

try
    Do something
    @fail Error("should send a Exception")
catch e
    expect(e.name).toBe "BLA_ERROR"
    expect(e.message).toBe 'Message'

Solution 7 - Javascript

In my case, the function throwing an error was async, so I followed this:

await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);

Solution 8 - Javascript

For CoffeeScript lovers:

expect( => someMethodCall(arg1, arg2)).toThrow()

Solution 9 - Javascript

For me, the posted solution didn't work and it kept on throwing this error:

> Error: Expected function to throw an exception.

I later realised that the function which I was expecting to throw an error was an async function and was expecting the promise to be rejected and then throw an error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

And that’s what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
    const promise = service.getRequestStatus('request-id');
        return expectToReject(promise).then((err) => {
            expect(err.message).toEqual('REQUEST NOT FOUND');
        });
}));

Solution 10 - Javascript

it('it should fail', async () => {
    expect.assertions(1);

    try {
        await testInstance.doSomething();
    }
    catch (ex) {
        expect(ex).toBeInstanceOf(MyCustomError);
    }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionechoxView Question on Stackoverflow
Solution 1 - JavascriptPete HodgsonView Answer on Stackoverflow
Solution 2 - JavascriptAndrzej ŚliwaView Answer on Stackoverflow
Solution 3 - JavascriptJamie MasonView Answer on Stackoverflow
Solution 4 - JavascriptJonathan GawrychView Answer on Stackoverflow
Solution 5 - JavascriptJakeView Answer on Stackoverflow
Solution 6 - JavascripttolbardView Answer on Stackoverflow
Solution 7 - JavascriptWildhammerView Answer on Stackoverflow
Solution 8 - JavascriptfernandohurView Answer on Stackoverflow
Solution 9 - JavascriptarifaBatoolView Answer on Stackoverflow
Solution 10 - JavascriptJuan RadaView Answer on Stackoverflow