【问题标题】:Node.js Mocha async test doesn't return from callbacksNode.js Mocha 异步测试不会从回调中返回
【发布时间】:2013-06-13 15:21:30
【问题描述】:

我完全不知道如何在 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();
        }]);

    });

【问题讨论】:

    标签: node.js amazon-web-services amazon-s3 mocha.js


    【解决方案1】:

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

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

    你需要在console.log(res)下方添加done()

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

    【讨论】:

    • 我应该提到 - 我试过了。我用异步控制更新了代码。在这个版本中,内部回调返回,然后代码挂起,因为我没有添加 done() - 但是,无论我在哪里添加 done() - 代码要么在没有回调的情况下完成,要么没有 done() 的错误被多次调用。
    • 我的问题变得一团糟,所以我进行了大量编辑。很抱歉有任何混淆。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2017-05-21
      • 1970-01-01
      • 2015-12-23
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多