node.js chai 测试数组相等不能按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17526805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
chai test array equality doesn't work as expected
提问by kannix
Why does the following fail?
为什么以下失败?
expect([0,0]).to.equal([0,0]);
and what is the right way to test that?
什么是测试它的正确方法?
回答by moka
For expect, .equalwill compare objects rather than their data, and in your case it is two different arrays.
对于expect,.equal将比较对象而不是它们的数据,在您的情况下,它是两个不同的数组。
Use .eqlin order to deeply compare values. Check out this link.
Or you could use .deep.equalin order to simulate same as .eql.
Or in your case you might want to check.members.
使用.eql以深深的比较值。查看此链接。
或者您可以使用.deep.equal以模拟与.eql.
或者在您的情况下,您可能想要检查.members.
For assertsyou can use .deepEqual, link.
对于断言,您可以使用.deepEqual, link。
回答by Meet Mehta
Try to use deep Equal. It will compare nested arrays as well as nested Json.
尝试使用深度相等。它将比较嵌套数组以及嵌套的 Json。
expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
Please refer to main documentation site.
请参阅主要文档站点。
回答by GreensterRox
This is how to use chai to deeply test associative arrays.
这就是如何使用 chai 深入测试关联数组。
I had an issue trying to assert that two associativearrays 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. :-)
我在尝试断言两个关联数组相等时遇到了问题。我知道这些不应该在 javascript 中真正使用,但我正在围绕遗留代码编写单元测试,这些代码返回对关联数组的引用。:-)
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');

