dimanche 25 janvier 2015

QUnit terminates when function with arg throws unless wrapped in anon function

I am using QUnit to test a function which throws an error in the case of invalid inputs. I am able to test this function by embedding it within an anonymous function, but am unsure why this is necessary. If I don't do this, QUnit reports:



Died on test #4 at http://localhost:8000/qunit/throwsTest.js:1:7: sometimesThrows


Notably, this message includes the thrown error.


I have also noticed that I can make functions that don't require args work if I pass the function as an argument rather than invoke it.


Check out my fiddle to see it live.



QUnit.test("throws test", function(assert) {
function alwaysThrows() { throw "alwaysThrows"; }

function sometimesThrows(foo) {
if (foo) {
return true;
}
else {
throw "sometimesThrows";
}
}

assert.throws(alwaysThrows, "alwaysThrows throws (works)")

assert.ok(sometimesThrows(true), "sometimesThows doesn't throw (works)");
assert.throws(function() {
sometimesThrows(false);
}, "sometimesThrows throws inside anonymous function (works)");

// Where the unexpected behavior occurs.
// The error _is_ being thrown being thrown.
assert.throws(sometimesThrows(false), "sometimesThrows throws (terminates)");

});


If wrapping the function to be tested in an anonymous function is the intended method for getting this to work, if someone could explain why, I would find that illuminating in developing my intuition.


Aucun commentaire:

Enregistrer un commentaire