3

I am writing a test suite that tests promise-returning functions. One common theme of these tests is the need to check if a promise-returning functions properly throws an error when passed invalid arguments. I have tried using should.throws, but in looking through the code I see it is not designed to work with promises.

I have made the following utility function to get the functionality I need:

var TestUtil = module.exports;
var should = require('should');

/**
 * Checks if a promise chain throws an error, and optionally that the error includes
 * the given errorMsg
 * @param promise {String} (optional) error message to check for
 * @param errorMsg
 */
TestUtil.throws = function(promise, errorMsg) {
  return promise
  .then(function(res) {
throw new Error(); // should never reach this point
  })
  .catch(function(e) {
if (errorMsg) {
  e.message.should.include(errorMsg);
}
should.exist(e);
  });
};

Does there exist a shouldjs function that does this same thing? I would like to keep my tests cohesive by only using the shouldjs api for checking, rather than using this one-off function.

almel
  • 7,178
  • 13
  • 45
  • 58

1 Answers1

1

As den bardadym said, what I'm looking for is .rejectedWith, which is one of shouldjs's promise assertion functions. You use it like so (copied directly from shouldjs's API documentation):

function failedPromise() {
  return new Promise(function(resolve, reject) {
    reject(new Error('boom'))
  })
}
failedPromise().should.be.rejectedWith(Error);
failedPromise().should.be.rejectedWith('boom');
failedPromise().should.be.rejectedWith(/boom/);
failedPromise().should.be.rejectedWith(Error, { message: 'boom' });
failedPromise().should.be.rejectedWith({ message: 'boom' });

// test example with mocha it is possible to return promise
it('is async', () => {
   return failedPromise().should.be.rejectedWith({ message: 'boom' });
});
almel
  • 7,178
  • 13
  • 45
  • 58