Mocha 测试抱怨未处理的承诺,但使用 async/await 和 catch 块
Mocha test complains about unhandled promise but using async/await with catch block
这些天我经常使用 async/await 但我有一个 mocha 测试,我正在测试以确保确实抛出错误。下面你可以看到 try/catch 块我必须捕获这个错误。绿色和灰色方块由 Wallaby(一种实时测试工具)插入,表示永远不会到达 catch 块。
当我从命令行 运行 mocha 时,我收到以下消息:
UnhandledPromiseRejectionWarning: FireModel::WrongRelationshipType: Can not use property "employer" on fancyperson with addToRelationship() because it is not a hasMany relationship [ relType: ownedBy, inverse: undefined ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().
addToRelationship()
的第一行检查关系类型是否正确(不正确)并抛出错误:
_errorIfNotHasManyReln
方法比较平淡,但为了完整起见,这里是:
protected _errorIfNotHasManyReln(
property: Extract<keyof T, string>,
fn: string
) {
if (this.META.property(property).relType !== "hasMany") {
const e = new Error(
`Can not use property "${property}" on ${
this.modelName
} with ${fn}() because it is not a hasMany relationship [ relType: ${
this.META.property(property).relType
}, inverse: ${
this.META.property(property).inverse
} ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().`
);
e.name = "FireModel::WrongRelationshipType";
throw e;
}
谁能帮我确定为什么这个错误没有被捕获?无奈之下,我在调用 _errorIfNotHasManyreln
的调用周围添加了另一个 try/catch 块,它确实捕获了错误,但随后我尝试重新抛出它并再次出现相同的情况。
您的 addToRelationship 方法也是异步的。您还必须 await
承诺响应:
try {
await bob.addToRelationship("employer", "4567");
}
catch(e) {
[...]
}
如果没有延迟到承诺被拒绝,那么 try/catch 没有收到任何同步和终止的内容。然后出现明显没有被捕获的异常
这些天我经常使用 async/await 但我有一个 mocha 测试,我正在测试以确保确实抛出错误。下面你可以看到 try/catch 块我必须捕获这个错误。绿色和灰色方块由 Wallaby(一种实时测试工具)插入,表示永远不会到达 catch 块。
当我从命令行 运行 mocha 时,我收到以下消息:
UnhandledPromiseRejectionWarning: FireModel::WrongRelationshipType: Can not use property "employer" on fancyperson with addToRelationship() because it is not a hasMany relationship [ relType: ownedBy, inverse: undefined ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().
addToRelationship()
的第一行检查关系类型是否正确(不正确)并抛出错误:
_errorIfNotHasManyReln
方法比较平淡,但为了完整起见,这里是:
protected _errorIfNotHasManyReln(
property: Extract<keyof T, string>,
fn: string
) {
if (this.META.property(property).relType !== "hasMany") {
const e = new Error(
`Can not use property "${property}" on ${
this.modelName
} with ${fn}() because it is not a hasMany relationship [ relType: ${
this.META.property(property).relType
}, inverse: ${
this.META.property(property).inverse
} ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().`
);
e.name = "FireModel::WrongRelationshipType";
throw e;
}
谁能帮我确定为什么这个错误没有被捕获?无奈之下,我在调用 _errorIfNotHasManyreln
的调用周围添加了另一个 try/catch 块,它确实捕获了错误,但随后我尝试重新抛出它并再次出现相同的情况。
您的 addToRelationship 方法也是异步的。您还必须 await
承诺响应:
try {
await bob.addToRelationship("employer", "4567");
}
catch(e) {
[...]
}
如果没有延迟到承诺被拒绝,那么 try/catch 没有收到任何同步和终止的内容。然后出现明显没有被捕获的异常