user2867106
user2867106

Reputation: 1131

mocha: how to call async functions in after()?

I'm writing a test that verifies the creation of models and then after the describe, it releases all the resources.

My problem is that 'done()' is called more than once, it is obvious why, but how can I implement such functionality and call done only once? both functions are async!

The test structure and async calls:

describe('create models', function() {
     it('...', function(done) {...});
});
after(function(done) {
         dbDestroyCenter('param1','param2')(done);
         dbDestroyCenter('param1','param2')(done);
});

The delete function:

function dbDestroyCenter(centerState, centerName) {
    return function (done) {
        State.findOne({ name: centerState }).exec(function (err, state) {

            if (err) return done(err);
            expect(state).not.to.be.an('undefined');

            Center.destroy({ state: state.id, name: centerName }).exec(function(err) {
                if (err) return done(err);
                return done();
            });
        });
    };
}

One possibility is to use async.parallel from https://github.com/caolan/async, but I am not sure Mocha doesn't provide solution for this. Any ideas?

Upvotes: 1

Views: 334

Answers (1)

Louis
Louis

Reputation: 151491

Pass your own callback to the function returned by your dbDestroyCenter function and keep a count. Once you its been called the number of times you expect, you're done and can call done.

after(function(done) {
    // Initialize to the number of things to destroy.
    var to_destroy = 2;
    function destroyed(err) {
        // Terminate immediately if there's an error.
        if (err)
            done(err);

        // If there's nothing left to destroy, then call done().
        if (!--to_destroy)
            done();
    }

    dbDestroyCenter('param1','param2')(destroyed);
    dbDestroyCenter('param1','param2')(destroyed);
});

This is the general principle.

Upvotes: 2

Related Questions