How to assert.throws on an async function with a callback

Recently, I was writing a module that took a callback, and needed to write a test, asserting on an exception.

Here’s how to do it:

it('throws error if myParam is less than 10', function(done) {
  var fn = function(){
    myModule.doSomething(8, function(err) {
      if (err) throw err
    });
  }

  assert.throws( function() { fn() }, /Value is less than 10/ )
  done();
});

Assuming our module looks something like this:

module.exports.doSomething = function(value, callback){
  if(value < 10)
    throw new Error('Value is less than 10/');

  //do some stuff
  callback();
};

Leave a Reply

Your email address will not be published. Required fields are marked *