Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comparing deep members between two different unsorted arrays doesn't produce accurate errors #1462

Open
MilanJimi opened this issue Mar 10, 2022 · 0 comments

Comments

@MilanJimi
Copy link

When using chai 4.3.4 with mocha 9.2.1, I came across a problem when deep matching arrays - My understanding is that expect().to.have.deep.members() error message should not depend on whether the arrays are sorted - but it does. Chai will sometimes mismatch members that are present in both expected and actual arrays, logging them as error.

Seems that sorting the array first so that the matching element is on the same index in both arrays helps, but this won't work for arrays which might be wildly different.

Including example:

import { expect } from 'chai'

const actual = [{ foo: 'X' }, { foo: 'Y' }, { foo: 'Z' }, { foo: 'a' }]

const expected1 = [{ foo: 'a' }, { foo: 'x' }, { foo: 'y' }, { foo: 'z' }]
const expected2 = [{ foo: 'x' }, { foo: 'y' }, { foo: 'z' }, { foo: 'a' }]
const expected3 = [{ foo: 'a' }, { foo: 'X' }, { foo: 'Z' }, { foo: 'Y' }]
const expected4 = [{ foo: 'X' }, { foo: 'Y' }, { foo: 'z' }, { foo: 'a' }]
const expected5 = [{ foo: 'a' }, { foo: 'Z' }, { foo: 'X' }, { foo: 'Y' }]

describe('test', () => {
  it('3 different, unsorted', () => {
    expect(actual).to.have.deep.members(expected1)
    // Will not match { foo: 'a' } from actual to expected
  })
  it('3 different, sorted', () => {
    expect(actual).to.have.deep.members(expected2)
    // Will match { foo: 'a' } from actual to expected
  })
  it('1 different, unsorted', () => {
    expect(actual).to.have.deep.members(expected3)
    // Will not match any of the matching members
  })
  it('1 different, sorted', () => {
    expect(actual).to.have.deep.members(expected4)
    // Will match all of the matching members
  })
  it('All matching, unsorted', () => {
    expect(actual).to.have.deep.members(expected5)
    // Will pass
  })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant