使用以下 JavaScript 库进行测试:
Mocha —— 核心框架:提供了包括通用型测试函数 describe 和 it,以及用于运行测试的主函数。
Chai —— 提供很多断言(assertion)支持的库。它提供了很多不同的断言,现在我们只需要用 assert.equal。
Sinon —— 用于监视函数、模拟内建函数和其他函数的库,我们在后面才会用到它。
这些库都既适用于浏览器端,也适用于服务器端。这里我们将使用浏览器端的变体。
使用 describe 和一组 it 代码块替换掉了单个的 it。现在,如果某个测试失败了,我们可以清楚地看到数据是什么。
describe("Raises x to power n", function() {
it("5 in the power of 1 equals 5", function() {
assert.equal(pow(5, 1), 5);
});
it("5 in the power of 2 equals 25", function() {
assert.equal(pow(5, 2), 25);
});
it("5 in the power of 3 equals 125", function() {
assert.equal(pow(5, 3), 125);
});
});
此外,我们可以通过编写 it.only 而不是 it 来隔离单个测试,并以独立模式运行它:
describe("Raises x to power n", function() {
it("5 in the power of 1 equals 5", function() {
assert.equal(pow(5, 1), 5);
});
// Mocha 将只运行这个代码块
it.only("5 in the power of 2 equals 25", function() {
assert.equal(pow(5, 2), 25);
});
it("5 in the power of 3 equals 125", function() {
assert.equal(pow(5, 3), 125);
});
});