kannix
kannix

Reputation: 5157

chai test array equality doesn't work as expected

Why does the following fail?

expect([0,0]).to.equal([0,0]);

and what is the right way to test that?

Upvotes: 279

Views: 127862

Answers (7)

moka
moka

Reputation: 23047

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

Upvotes: 427

Gianluca Tomasino
Gianluca Tomasino

Reputation: 36

You can use

https://www.chaijs.com/api/assert/#method_samedeepmembers

assert.sameDeepMembers(set1, set2, [message])

Asserts that set1 and set2 have the same members in any order. Uses a deep equality check.

assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members');

Upvotes: 0

catomatic
catomatic

Reputation: 881

for unordered deep equality, use members

expect([1,2,3]).to.have.members([3,2,1]); // passes expect([1,2,3]).to.have.members([1,2,3]); // passes expect([1,2,3]).to.eql([3,2,1]); // fails

source

Upvotes: 3

Lane
Lane

Reputation: 4996

import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.

Upvotes: 1

Dmitry Grinko
Dmitry Grinko

Reputation: 15204

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

Upvotes: 0

GreensterRox
GreensterRox

Reputation: 7140

This is how to use chai to deeply test associative arrays.

I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)

I did it by defining the variable as an object (not array) prior to my function call:

var myAssocArray = {};   // not []
var expectedAssocArray = {};  // not []

expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';

// legacy function which returns associate array reference
myFunction(myAssocArray);

assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');

Upvotes: -1

Meet Mehta
Meet Mehta

Reputation: 4909

Try to use deep Equal. It will compare nested arrays as well as nested Json.

expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });

Please refer to main documentation site.

Upvotes: 77

Related Questions