Using toThrowError in Jasmine

24,135

Checking exception for a function with parameter is not supported in jasmine. But you can use below workaround to overcome this limitation and test your functions.

describe('toThrowError test case', function() {

    it('test getRandomNumber function for undefined', function() {
        expect(function() {
            getRandomNumber(undefined);
        }).toThrowError("You must provide a number");
    });

    it('test getRandomNumber function for 0', function() {
        expect(function() {
            getRandomNumber(0);
        }).toThrowError("The maximum value must be greater than 0 and less than 100.");
    });

});

toThrowError matcher takes 1 or 2 parameters

  • 1 Parameter - Either exception message or exception type
  • 2 Parameters - Exception type and Exception message

Example to check based on exception type:

function getRandomNumber(max) {
    throw new SyntaxError();
}

describe('toThrowError test case', function() {
    it('test getRandomNumber function for undefined', function() {
        expect(function() {
            getRandomNumber(undefined);
        }).toThrowError(SyntaxError);
    });
});

Refer link for different types of exceptions.

Custom Error Message

Below mentioned snippet gives a sample for using the custom error messages.

function getRandomNumber(max) {
    throw new ArgumentException();
}

function ArgumentException(message) {
  this.name = 'ArgumentException';
  this.message = message || '';
}

ArgumentException.prototype = new Error();
ArgumentException.prototype.constructor = ArgumentException;

describe('toThrowError test case', function() {
    it('test getRandomNumber function for undefined', function() {
        expect(function() {
            getRandomNumber(undefined);
        }).toThrowError(ArgumentException);
    });
});
Share:
24,135

Related videos on Youtube

user3192178
Author by

user3192178

Updated on July 09, 2022

Comments

  • user3192178
    user3192178 almost 2 years

    I am working on an app that makes heavy use of JavaScript. I need to unit test this code. In an effort to do that, I'm relying on Jasmine.

    Some of my JavaScript code throws JavaScript Error objects. Those objects assign values to the message and name property of the Error object. I assign a type of exception to the name property. For instance, sometimes the name is set to OutOfRangeException, sometimes its ArgumentException, etc.

    How do I use the toThrowError function in the Jasmine framework to test if a thrown error has a specific name? Currently, my JavaScript looks like the following:

    function getRandomNumber(max) {
      if ((!isNaN(parseFloat(max)) && isFinite(max)) === false) {
        var error = new Error('You must provide a number');
        error.name = 'ArgumentException';
        throw error;
      }
    
      if ((max === null) || (max < 1) || (max > 100)) {
        var error = new Error('The maximum value must be greater than 0 and less than 100.');
        error.name = 'ArgumentOutOfRangeException';
        throw error;
      }
    
      return Math.floor(Math.random() * max) + 1;
    }
    
    function ArgumentException(message) {
      this.name = 'ArgumentException';
      this.message = message || '';
    }
    ArgumentException.prototype = new Error();
    ArgumentException.prototype.constructor = ArgumentException;
    

    How can I write a Jasmine test that checks for an ArgumentException error or an ArgumentOutOfRangeException error?

    Thank you!

    • ltrainpr
      ltrainpr almost 9 years
      Just wanted to throw this out there: I was getting toThrowError is not a function failure while using the jasmine-node npm package. Turns out the Jasmine version used is 1.3 and does not support toThrowError. Use toThrow(new Error('the error')) instead.
  • user3192178
    user3192178 over 10 years
    Hello, thank you for your comment. You mentioned that there is a matcher with 1 parameter that takes an exception type. Can you please show an example of how that works? I feel like I'm doing something wrong and I have been unsuccessful in getting that approach to work.
  • user3192178
    user3192178 over 10 years
    THank you for the update. Will that actually work? When I tried it, I got an error that says: "Error: Expected is not an Error, string, or RegExp.". Or am I doing something wrong on my end? Thank you!
  • user3037143
    user3037143 over 10 years
    i have tried the code with jasmine2.0 and then only updated the answer . Are you using the same code as is?
  • user3192178
    user3192178 over 10 years
    I am using the same code. I used the code in Chrome. Is that the problem?
  • user3037143
    user3037143 over 10 years
    I am also using chrome. Can you debug it in chrome, let me explain the flow. (1) Add a break point at extractExpectedParams() function in jasmine.js (2) it will internally call checkForAnErrorType() function (2) This function checks the whether passed object is a type of Error object, if this case, it should return true --- in your case, errorType variable is not set, which is why it is throwing the mentioned error. Can you check the same flow and let me know what is the trace?
  • user3192178
    user3192178 over 10 years
    Thank you for sticking with me. I know where our confusion is coming from. In your example you use SyntaxError, which is a built-in object. (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…‌​). However, I'm trying to use a custom type that I create, ArgumentException. I've updated my code sample to include the definition of ArgumentException. We're so close!
  • user3037143
    user3037143 over 10 years
    Can you try "throw new ArgumentException('message');" instead of your using "Error" object and modifying the name? i have modified the same in the answer.
  • user3192178
    user3192178 over 10 years
    Wow. Thank you so much for staying with me on this one. I really appreciate your help. The problem has been solved!