Search code examples
javascriptnpmmocha.jsnpm-request

How to call (NPM) request multiple times in mocha before hook?


I would like to call request multiple time (2 times) in mocha before hook. Is there a correct procedure/way to call them. My current usage is like this and I get error done() called too many times.

describe('...', function(){
  before(function(done){
    request({
       ...
    }, function(err,res,body){
       ...
       done(); //also tried by removing it.
    });

    //request 2
    request({
       ...
    }, function(err,res,body){
       ...
       done();
    });
  });
  //it block follows
});

Solution

  • You'd need to wait for all of the requests and only call done when they are all complete.

    var requestAComplete = false, requestBComplete = false;
    
    function checkDone() {
        if (requestAComplete && requestBComplete) {
            done();
        }
    }
    
    describe('...', function(){
      before(function(done){
        request({ ... }, function(err,res,body){
           ...
           requestAComplete = true;
           checkDone();
        });
    
        //request 2
        request({ ... }, function(err,res,body){
           requestBComplete = true;
           checkDone();
        });
      });
      //it block follows
    });
    

    Of course if you need more of them, you should use an array or a dictionary to track the statuses, and check with a loop. (or perhaps remove from the collection).

    Alternatively, as a better but more advanced solution, wrap both requests into array of promises, convert into a promise of an array with all and call done when it resolves.