摩卡beforeEach vs之前执行

最近我碰到一个我无法解释的问题。 在这些testing中我有很多代码,所以我会尽我所能来捕捉这个主意

我有这样的testing:

describe('main page', function(){ beforeEach(function(done){ addUserToMongoDb(done); // #1 }); afterEach(function(done){ removeUserFromMongoDb(done); }); context('login', function(){ it('should log the user in, function(){ logUserIn(user_email); // #2 - This line requires the user from the beforeEach }); }); context('preferences', function(){ before(function(done){ //#3 logUserInBeforeTest(user_email); }); it('should show the preferences', function(){ doCheckPreferences(); // #4 }); }); }); 

问题是, #1运行良好。 我可以看到它发生在数据库和#2通过testing。

但是,在#4偏好上下文中的testing失败,因为它无法find用户在#3login他们。

似乎before的上下文是在beforeEach before执行的,这会导致它们失败。 如果我将logUserIn移动到it阻止它工作正常。

什么可能导致这个?

Mocha的testing运行者在Mocha Test Runner的Hooks部分解释了这个function。

从钩子部分:

 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 }); 

您可以将这些例程嵌套在其他每个例程之前/之前的描述块中。

我发现了一个类似的问题。 该文档是误导性的,因为“此块之前”意味着(至less对我来说)“在这个描述部分之前”。 同时它的意思是“在任何描述部分之前”。 检查这个例子:

 describe('outer describe', function () { beforeEach(function () { console.log('outer describe - beforeEach'); }); describe('inner describe 1', function () { before(function () { console.log('inner describe 1 - before'); }); describe('inner describe 2', function () { beforeEach(function () { console.log('inner describe 2 - beforeEach'); }); }); // output will be: // inner describe 1 - before // outer describe - beforeEach // inner describe 2 - beforeEach 

看起来你放在before层次结构中的哪个地方并不重要 – 它将在任何描述之前运行,而不在它包含描述之前运行。

混乱的原因在于摩卡的logging。 你可以在摩卡中find:

testing可以出现在你的钩子之前,之后或穿插。 钩子将按照它们定义的顺序运行,视情况而定; 所有before()钩子运行(一次),然后任何beforeEach()钩子,testing,任何afterEach()钩子,最后在()钩子(一次)之后。

讨论beforebeforeEach钩子分别在所有或每个分别执行之前 – 无法在描述节前执行它。

在这里,你可以find #1的贡献者的摩卡的主分支的答案的想法添加像beforeDescribe钩的东西。

我想你应该看看 – --delay摩卡选项 。