我正在 JavaScript 中创建一个二叉树类,但我的测试失败了,但我没有发现我的方法有任何问题,并且我没有收到任何差异。任何见解都会很棒。
这是我的类(class):
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 - Mocha/chai 断言失败,但没有差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36296722/