Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qunit - test exception message?

So QUnit provides the "raise" assertion to test if an exception is thrown. Is there any way to test the actual message thrown by the exception, though? For instance, say I have this function:

throwError = function(arg) {
  var err = new Error();
  if (typeof arg === 'undefined') {
    err.message = 'missing parameter';
    throw err;
  }
}

I'd like to be able to write something along these lines:

raises(
  function(){throwError();},
  Error.message,
  'missing arg'
);

Ideally, this test would fail because the exception message is "missing parameter" and I expect it to be "missing arg," but it passes because qunit only checks that an error was raised. Any way to check the actual contents of the thrown exception?

like image 798
Philip Schweiger Avatar asked May 06 '11 17:05

Philip Schweiger


1 Answers

I figured out the answer, posting here in case others find it useful. Given this function:

throwError = function(arg) {
  var err = new Error();
  if (typeof arg === 'undefined') {
    err.message = 'missing parameter';
    throw err;
  }
}

The test would look like this:

raises(
  function(){
    throwError();
  },
  function(err) {
    return err.message === 'missing arg';
  },
  'optional - label for output here'
);
like image 137
Philip Schweiger Avatar answered Sep 28 '22 14:09

Philip Schweiger