Mocha Flow Control After Assertion Fails
Solution 1:
An after
hook will still get called when a test fails, so you can place your test inside a context that has such a hook:
describe('suite', function() {
after(function(done) {
// do somethingdone();
});
it('test', function(done) {
a.should.equal(b);
done();
}
});
Solution 2:
The reason it is being called twice is because the catch
is handling the exception, but the finally
block will always execute regardless of if the assertion throws an error.
Use return
to handle your scenario - if an exception is caught it will return done with the error, otherwise it will skip the catch and just return done()
.
try {
// test assertiona.should.equal(b)
} catch(e) {
// catch the error and return it
console.log(e)
return done(e)
}
// just return normally
return done()
If you need to use it in an if/else scenario you can handle it with a variable.
var theError = false;
try {
// test assertion
a.should.equal(b)
} catch(e) {
// indicate we caught an errorconsole.log(e)
theError = e
}
if (theError) {
// there was an exceptiondone(theError)
} else {
// no exceptions!done()
}
Solution 3:
Remember the finally will be executed either it fails or doesn't fail. That is why it executes the done twice.
You can do:
try {
a.should.equal(b)
} catch(e) {
console.log(e)
done(e)
}
done()
If it fails you will exit through the catch, otherwise you keep going and return normally.
Solution 4:
The test runner's job to decide if it should bail or continue to test the other tests in the suite.
If you want tests to continue running remove the --bail
from your mocha.opts
https://mochajs.org/api/mocha
Post a Comment for "Mocha Flow Control After Assertion Fails"