[英]Mocha/chai assertion is failing but there is no diff
我正在用javascript创建一个二叉树类,我的测试失败了,但是我的方法没有发现任何问题,并且没有收到任何差异。 任何见解都会很棒。
这是我的课:
function binaryTree() {
this.root = null;
};
binaryTree.prototype = {
constructor: binaryTree,
add: function(val) {
var root = this.root;
if(!root) {
this.root = new Node(val);
return;
}
var currentNode = root;
var newNode = new Node(val);
while(currentNode) {
if(val < currentNode.value) {
if(!currentNode.left) {
currentNode.left = newNode;
break;
}
else {
currentNode = currentNode.left;
}
}
else {
if(!currentNode.right) {
currentNode.right = newNode;
break;
}
else {
currentNode = currentNode.right;
}
}
}
}
这是我的测试:
it('adds values to the binary tree', function () {
var test = new binaryTree();
test.add(7);
test.add(43);
test.add(13);
test.add(27);
test.add(82);
test.add(2);
test.add(19);
test.add(8);
test.add(1);
test.add(92);
expect(test).to.equal({
root:
{ value: 7,
left:
{ value: 2,
left: { value: 1, left: null, right: null },
right: null },
right:
{ value: 43,
left:
{ value: 13,
left: { value: 8, left: null, right: null },
right:
{ value: 27,
left: { value: 19, left: null, right: null },
right: null } },
right:
{ value: 82,
left: null,
right: { value: 92, left: null, right: null } } } }
});
});
这是我得到的错误:
1) binary tree tests adds values to the binary tree:
AssertionError: expected { Object (root) } to equal { Object (root) }
+ expected - actual
如果我弄乱了测试对象中的值,我会看到一个差异,因此在我看来一切都相等,我很困惑。 如果能再引起我的关注,我将不胜感激。
您正在使用Mocha的to.equal
期望,但这会测试严格的均等性。 http://chaijs.com/api/bdd/#method_equal
即使两个对象具有相同的键值对,它们也不会对三等式(===)比较器返回true。 这是因为它们实际上是存储在内存中的两个单独的对象,它们看起来相似。
使用to.deep.equal
代替!
说得通?
万一遇到任何人,我发现了问题。 即使所有属性都相等,也无法在JavaScript中完美地比较两个对象。 这篇文章有两种方法可以解决此限制,在这种情况下,其中一种很容易实现:
将expect(test).to.equal({
更改为expect(test).to.equal({
expect(JSON.stringify(test)).to.equal(JSON.stringify({
将允许此测试通过。对对象进行字符串化是比较两个对象的一种非常简单的方法但这仅在属性的顺序完全相同时才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.