简体   繁体   中英

Handle Promise rejection case Mocha

If I comment the line return Promise.reject(err); in my findGood function, the test case should fail. Meaning that, if I'm not returning from my function, the catch block in the test should be undefined .

var findGood = function (name) {

    return goodModel.findByName(name)
        .then( (result) => {

            ....
            return result;


        })
        .catch( (err) => {          
            return Promise.reject(err);
        }); 
};

Here is a test

it('good not found', function () {

   var goodModelStub = sinon.stub(goodModel, 'findByName');

   var error = 'Good not found';

   goodModelStub.returns(Promise.reject(error));

   return goodFinder.findGood('Sony')
     .catch(function (err) {
         assert.equal(err, error);
  });

});

First there's no need to catch an error and then throw it again, handle the rejection in the proper place (your test case in this instance)

findGood returns a Promise so why not use chai-as-promised

it('good not found', function () { 
   var goodModelStub = sinon.stub(goodModel, 'findByName');

   var error = 'Good not found';

   goodModelStub.returns(Promise.reject(error));

   return goodFinder.findGood('Sony').should.be.rejected
  });
});

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