We have a method which takes as arguments a potential error triggered a level higher. We want to test
handleFailure((msg, err) => {
if (err) throw err // preserve stack
console.error(msg);
process.exit(1);
})
We want to test, in case there is an error, that the error is thrown. We tried this:
it('should throw error', () => {
let error = new Error('someError');
expect(handleFailure('some message', error)).to.throw(error);
});
The error is thrown, I can see it in console. But it's not "captured" by the unit test:
1 failing
1) command processor
handleFailure method
should throw error:
Error: someError
at Context.it (tests/commandProcessor.spec.js:111:39)
How can we test the error is thrown using sinon and chai?
The problem with your code is, expect is never called as the error is thrown before returning from handleFailure.
One way you can handle it is by wrapping your code in an anonymous function as below.
it('should throw error', () => {
let error = new Error('someError');
expect(function(){handleFailure('some message', error)}).to.throw(error);
});