简体   繁体   中英

Async callback doesn't get called

I have a frustrating problem. I am trying to extract a function that is used in many classes. Doing this gives me problems with the 'done'-callback. Here is my code:

I have extracted the function and added it to util.js:

var chai = require('chai');
var expect = chai.expect;
var util = exports = module.exports = {};

chai.use(require('chai-http'));
chai.use(require('chai-string'));

util.testAsyncCalls = function testAsyncCalls(urlArray, urlSuffix, result, callback) {
    async.each(urlArray, function (url, callback) {
        chai.request(url)
            .get(urlSuffix)
            .then(function (res) {
                expect(res).to.have.status(200);
                expect(res.body.totalStatus, res.body.summary).to.equalIgnoreCase(result);
                callback();
            })
            .catch(function (err) {
                callback(err);
            });
    });
};

Then, in the test itself, I call the function like below:

 var config = require(process.env.CONFIG || '../env.json'),
   util = require('../util.js');
    describe('App', function () {
        it('Is /home ok ?', function(done) {
            util.testAsyncCalls(config.url.applications, '/home/info', 'SUCCESS', done);
        })
    });

Running the test via mocha gives me the following error:

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

When I perform a normal get on the url, I get a valid response so I assume the callback is the problem. Can anybody help?

Thanks in advance. Regards

You must call your "global" callback at the end of the each, look at the each signature

util.testAsyncCalls = function testAsyncCalls(urlArray, urlSuffix, result, callback) {
    async.each(urlArray, function (url, next) {
        chai.request(url)
        .get(urlSuffix)
        .then(function (res) {
            expect(res).to.have.status(200);
            expect(res.body.totalStatus, res.body.summary).to.equalIgnoreCase(result);
            next();
        })
        .catch(function (err) {
            next(err);
        });
    }, callback);
};

As a good practice, don't use the same name for callback in sub scopes, use 'next' for example in your each instead of 'callback'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM