I’m utterly confused on how to wrap nested async callbacks in a Mocha test. Here is the offending code sample: It’s calling Amazon S3 to check that files exist:
var should = require('should'); var appConfig = require("../config.js"); var fs = require('fs'); var async = require('async'); var s3 = require('aws2js').load('s3', appConfig.awsAccessKeyId, appConfig.awsSecretAccessKey); s3.setBucket(appConfig.awsBucketName); var test_user_id = 590170571; var user_file_code = test_user_id * 2; var output_file_template = ['wordcloud_r', 'polarity_r', 'emot_cat_r']; describe('Should show uploaded files to amazon s3', function () { it.only('should upload three local graphics files to Amazon S3 bucket', function (done) { async.each(output_file_template, function (test_file, cb) { console.log(test_file); s3.head('reports/dsfsdf.dff', function (err, res) { if (err) { console.log(err) } console.log(res) cb(null); // done(); //nope }); // done(); //nope }); // done(); //nope }); });
Either code hangs waiting to complete (if I omit done() ) – or, the code completes without callbacks, or, node complains that done() was called multiple times.
With the help below, I sort of got it working, but it looks like asynchronous voodoo stew
it.only('should upload three local graphics files to Amazon S3 bucket', function (done) { async.series([function (callback) { async.each(output_file_template, function (test_file, cb) { console.log(test_file); s3.head('reports/dsfsdf.dff', function (err, res) { if (err) { console.log(err) } console.log(res) cb(); callback(); }); }); }, function (callback) { done(); callback(); }]); });
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try using async.serial. Inside the first entry, use async.each to run through multiple loops. In the second entry, put done().
Method 2
You need to use the asynchronous support in mocha. Try adding done to the following line:
describe('Should show uploaded files to amazon s3', function (done) {
and you need to add done()
below the console.log(res)
.
Documentation is here: http://visionmedia.github.io/mocha/#asynchronous-code
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0