Node.js Mocha 异步测试不会从回调返回 [英] Node.js Mocha async test doesn't return from callbacks

查看:37
本文介绍了Node.js Mocha 异步测试不会从回调返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

    });

推荐答案

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

Try using async.serial. Inside the first entry, use async.each to run through multiple loops. In the second entry, put done().

这篇关于Node.js Mocha 异步测试不会从回调返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆