问题
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