javascript - Mocha 测试提示未处理的 Promise,但使用带有 catch block 的 async/await

标签 javascript async-await mocha.js

这些天我经常使用 async/await,但我有一个 Mocha 测试,我正在测试以确保确实抛出错误。下面您可以看到我必须捕获此错误的 try/catch block 。绿色和灰色方 block 是由 Wallaby(实时测试工具)插入的,表示从未到达 catch block 。

enter image description here

当我从命令行运行 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() 的第一行检查关系类型是否正确(不正确)并抛出错误:

enter image description here

_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 block ,它确实捕获了错误,但随后我尝试重新抛出它,并再次陷入相同的情况。

最佳答案

您的 addToRelationship 方法也是异步的。您还必须等待 promise 响应:

try {
    await bob.addToRelationship("employer", "4567");
}
catch(e) {
    [...]
}

如果没有延迟到 promise 拒绝,则 try/catch 不会收到任何同步和终止的内容。然后发生了异常,显然没有被捕获。

关于javascript - Mocha 测试提示未处理的 Promise,但使用带有 catch block 的 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50974279/

相关文章:

javascript - 在 'default' 中找不到导出 'router' (导入为 './router' )

javascript - wait/async 如何处理 Unresolved promise

c# - 任务异步/等待不适用于 WPF,因为它在其他场景中有效

Javascript异步如何等待不同数量的uploadTasks全部完成?

unit-testing - 使用 Mocha 和 Chai 测试 Angular

javascript - 如何在测试中伪造 Bluebird 的计时器?

javascript - AngularJS - 未选中单选按钮

javascript - AngularJS:范围监视未被触发,即使 objectEquality = true

javascript - 我如何检查 after block 中是否有任何 mocha 测试失败?

javascript - Now.sh 构建因 : Support for the experimental syntax 'decorators-legacy' isn't currently enabled 而中断