Catching thrown errors with SinonJS

拜拜、爱过 提交于 2019-12-05 21:41:12

It appears that this works inside a try/catch:

function foo() { throw new Error("hey!"); }
var fooSpy = sinon.spy(foo);
try {
  fooSpy();
} catch (e) {
  // pass
}
assert(fooSpy.threw());

Note that you have to call fooSpy, not foo itself.

But also note that .should.be.true() is not part of Sinon, so you're probably already using Chai or a similar library, in which case the expect(foo).to.have.thrown() or assert.throws(foo, someError) syntax seems much nicer.

Update: If you're using ShouldJS, looks like you can use should.throws. I still think this is nicer than using the Sinon version for this purpose.

Revised

Following @nrabinowitz's helpful advice, here's a solution that uses should.throws. This avoids using Sinon.spy altogether.

describe('#testError', function() {
  it('throws an error', function() {
    should.throws(function() {
      testError(false);
    });
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!