最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - qunit - test exception message? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked May 6, 2011 at 17:11 Philip SchweigerPhilip Schweiger 2,7341 gold badge18 silver badges27 bronze badges 2
  • Isn't QUnit's throws doing that? – Tim Büthe Commented Feb 27, 2013 at 12:48
  • throws work, but, for some reason, it doesn't validate the exception message. – Guilherme Garnier Commented Jul 16, 2013 at 18:28
Add a ment  | 

1 Answer 1

Reset to default 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'
);
发布评论

评论列表(0)

  1. 暂无评论