The following mocha it statement:
it('should do truthy and falsey things', function() {
var val = true;
assert.equal(val, true, "true should be true!");
console.log('state 1:', val);
val != val;
assert.equal(true, false, "should continue running even after failing");
console.log('state 2:', val);
val != val;
assert.equal(false, false, "false should be false!");
});
results in the following log:
state 1: true
1) should do truthy and falsey things
And that's it. Once the second assert fails, the rest of the function doesn't run.
Is it possible to have the rest of the function (in this case, the last three lines), and if so, how?
The most direct way to prevent an assertion failure from ending the test right there would be to catch the exception thrown by the failure and rethrow it later. However, I do not recommend doing this because this creates complications. If more than one test fails, which exception are you going to rethrow? Also, you have to remember to rethrow the exception you caught, otherwise the test will seem to be passing.
Generally I just live with the fact that if I have a test with multiple assertions then the the test will stop on the first failure. In cases where I cannot live with it, I've generally adopted a strategy of recording checks into a structure and then comparing the structure to an expected value at the very end of the test. There are many ways a structure can be constructed. Here's an example:
it('should allow multiple tests', function () {
var expected = {
"something should be true": true,
"something should be false": false,
"forgot this one": 1
};
var actual = {};
var thing_to_test = true;
// First test
actual["something should be true"] = thing_to_test;
// Second test
actual["something should be false"] = thing_to_test;
// We forget the third test.
assert.equal(actual, expected);
});
When I run the test above, I get the following output:
1) should allow multiple tests
0 passing (12ms)
1 failing
1) should allow multiple tests:
AssertionError: { 'something should be true': true,
'something should be false': true } == { 'something should be true': true,
'something should be false': false,
'forgot this one': 1 }
+ expected - actual
{
- "something should be false": true
+ "forgot this one": 1
+ "something should be false": false
"something should be true": true
}
at Context.<anonymous> (test.js:22:12)
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