255
votes

Why does the following fail?

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

and what is the right way to test that?

7

7 Answers

389
votes

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.

67
votes

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.

0
votes

You can use .deepEqual()

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

assert.deepEqual([0,0], [0,0]);
0
votes
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.
0
votes

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

0
votes

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');
-1
votes

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');