Currently I'm trying to understand how BDD DSL works in Mocha and I'm stuck. I'd like this approach and want to apply this.
For example, the following test:
describe('foo', function(){
describe('bar', function(){
it('should be something')
});
});
will produce output:
foo
bar
- should be something
0 passing (4ms)
1 pending
Question: how invocation of global function describe in nested block determined as nested? I looked at source code, but can't handle the main idea right now.
Mocha keeps track of these things in Suites, as you can see from the 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;
};
To simplify things a bit, for each describe, Mocha creates a new suite. Suites can contain other suites.
For your example, Mocha creates the foo suite, which then contains the bar suite, which contains the should be something test.
It can be achieved by a global tree data structure.
When you call a describe, mocha adds a node, when you call it, mocha adds a leaf.
When the root describe call returns, the tree is complete and mocha traverses the nodes executing the leafs one by one.