qunit - test exception message?
Asked Answered
G

1

10

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?

Gentry answered 6/5, 2011 at 17:11 Comment(2)
Isn't QUnit's throws doing that?Studied
throws work, but, for some reason, it doesn't validate the exception message.Epigraph
G
18

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'
);
Gentry answered 6/5, 2011 at 18:30 Comment(1)
Yeah, I independently found this one--it's an undocumented feature as far as I can tellFionafionna

© 2022 - 2024 — McMap. All rights reserved.