如何使用 mocha + chai + sinon 测试 fs.writeFile 错误

How to test fs.writeFile errors with mocha + chai + sinon

我想测试如果在 fs.writeFile 期间发生错误,则会向控制台日志输出一条消息。下面的测试确实通过了,但是它将错误的堆栈跟踪输出到测试控制台,这是不需要的。如何避免这种情况?

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;
  });
});

不太理想,但如果你存根console.log并在调用history.save后立即恢复它,你可能不会干扰Mocha对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;
});

测试是否抛出了正确的错误:

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);
});