chai test array equality doesn't work as expected

寵の児 提交于 2019-12-17 03:34:12

问题


Why does the following fail?

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

and what is the right way to test that?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/17526805/chai-test-array-equality-doesnt-work-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!