Comparing arrays in chai

I am writing several tests with chai and chai-as-promised (and more frameworks, but in this case it does not matter), and I need to check if the array that I get from the webpage is the same as the predefined an array. I tried to use expect(arrayFromPage).to.eventually.deep.equal(predefinedArray) , but this will not work because the order of the elements on the page is sometimes different (this is normal, I don't need to check if they are in the same order).

I found a way around the problem using expect(listFromPage).to.eventually.include.all.members(predefinedArray) , but I would like to know if there is a better solution.

What bothers me the most about my workaround, I only assure you that predefinedArray is a subset of listFromPage , not that they are made from the same elements.

So, I would like to know if there is a statement 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 would like to know if there is a single line solution.

+6
source share
4 answers

Seeing, as noted earlier, I tried to do the same as in the accepted answer. It probably worked then, but it 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 bit more research and found a migration request that added this functionality back in 2013:

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

So, the official way to do it now:

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

For completeness, an error occurs here, created by two different sets:

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

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

+12
source

This is not entirely clear from the documentation, but .to.have.all.members seems to work. I could find a mention of this function for .keys , but it looks the same as for .members with arrays.

+4
source

You can do this with two lines:

 expect(listFromPage).to.eventually.include.all.members(predefinedArray) expect(predefinedArray).to.eventually.include.all.members(listFromPage) 

In doing so, you will check whether both arrays have the same values. But order doesn't matter.

+2
source

From the future, the way that worked for me was to use .deepEqual , which helped

 assert.deepEqual(['name'], ['name'], 'this must be same to proceed'); 
+1
source

All Articles