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?
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
assertRaises(exception, callable, *args, **kwds) Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.
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
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: ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With