【问题标题】:How to test fs.writeFile errors with mocha + chai + sinon如何使用 mocha + chai + sinon 测试 fs.writeFile 错误
【发布时间】:2017-10-23 22:14:45
【问题描述】:

我想测试一下,如果在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;
  });
});

【问题讨论】:

  • 我想我也想测试一下确切的错误信息。

标签: node.js mocha.js sinon chai


【解决方案1】:

虽然不太理想,但是如果你存根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);
});

【讨论】:

    猜你喜欢
    • 2017-10-08
    • 2015-12-01
    • 2018-04-08
    • 2023-04-11
    • 2023-03-22
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多