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

Chai中throw断言结合with.property时如何使用deep equal比较属性值

解决方案

你遇到的断言失败确实是property默认采用严格相等规则导致的,引用类型的对象只会对比内存地址,不会递归校验内部属性,只要在断言前添加deep标记即可开启深度相等比较。

写法1:基于原代码改造

在property前增加deep标记即可:

const docNotFound = expect(() => getDoc('01234567890')).to.throw('DocNotFoundError')
docNotFound.with.deep.property('details', { docId: '01234567890' })

写法2:链式完成全量断言

无需单独存储错误实例,直接在一条断言链内写完所有校验逻辑:

expect(() => getDoc('01234567890'))
  .to.throw(DocNotFoundError)
  .and.have.deep.property('details', { docId: '01234567890' })

备选写法:单独校验属性

如果需要对details做更复杂的自定义校验,可以单独取出属性后做深度相等判断:

const throwErr = expect(() => getDoc('01234567890')).to.throw(DocNotFoundError)
expect(throwErr.details).to.deep.equal({ docId: '01234567890' })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:27:02