});
});
});
详解describe和it
上面的实例代码比较简单,那么什么是describe和it呢? 大致上,我们可以看出describe应该是声明了一个TestSuit(测试集合) ,而且测试集合可以嵌套管理,而it声明定义了一个具体的测试用例。 以bdd interface为例,具体的源代码如下:
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.describe = context.context = function(title, fn) {
var suite = Suite.create(suites[0], title);
suite.file = file;
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
}; /**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.it = context.specify = function(title, fn) {
var suite = suites[0];
if (suite.pending) {
fn = null;
}
var test = new Test(title, fn);
test.file = file;
suite.addTest(test);
return test;
};
Hooks(钩子)
实际上这个在写unit test是很常见的功能,就是在执行测试用例,测试用例集合前或者后需要某个回调函数(钩子)。Mocha提供了before(),after(), beforeEach() 和aftetEach(),示例代码如下:
describe('hooks', function() {
before(function() {
// runs before all tests in this block
// 在执行所有的测试用例前 函数会被调用一次
}); after(function() {
// runs after all tests in this block
// 在执行完所有的测试用例后 函数会被调用一次
});
beforeEach(function() {
// runs before each test in this block
// 在执行每个测试用例前 函数会被调用一次
});
afterEach(function() {
// runs after each test in this block
// 在执行每个测试用例后 函数会被调用一次
});
// test cases
});
hooks还有下列其他用法:
Describing Hooks – 可以对钩子函数添加描述,能更好的查看问题
Asynchronous Hooks (异步钩子): 钩子函数可以是同步,也可以是异步的,和测试用例一下,下面是异步钩子的示例代码:
beforeEach(function(done) {
// 异步函数
db.clear(function(err) {
if (err) return done(err);
db.save([tobi, loki, jane], done);
});
});
Root-Level Hooks (全局钩子) – 就是在describe外(测试用例集合外)执行,这个一般是在所有的测试用例前或者后执行。
Pending Tests (挂起测试)
就是有一些测试,现在还没有完成,有点类似TODO, 如下面的代码:









