brandonscript
brandonscript

Reputation: 72825

Running mocha test loop synchronously

I'm running a mocha test loop on an array like so:

it('each should have permissions defined for each role', function(done) {
    async.forEach(_permissions, function(permission, callback) {
        log.debug(permission.permissions.should.be.an.instanceOf(Array).and.not.be.empty);
        callback(permission.permissions.should.be.an.instanceOf(Array).and.not.be.empty);
    },
    function(result) {
        log.debug(result);
        done();
    });
});

When I log it out, it appears to be running asynchronously even though I'm using the done() callback. Is this the case? Are my tests still being executed successfully, or is it only executing the first one and then returning a successful result?

Here's the console output:

[Tue Dec 02 2014 09:24:07 GMT-0800 (PST)] DEBUG { obj: [ 'permissions!' ], params: { operator: 'to be empty' }, negate: false }
    ✓ each should have permissions defined for each role // <- here's the test result
[Tue Dec 02 2014 09:24:07 GMT-0800 (PST)] DEBUG { obj: [ 'permissions!' ], params: { operator: 'to be empty' }, negate: false }
[Tue Dec 02 2014 09:24:07 GMT-0800 (PST)] DEBUG { obj: [ 'permissions!' ], params: { operator: 'to be empty' }, negate: false }
[Tue Dec 02 2014 09:24:07 GMT-0800 (PST)] DEBUG { obj: [ 'permissions!' ], params: { operator: 'to be empty' }, negate: false }

Upvotes: 0

Views: 620

Answers (1)

Andras
Andras

Reputation: 3055

use eachSeries, this got me too in the past. forEach is the parallel version.

Use like so:

it('each should have permissions defined for each role', function(done) {
    async.eachSeries(_permissions, function(permission, callback) {
        permission.permissions.should.be.an.instanceOf(Array).and.not.be.empty;
        callback();
    },
    function(err) {
        done();
    });
});

Upvotes: 1

Related Questions