<分区>
我想使用 mocha/chai 来测试与二叉搜索树相关的代码。在这里,我正在测试公共(public) insert
方法。我想使用 beforeEach()
和/或 afterEach()
钩子(Hook)在每个 it()
语句之前重置测试环境,这样我不必完全重复基础知识。但是,我不断收到各种错误。
规范
describe("BinarySearchTree insert function", function() {
beforeEach(function() {
var binarySearchTree = new BinarySearchTree();
binarySearchTree.insert(5);
});
it("creates a root node with value equal to the first inserted value", function () {
expect(binarySearchTree.root.value).to.equal(5);
});
it("has a size equal to the amount of inserted values", function () {
binarySearchTree.insert(3);
expect(binarySearchTree.size).to.equal(2);
});
it("returns an error for non-unique values", function () {
binarySearchTree.insert(3);
expect(binarySearchTree.insert(3)).to.throw(String);
});
it("if inserted value is larger than current node, make or descend to rightChild", function () {
binarySearchTree.insert(3);
binarySearchTree.insert(10);
binarySearchTree.insert(7);
expect(binarySearchTree.root.rightChild.value).to.equal(10);
});
});
错误:ReferenceError:未定义 binarySearchTree
事实上,在没有 afterEach()
重置测试环境之前,我预计会出现错误,而不是因为未定义 binarySearchTree
。如果可能的话,我想只用 Mocha 和 Chai(而不是像 Sinon 等其他包)来完成这个。
测试代码
exports.Node = Node;
function Node(value) {
this.value = value;
this.leftChild = null;
this.rightChild = null;
}
exports.BinarySearchTree = BinarySearchTree;
function BinarySearchTree() {
this.root = null;
this.size = 0;
}
BinarySearchTree.prototype.insert = function(value) {
// 1) when root node is already instantiated
if (this.root === null) {
// tree is empty
this.root = new Node(value);
this.size++;
} else {
// 2) nodes are already inserted
var findAndInsert = function (currentNode) {
if (value === currentNode.value) {
throw new Error('must be a unique value');
}
// base case
if (value > currentNode.value) {
// belongs in rightChild
if (currentNode.rightChild === null) {
currentNode.rightChild = new Node(value);
} else {
findAndInsert(currentNode.rightChild);
}
} else if (value < currentNode.value) {
// belongs in leftChild
if (currentNode.leftChild === null) {
currentNode.leftChild = new Node(value);
} else {
findAndInsert(currentNode.leftChild);
}
}
};
findAndInsert(this.root);
this.size++;
}
};
奖金问题...我不确定我是否正确测试抛出的错误(当插入非唯一值时)?