0

我对如何在 Mocha 测试中包装嵌套的异步回调完全感到困惑。这是有问题的代码示例:它正在调用 Amazon S3 来检查文件是否存在:

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
    });
});

要么代码挂起等待完成(如果我省略 done() ) - 或者,代码在没有回调的情况下完成,或者,节点抱怨 done() 被多次调用。

在下面的帮助下,我有点让它工作了,但它看起来像异步巫毒炖菜

 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();
        }]);

    });
4

2 回答 2

1

您需要使用 mocha 中的异步支持。尝试将 done 添加到以下行:

describe('Should show uploaded  files to amazon s3', function (done) {

并且您需要done()console.log(res).

文档在这里:http: //visionmedia.github.io/mocha/#asynchronous-code

于 2013-06-17T18:00:00.460 回答
1

尝试使用 async.serial。在第一个条目中,使用 async.each 运行多个循环。在第二个条目中,放入 done()。

于 2013-06-17T23:39:31.697 回答