Reputation: 251
QUnit has an assertion for testing that a function raises an exception (QUnit/raises). Is it possible -- using QUnit -- to assert that a function does not raise an exception.
I realize that it is possible to test it like in the following code:
try {
theTest();
ok(true);
} catch (e) {
ok(false, "Expected to succeed");
}
But I think it ought to be possible using QUnit. Any clues?
Upvotes: 19
Views: 5178
Reputation: 22339
I had the same issue as you mentioned in the comment whereby my test which tests no Error
is thrown would stop "badly" showing a badly formatted Died on test #1
message without any useful information.
I ended up using a mix of both; raises()
for one test and try/catch
for the other.
I used raises() for the test which tests that an Error
is thrown, similar to this:
test("When myFunction() is called with a invalid instance Then Error is thrown", function () {
// Arrange
var testInstance = {};
// Act
raises(function() {
myFunction(testInstance);
}, Error, "myFunction() should throw an Error");
// Assert
// raises() does assertion
});
If the above throws an Error
all is fine and if not a nice formatted message is displayed, similar to this:
myFunction() should throw Error
Result: No exception was thrown.
I then used try/catch
for the tests which have to ensure no Error
is thrown, similar to this:
test("When myFunction() is called with a valid instance Then no Error is thrown", function () {
// Arrange
var testInstance = new myObject();
var result;
// Act
try {
myFunction(testInstance);
result = true;
} catch(error) {
result = false;
}
// Assert
ok(result, "myFunction() should not throw an Error");
});
If the above throws no Error
all is fine and if an Error
is thrown a nice formatted message is displayed, similar to this:
myFunction() should not throw an Error
Source: ...
Upvotes: 2
Reputation: 19858
There is no such method in qunit
However, if you just write the following code which is much shorter, you will obtain the same result with additionnal benefits
theTest();
ok(true, "My function does not crash");
1/ If the code of a test raises an exception, qunit will mark the test as failed.
2/ If you check the "no try/catch" checkbox, you will be able to debug where the exception was thrown, which is not the case with your try/catch
Upvotes: 18