Currently, I have a function that reads a file. When I throw and test for an error outside of the readfile callback, it works:
var doWork = function(path) {
//throw new RangeError('blah'); // works, error is thrown
fs.readFile(path, 'utf-8', function(error, data) {
//etc.... logic.. etc..
if(data.split('\n')[0] > x)
throw new RangeError('blah'); //does not work
});
}
My tests:
describe('my test suite', function(){
it('should throw an error', function(){
var func = function() {
doWork('my path');
}
var err = new RangeError('blah');
expect(func).to.throw(err); //no error is thrown if "throw" is inside readFile cb
});
});
Results:
AssertionError: expected [Function: func] to throw RangeError
at Context.<anonymous> (test.js:53:27)
To handle errors asynchronously, you could use a callback, or promise, to notify the caller that an error occurs.
I think the issue is:
expect(func)is calledreadFileyields (because it's async) back to the testYou could change the call signature of
doWorkto accept a callback (conventionally passed error as a first argument and a result) as a second argument.I personally would recommend looking into promises, as I think that they are much cleaner looking, and easier to understand/work with. The should allow you to continue to throw, and to register an catch/error event to handle the exception.