开发者

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 thr开发者_如何学编程own exception?


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'
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜