gpt4 book ai didi

javascript - Chai 期望 [Function] 抛出一个(错误)未通过测试(使用 Node)

转载 作者:搜寻专家 更新时间:2023-11-01 00:01:38 25 4
gpt4 key购买 nike

问题:

我正在使用 Chai 进行测试,但我似乎一直在测试预期的错误:

Chai 预计 [Function] 会抛出一个(错误)

当前代码:

测试代码如下:

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 函数的多种变体(包括调用匿名函数:

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

绑定(bind),如示例中提供的那样,

和最基本的

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

我还尝试将“未找到记录”中的 throw 参数替换为多项内容,包括将输入定向到已创建的错误 (Error),并在参数中创建一个新错误 (new Error('Record not found '));

可能的原因:

我怀疑没有抛出错误,因为测试需要一段时间才能与数据库通信以删除记录,但我不确定如何补救。

此外,似乎在此测试之后立即运行的测试实际上返回了应该在此测试中返回的错误。

最佳答案

鉴于(来自评论)tableService.deleteEntity 是异步的,不可能测试 throw。并且代码本身是无效的。因为抛出的异常不会被捕获,所以它不会被处理,因为它是在不同的 tick 中抛出的。阅读更多关于 Asynchronous error handling in JavaScript 的信息和 unhandled exceptions in Node.js

换句话说,无法测试这样的函数是否会抛出错误:

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

关于javascript - Chai 期望 [Function] 抛出一个(错误)未通过测试(使用 Node),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com