Home > OS >  Check if a nested property has an object that partially matches a target in expect
Check if a nested property has an object that partially matches a target in expect

Time:12-20

I have an object like this:

> const expect = require('chai').expect
> r = {  loadedElementData: { userIdRecord: { name: 'Chiara', surname: 'Fabbietti', id: 1 } }, resolvedIdParamsValues: { users: 1 }, resolvedListFilter: {}, totalLoads: 1 }

I can check if an object with specific contents is somewhere deep in r -- this doesn't throw:

> expect(r).to.have.nested.deep.property('loadedElementData.userIdRecord', { name: "Chiara", surname: "Fabbietti", id: 1 })

However, I want to check for partial objects. So, I would like something like this to pass even though the comparison object is a partial match:

> expect(r).to.have.nested.deep.property('loadedElementData.userIdRecord', { id: 1, name: 'Chiara' })

This obviously won't work, since it will check for the object's deep equality.

This in theory should work:

expect(r).to.nested.include({'loadedElementData.userIdRecord': { id: 1, name: 'Chiara' } })

But doesn't. This should REALLY work:

 expect(r).to.deep.nested.include({ 'loadedElementData.userIdRecord': { id: 1, name: 'Chiara' } })

But doesn't.

I can make it work checking ONE property (only 'id'):

expect(r).to.nested.include({ 'loadedElementData.userIdRecord.id': 1})

But I am limited to check for id, and can't check for name too at the same time.

I can do this in 2 steps:

> expect(r).to.include.nested.property('loadedElementData.userIdRecord')
> expect(r.loadedElementData.userIdRecord).to.include({ id: 1 })

But this is a two step process -- can I do it in one step?

CodePudding user response:

If you check their Github issues, maintainers acknowledge that the nested inclusion of an object subset is not working since 2020. Reference: chai Github

This is the line where Chai decides if doing a deep equality or a strict equality when comparing two objects: https://github.com/chaijs/chai/blob/a8359d3d15779a23a7957a4c52539d48de2763e0/lib/chai/core/assertions.js#L1892.
_.eql is a reference to Chai's deep equal own library implementation.

In the deep-eql library the flow will reach to this function that does loose equality comparisons but not partial ones.

  • Related