tj / should.js

BDD style assertions for node.js -- test framework agnostic
MIT License
2.75k stars 195 forks source link

Allow for providing arguments directly to throw #70

Closed skabbes closed 12 years ago

skabbes commented 12 years ago

This is very helpful for testing functions which can throw different types of errors, or which should conditionally throw

var throwsSometimes = function(a){
  if( a === 1 ){
    throw new Error('invalid argument');
  }
};

throwsSometimes.should.throw(1, /^invalid/);
throwsSometimes.should.not.throw(50, /^invalid/);
floatingLomas commented 12 years ago

Seriously, this would be good.

I want to do this:

var result = testDevice.create.should.throwError({}, 'Invalid data.');

Or this...

var result = testDevice.create.should.throwError('Invalid data.').given({});

But my current solution of this...

var error = {};

try {
    var result = testDevice.create({});
} catch(e) {
    error = e;
};

(function () {
    if(error) throw error;
}).should.throwError('Invalid data.');

...Looks so yucky. It works, but ... yucky.

PS: Certainly open to a better way to do it given the current approach, if one exists.

tj commented 12 years ago

the anonymous function was just supposed to be a wrapper:

(function(){
  my.method(to, test, here)
}).should.throw(whatever)
skabbes commented 12 years ago

this would also work:

my.method.bind(my, to, test, here).should.throw(whatever);

or for @floatingLomas 's example

testDevice.create.bind(testDevice, {}).should.throw('Invalid data.');

If there's no plan to merge this, let's just close it, ya?

floatingLomas commented 12 years ago

Ya, I just realized that the anonymous function makes so much more sense. It would be nice if that were a bit clearer in the 'throws()' section of the documentation - maybe with an example. It makes perfect sense now, but it sure didn't at first.