使用异步时未输入 .end() 函数

.end() function not entered when using async

我正在使用 supertest 和 async 来测试一些网站。 当我用 mocha 执行测试时,没有进入 end 函数。 我在结束函数中添加了一些日志记录,但没有打印出来。 当我删除 async.each 时,结束函数 ,因为我看到了日志记录。知道什么似乎是错的吗? 超测不兼容async吗?

这是我的代码:

describe('Era', function() {
it('Does era run?', function(done) {
    async.each(config.url.era, function(url) {
        console.log('Opening connection to ' + url);
        request(url).get('/rest/status').expect(200).end(function(err, res) {
            console.log(err);
            if(err) return done(err);
            console.log('Time to assert some stuff');
            assert.equal(res.text.indexOf('up') > -1, 'Node ' + url + ' failed with status ' + res.statusCode);
        });
    });
    done();
});

我认为你需要调用回调 done:

it('Does era run?', function(done) {
    async.each(config.url.era, function(url) {
        console.log('Opening connection to ' + url);
        request(url).get('/rest/status').expect(200).end(function(err, res) {
            console.log(err);
            if(err) return done(err);
            console.log('Time to assert some stuff');
            assert.equal(res.text.indexOf('up') > -1, 'Node ' + url + ' failed with status ' + res.statusCode);
        });
        // call at end of each async call
        done();
   });
});

async.each() 期待每次迭代的回调继续进行。此外,async.each() 末尾的可选回调可用于调用 done()。这是修改后的代码:

describe('Era', function() {
    it('Does era run?', function(done) {
        async.each(config.url.era, function(url, eachCb) {
            console.log('Opening connection to ' + url);
            request(url).get('/rest/status').expect(200).end(function(err, res) {
                console.log(err);
                if (err) return eachCb(err);  // terminate the loop
                console.log('Time to assert some stuff');
                assert.equal(res.text.indexOf('up') > -1, 'Node ' + url + ' failed with status ' + res.statusCode);
                eachCb(null);  // continue with the next iteration
            });
        }, function(err) {
            if (err) {
                return done(err);
            }
            done();
            // the above 2 statements can be simplify for just
            // done(err);  // err is an error or null
        });
    });
});

以上代码可以简化为:

describe('Era', function() {
    it('Does era run?', function(done) {
        async.each(config.url.era, function(url, eachCb) {
            console.log('Opening connection to ' + url);
            request(url).get('/rest/status').expect(200).end(function(err, res) {
                console.log(err);
                if (err) return eachCb(err); // terminate the loop
                console.log('Time to assert some stuff');
                assert.equal(res.text.indexOf('up') > -1, 'Node ' + url + ' failed with status ' + res.statusCode);
                eachCb(null);  // continue with the next iteration
            });
        }, done);  // async.each() will call done() with err or null as argument
    });
});