Why does the following fail?
expect([0,0]).to.equal([0,0]);
and what is the right way to test that?
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.
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.
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');
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');