首页 > 解决方案 > 与属性深度相等的柴抛

问题描述

expect.to.throw为抛出的错误返回一个代理,因此我可以使用with.property它来检查错误的某些属性。

我在我的自定义错误上附加了一个details对象,但我无法测试它们,因为with.property比较只使用严格等于。

我可以以某种方式使用深度相等来比较这个属性吗?

例子:

class DocNotFoundError extends Error {
  constructor(message, docId) {
    super(message)
    this.details = { docId }
  }
}

const getDoc = id => {
  throw new DocNotFoundError('errors.docNotFound', id)
}

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

该错误将失败,类似于

AssertionError: expected { Object (error, ...) } to have property 'details' of { Object (docId) }, but got { Object (docId) }
+ expected - actual

我认为这是因为它只检查引用相等而不是深度对象相等。

标签: chai

解决方案


首先,问题中有一个错字:DocNotFoundError不应该用引号引起来。

我设法让它与 . 一起工作docNotFound.to.have.deep.property('details', { docId: '01234567890' }),所以是的,您应该执行深度比较以检查对象是否具有具有相同值的键。

来源 1

来源 2


推荐阅读