Skip to content Skip to sidebar Skip to footer

Mocha Flow Control After Assertion Fails

I think mocha stops running the current test case after assertion fails, like this it('test', function(done) { a.should.equal(b); //if a is not equal to be, won't go here

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.optshttps://mochajs.org/api/mocha

Post a Comment for "Mocha Flow Control After Assertion Fails"