Mocha如何确定嵌套级别?

时间:2014-09-18 22:56:25

标签: javascript node.js mocha dsl

目前,我正试图了解BDD DSL如何在Mocha中运行,而且我被卡住了。我喜欢这种方法并想要应用它。

例如,以下测试:

describe('foo', function(){
    describe('bar', function(){
        it('should be something')
    });
});

将产生输出:

foo
  bar
    - should be something


0 passing (4ms)
1 pending

问题:嵌套块中全局函数describe的调用如何确定为嵌套?我查看了源代码,但现在无法处理主要想法。

2 个答案:

答案 0 :(得分:1)

Mocha会在套件中跟踪这些内容,您可以在source

中看到
/**
 * 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,Mocha创建一个新的套件。套房可以包含其他套房。

对于您的示例,Mocha创建了foo套件,其中包含bar套件,其中包含should be something测试。

答案 1 :(得分:0)

可以通过全局树数据结构来实现。

当您调用 describe 时,mocha会添加一个节点,当您调用时,mocha会添加一个叶子。

当根描述调用返回时,树完成,mocha逐个遍历执行叶子的节点。