【发布时间】:2017-09-05 05:25:45
【问题描述】:
我需要使用 Mocha 测试函数 testMe。但是当我的单元测试抛出错误时就会出现问题。这是一个简化的例子
function testMe(callback) {
new Promise((resolve, reject) => {
setTimeout(() => resolve([1,2,3]), 1000);
}).then((result) => {
callback(null, result);
}).catch((error) => {
callback(error, null)
});
}
testMe((err, result) => {
if(err) throw new Error();
if(result.length < 5) throw new Error();
});
在这个例子中,在 throw 运行 catch 块之后。但我只需要在拒绝后运行 catch 块。
编辑:
在这种情况下,脚本永远不会停止。我不明白为什么。
function testMe(callback) {
new Promise((resolve, reject) => {
setTimeout(() => resolve([1,2,3]), 1000);
}).then((result) => {
callback(null, result);
}, (error) => {
callback(error, null)
}).catch(() => {
console.log('Do not throw an error but still running');
});
}
testMe((err, result) => {
if(err) throw new Error();
if(result.length < 5) throw new Error();
});
【问题讨论】:
-
在使用 Promise 时不要使用回调参数!
-
但我需要使用它。因为在 testMe 中我使用的是 horseman API。
-
Use
.then(…, …)instead of.then(…).catch(…)避免调用callback两次,尽管这仍然不会让你例外;只是未经处理的拒绝。 -
不,您不需要将回调传递给
testMe- 您应该有testMereturn 一个承诺,然后用 mocha 进行检查。跨度> -
如果我使用 .then(..., ...) 而不是 .then().catch() 我收到 UnhandledPromiseRejectionWarning: Unhandled Promise RejectionWarning: Unhandled Promise Rejection (rejection id: 1): Error
标签: javascript node.js callback promise mocha.js