You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何一步测试被拒绝Promise的错误类与错误信息?

解决方案

你可以通过Jest的链式断言特性,在单次Promise调用中同时验证错误实例和消息,无需执行两次测试:

await expect(core.createDatabaseFile("non-existing/test.sqlite3")).rejects
  .toBeInstanceOf(ResponseError)
  .toHaveProperty("message", "No permissions to access the directory.");

如果你的自定义错误类还包含错误码等其他属性,也可以继续链式添加断言:

await expect(core.createDatabaseFile("non-existing/test.sqlite3")).rejects
  .toBeInstanceOf(ResponseError)
  .toHaveProperty("message", "No permissions to access the directory.")
  .toHaveProperty("code", "PERMISSION_DENIED");

另外,也可以使用expect.objectContaining来匹配错误对象的多个属性:

await expect(core.createDatabaseFile("non-existing/test.sqlite3")).rejects.toEqual(
  expect.objectContaining({
    message: "No permissions to access the directory.",
    code: "PERMISSION_DENIED"
  })
);

这种方式会先验证Promise拒绝的对象是ResponseError的实例,同时检查指定属性的值,全程只执行一次createDatabaseFile调用,避免重复执行的成本。

内容的提问来源于stack exchange,提问作者Mike Lischke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:30:47