UPDATE 2-July-2013
Using the latter approach with an anonymous function wrapped up can lead to some weird testing. If you expect a flawed error, but there is an error in the actual execution, the test will pass, but will pass any error and possibly not the one you expected. I do two things, if this is an error that I indicate, I guarantee that the text of the error will return from the stub and the error will be the same. If it is from a third-party library, where I do not necessarily know the errors, I will put some arbitrary value so that I know that the passes are related to the units that I am testing. An example of using sinon.js to drown out a bit of schiz.
it('should return an error if the save fails', function(){ stubCall.restore(); stubCall = sinon.stub(Provider, 'save').callsArgWith(1, new Error('Save Error')); (function(){ User.create(fakeUser, function(err, user){ if(err) throw err; }); }).should.throw("Save Error"); });
I get into Node.js and try to do some behavior-driven (BDD) development with Mocha and should.js (and sins there too at some point).
I have problems testing the errors returned by the callback, for example this simple test:
it('should return an error if you try and execute an invalid Query object', function () { var stubQuery = {}; Provider.execute(stubQuery, function (err) {
with function:
PostgresqlProvider.prototype.execute = function (query, cb) {
};
It doesn't matter what I'm trying to test, the test always passes (should.exist, etc.), and the only way I can get it is to add cb (null); into the execution function, which seems to run counter to what I do when I try to test, before adding behavior, and not adding behavior to reject the test.
I know that I am making some kind of real newb error, perhaps at several levels, but I donβt understand how the error passed as a callback is tested, it is not thrown (which Iβm sure I could test easier)!
UPDATE
Using the code from Herman, I adjusted and that really words (the test does not work without specific behavior)
it('should return an error if you try and execute an invalid Query object', function () { var stubQuery = {}; Provider.execute(stubQuery, function (err) { if (err) throw new Error(err); }).should.throw(); });
the problem is that I cannot "catch" the error, if sent in the callback to pass the test, the should.throw method is not called, it just claims that the expected throw to happen, but didnt even though I return the error for a callback from my method. It may be, but I'm not sure that I should add some form of closure and at what level.
UPDATE 2
It turned out that I needed to wrap the function call inside the closure, not the callback (Doh!), And then put the assert (should.throw) command at the end of the closure;
it('should return an error if you try and execute an invalid Query object', function () { var stubQuery = {}; (function(){ Provider.execute(stubQuery, function (err) { if (err) throw err; }); }).should.throw(); });