I'm using a before block in a set of mocha unit tests and within them I'm iterating over a set of calls to get information from a REST API. I'm using chai-http to do this. However I am running into the problem that the done()
method is being called before the series of n requests I make have completed. Calling done in the end block results in multiple done()
calls but putting outside of the block means it's called before I'm really done! Here is an example of before block:
var flags = [];
var groups = [];
// This functions correctly 1 done() called at the end
before(function(done) {
chai.request(server)
.get('/groups')
.end(function(err, res){
groups = JSON.parse(res.text);
done();
});
});
before(function(done) {
groups.forEach(function(rec) {
chai.request(server)
.get('/groups/' + rec.KEYWORD_GROUP_ID + '/groupflags')
.end(function(res, err) {
Array.prototype.push.apply(flags, JSON.parse(res.text));
// A done() here gets called n times
});
// But here it's called before the requests all end
done();
});
Is there a way of detecting when all of these requests have completed then I can call a single done()
to ensure my tests are only executed with the correct context set up?
You could try with async.whilst()
. Count up a counter to groups.length and then hit done()
in the callback. Link to the function documentation: (http://caolan.github.io/async/docs.html#whilst)
Something like...
let counter = 0;
async.whilst(
() => {
// Test if we have processed all records
return counter < groups.length;
},
(callback) => {
let rec = groups[counter++]; // Sorry Douglas
chai.request(server)
.get('/groups/' + rec.KEYWORD_GROUP_ID + '/groupflags')
.end(function (res, err) {
Array.prototype.push.apply(flags, JSON.parse(res.text));
callback(null, counter);
});
},
(err) => {
assert(!err, err);
done();
}
);