Testing if JS method throws RangeError with QUnit

风流意气都作罢 提交于 2019-12-23 23:12:06

问题


I made some Javascript unit tests with QUnit library, then I want to test if method throws RangeError. It has be done in this way:

QUnit.test("Resolve slide animation from left", function( assert ) {
var myOwnCreator = new MyOwnCreator();
assert.equal(myOwnCreator.resolveAnimationType("slideSide", "show", "left"),
  "slide-left-in");
assert.equal(myOwnCreator.resolveAnimationType("slideSide", "hide", "left"),
  "slide-left-out");
assert.throws(myOwnCreator.resolveAnimationType("slideSide", "hide"), 
  new RangeError(),
  " If animation type is 'slideSide', you have to provide correct direction" 
  + "to identify animation properly, direction cannot be 'undefined'");
});

First and second test passed, because animation classes resolved by function (,,slide-...") were ok. But third test died:

Died on test #3     at file...

Because it throws RangeError. It's ok that it throws RangeError, but I don't understand how I can catch it in unit test, to get ,,ok" information. If I understand QUnit documentation: QUnit throws documentation

I do everything ok: I pass function which throws Error, instance of expected Error and expected message. I anybody would decide to help me, I will be very happy - thank you in advance.


回答1:


I found an answer on my own. Instead calling function:

assert.throws(myOwnCreator.resolveAnimationType("slideSide", "hide"), 
  new RangeError()....

I should pass to assert.throws() function which call my function, like this:

assert.throws(function(){
    myOwnCreator.resolveAnimationType("slideSide", "hide");
  }, 
  new RangeError(--message which function should throw in error--)...


来源:https://stackoverflow.com/questions/26439824/testing-if-js-method-throws-rangeerror-with-qunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!