tj / should.js

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

throw() should allow for optional arguments #121

Closed GabeIsman closed 11 years ago

GabeIsman commented 11 years ago

I'm new to should so forgive me if I'm missing something. I was trying to use throw() to test that a function throws an exception when passed specific arguments, and there didn't seem to be a way to do it. Specifically:

(function(n) {
    if (n < 0) throw new Error("Does not accept negative numbers");
    // do stuff
}).should.throw("Does not accept negative numbers"); // doesn't work

Maybe we could an optional second parameter to throw() that is a list of arguments to pass to the function. So we could do something like:

(function(n) {
    if (n < 0) throw new Error("Does not accept negative numbers");
    // do stuff
}).should.throw("Does not accept negative numbers", [-1]); // would work

Alternatively, we could define another function whenPassed() or something, that defines the arguments that should be passed to the function when invoked in throw. That would allow for a more natural syntax:

(function(n) {
    if (n < 0) throw new Error("Does not accept negative numbers");
    // do stuff
}).whenPassed(-1).should.throw("Does not accept negative numbers");

I like that one quite a bit. Did I miss something? Is there already a way to do this? Should I submit a pull request?

btd commented 11 years ago

I think something like this can be used:

> (function(n) {
...     if (n < 0) throw new Error("Does not accept negative numbers");
...     // do stuff
... }).bind(null, -1).should.throw()