问题:
我正在使用 Chai 进行测试,但我似乎无法测试预期的错误:
柴期望 [函数] 抛出一个(错误)
当前代码:
以下是测试的代码:
describe('Do something', function () {
it('should remove a record from the table', function (done) {
storage.delete(ID, done);
});
it('should throw an error when the lookup fails', function () {
expect(storage.delete.bind(storage, ID)).to.throw('Record not found');
});
});
下面是函数的代码:
delete: function (id, callback) {
// Generate a Visitor object
visitor = new Visitor(id);
/* Delete the visitor that matches the queue an
cookie provided. */
tableService.deleteEntity(function (error, response) {
// If successful, go on.
if (!error) {
// Do something on success.
}
// If unsuccessful, log error.
else {
if (error.code === 'ResourceNotFound') {
throw new Error('Record not found');
}
// For unexpected errros.
else {
throw new Error('Table service error (delete): ' + error);
}
}
if (callback) callback();
});
},
尝试的解决方案:
我已经尝试了调用期望函数的多种变体(包括调用匿名函数:
expect(function() {storage.delete(ID);}).to.throw('Record not found');
绑定,如示例中提供,
和基本之一
expect(storage.delete(ID)).to.throw('Record not found');
我还尝试将 throw 参数从"未找到记录"替换为多种内容,包括将输入定向到已创建的错误(错误),并在参数中创建新错误(新错误("未找到记录"));
可能的原因:
我怀疑错误没有被抛出,因为测试需要一段时间才能与数据库通信以删除记录,但是我不确定如何补救。
此外,似乎在此测试之后运行的测试实际上返回了应该在此测试中返回的错误。
鉴于(从注释中)tableService.deleteEntity
是异步的,因此不可能测试该throw
。并且代码本身是无效的。由于不会捕获引发的异常,因此它将在以不同的刻度引发时未处理。阅读有关 JavaScript 中的异步错误处理和 Node 中未经处理的异常的更多信息.js
换句话说,这样的函数不能被测试抛出错误:
function behaveBad(){
setTimeout(function(){
throw new Error('Bad. Don't do this');
}, 50);
}