如何使用 chai 和 sinon 测试方法是否重新抛出现有错误
how to test that a method rethrow existing error using chai and sinon
我们有一个方法将触发更高级别的潜在错误作为参数。我们要测试
handleFailure((msg, err) => {
if (err) throw err // preserve stack
console.error(msg);
process.exit(1);
})
我们想要测试,以防出现错误时抛出错误。我们试过这个:
it('should throw error', () => {
let error = new Error('someError');
expect(handleFailure('some message', error)).to.throw(error);
});
抛出错误,我可以在控制台中看到它。但是单元测试不是"captured":
1 failing
1) command processor
handleFailure method
should throw error:
Error: someError
at Context.it (tests/commandProcessor.spec.js:111:39)
我们如何测试使用 sinon 和 chai 抛出的错误?
您的代码的问题是,从未调用 expect,因为在从 handleFailure 返回之前抛出错误。
处理它的一种方法是将代码包装在匿名函数中,如下所示。
it('should throw error', () => {
let error = new Error('someError');
expect(function(){handleFailure('some message', error)}).to.throw(error);
});
我们有一个方法将触发更高级别的潜在错误作为参数。我们要测试
handleFailure((msg, err) => {
if (err) throw err // preserve stack
console.error(msg);
process.exit(1);
})
我们想要测试,以防出现错误时抛出错误。我们试过这个:
it('should throw error', () => {
let error = new Error('someError');
expect(handleFailure('some message', error)).to.throw(error);
});
抛出错误,我可以在控制台中看到它。但是单元测试不是"captured":
1 failing
1) command processor
handleFailure method
should throw error:
Error: someError
at Context.it (tests/commandProcessor.spec.js:111:39)
我们如何测试使用 sinon 和 chai 抛出的错误?
您的代码的问题是,从未调用 expect,因为在从 handleFailure 返回之前抛出错误。
处理它的一种方法是将代码包装在匿名函数中,如下所示。
it('should throw error', () => {
let error = new Error('someError');
expect(function(){handleFailure('some message', error)}).to.throw(error);
});