Reputation: 1995
I would like to test that if an error happens during fs.writeFile
a message is output to the console log. The below test do pass, but it outputs the stack trace of the error to the testing console, which is unwanted. How to avoid that?
describe('with fs error', () => {
it('should output errors to console', () => {
sandbox.stub(fs, 'writeFile').yields(new Error('write error'));
const consoleSpy = sandbox.spy(console, 'log');
history.save();
expect(consoleSpy).to.have.been.calledOnce;
});
});
Upvotes: 2
Views: 1696
Reputation: 203514
It's not ideal, but if you stub console.log
and immediately restore it after calling history.save
, you probably won't interfere with Mocha's use of console.log
:
it('should output errors to console', () => {
sandbox.stub(fs, 'writeFile').yields(new Error('write error'));
const consoleStub = sinon.stub(console, 'log');
history.save();
consoleStub.restore();
expect(consoleStub).to.have.been.calledOnce;
});
To test if the correct error was thrown:
it('should output the correct error to console', () => {
let error = new Error('write error');
sandbox.stub(fs, 'writeFile').yields(error);
const consoleStub = sinon.stub(console, 'log');
history.save();
consoleStub.restore();
expect(consoleStub).to.have.been.calledWith(error);
});
Upvotes: 3