柴期望抛出一个(错误)不通过testing(使用节点)

问题是:

我正在使用Chai来做testing,而且我似乎被卡住在testing一个预期的错误:

柴期待[function]抛出(错误)

当前代码:

这是testing的代码:

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

尝试解决scheme:

我已经尝试了调用expect函数的多种变体(包括调用匿名函数:

 expect(function() {storage.delete(ID);}).to.throw('Record not found'); 

绑定,如示例中所提供的,

和基本的一个

 expect(storage.delete(ID)).to.throw('Record not found'); 

我也尝试用'logging未find'代替throw参数,包括将input指向已经创build的错误(Error),并在参数中创build一个新的错误(new Error('Record not found')) ;

可能的原因:

我怀疑错误没有被抛出,因为testing需要一段时间才能与数据库进行通信来删除logging,但是我不确定如何解决这个问题。

另外,看起来在这个testing之后运行的testing实际上返回了这个testing应该返回的错误。

鉴于(从评论) tableService.deleteEntity是asynchronous的,这是不可能的,testingthrow 。 而代码本身是无效的。 因为抛出的exception不会被捕获,所以它会被抛出一个不同的滴答。 详细了解JavaScript中的asynchronouserror handling和Node.js中未处理的exception

换句话说,这样的函数不能testing抛出错误:

 function behaveBad(){ setTimeout(function(){ throw new Error('Bad. Don\'t do this'); }, 50); }