arraysnode.jschai

Comparing arrays in chai


I'm writing some tests with chai and chai-as-promised (and more frameworks, but it doesn't matter in this case) and I need to check if array I get from a web-page is same as a predefined array. I tried to use expect(arrayFromPage).to.eventually.deep.equal(predefinedArray), but it won't work, because order of elements on page is sometimes different (which is OK, I don't need to check if they are in the same order).

I've found a way to workaround the issue by using expect(listFromPage).to.eventually.include.all.members(predefinedArray), but I'd like to know if there is a better solution.

What bothers me most in my workaround, is that I only assure that predefinedArray is subset of listFromPage, not that they are made of same elements.

So, I'd like to know if there is an assert that will pass for [1,2,3] and [3,2,1], but not for [1] and [1,2,3] or [1,2,3,4] and [1,2,3].

I know that I can use some second expectation (compare lengths, or something else), but I'd like to know if there is a one-line solution.


Solution

  • Seeing as this was marked as resolved earlier, I tried doing the same thing as in the accepted answer. It probably worked back then, but doesn't seem to work anymore:

    expect([1, 2, 3, 4]).to.have.all.members([2, 4, 3, 1]);
    

    Gives the following error:

    AssertionError: expected 1 to be an array
    

    I did a little more research and found a pull request that added this functionality back in 2013:

    https://github.com/chaijs/chai/pull/153

    So the official way of doing this now is like this:

    expect([1, 2, 3, 4]).to.have.same.members([2, 4, 3, 1]);
    

    For completeness, here's the error that two different sets produces:

    AssertionError: expected [ 1, 2, 3, 4 ] to have the same members as [ 4, 3, 1 ]
    

    Hope this helps anyone searching for the same answer now. :-)