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)
Going off @dm03514, set your file reader logic as a promise since you can't directly test throws asynchronously.
Then in your test suites.
Have a look at
chai-as-promised
: http://chaijs.com/plugins/chai-as-promised/