0

expect.to.throw returns a Proxy to the thrown Error, so I can use with.property in order to check some properties of the error.

I attach a details object on my custom errors but I can't test for them, since the with.property compares only using strict equals.

Can I compare this property using deep equal somehow?

Example:

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

The error will fail similar to

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

I assume this is due to it only checks for reference equality and not deep object equality.

Jankapunkt
  • 8,128
  • 4
  • 30
  • 59

1 Answers1

1

First of all there is a typo in the question: DocNotFoundError should not be in quotes.

I managed to get it working with docNotFound.to.have.deep.property('details', { docId: '01234567890' }), so yes you should perform deep comparison to check if objects have keys with same values.

Source 1

Source 2

Vulwsztyn
  • 2,140
  • 1
  • 12
  • 20
  • Thank you that worked out very well! One comment to your answer, can you please remove the sources? I think they both are dealing only with general deep equality and not with property equality **of expected thrown errors**, right? – Jankapunkt Sep 09 '21 at 12:51
  • why should I remove the sources if they could help someone and do you no harm? they helped me solve this – Vulwsztyn Sep 09 '21 at 20:29
  • 1
    Ok no problem then – Jankapunkt Sep 10 '21 at 06:39