user348173
user348173

Reputation: 9278

Properly call mocha done callback and promises

I have several integration tests in my app:

 it('creating vehicle', function (done) {
    createVehicle()         
      .then(() => {
        done();
      })
      .catch((err) => {
        done(err);
      });
  });

createVehicle makes post request and returns promise:

 return request.json('post', '/api/vehicle/')
    .send(obj)
    .expect(200)
    .then((res) => {
      expect(res.body).toExist("Body is empty");
      expect(res.body.id).toExist("Id is empty");     
      return res.body;
    });

Now all works fine, but if I rewrite first snippet in the following way:

it('creating vehicle', function (done) {
        createVehicle()         
          .then(done) //*
          .catch(done); //*
      });

I get error from Mocha

done() invoked with non-Error

I understand why. The createVehicle return res.body and it's passed to then callback, in result done run as done(arg) and I get the error, because mocha done callback has to be called without arg when there is no error and with argument when there is error.

Is it possible to use this variant:

 .then(done) 
 .catch(done); 

How to achieve this?

Of course, I can delete return statement, but createVehicle is used in several places and I need returned value:

it('creating vehicle with media', function (done) {
    createVehicle()
       .then(createMedia)  //createMedia will get returned value       
      //....
  });

Upvotes: 0

Views: 110

Answers (1)

robertklep
robertklep

Reputation: 203304

The easiest solution would be to just return the promise instead of having to deal with callbacks, because Mocha supports promises out-of-the-box:

it('creating vehicle', function() {
  return createVehicle();
});

Upvotes: 1

Related Questions