用Mochatesting访问内部描述块时,外部描述块中的variables是不确定的

我有一个testing套件,如下所示:

(请注意,顶部的accountToPostvariables(在第一个describe块下面)

 describe('Register Account', function () { var accountToPost; beforeEach(function (done) { accountToPost = { name: 'John', email: 'email@example.com', password: 'password123' }; done(); }); describe('POST /account/register', function(){ describe('when password_confirm is different to password', function(){ //accountToPost is undefined! accountToPost.password_confirm = 'something'; it('returns error', function (done) { //do stuff & assert }); }); }); }); 

我的问题是,当我尝试修改我的嵌套的描述块中的accountToPost ,它是未定义的…

我能做些什么来解决这个问题?

保留它的位置,但在beforeEachcallback中包装并执行代码:

 beforeEach(function () { accountToPost.password_confirm = 'something'; }); 

摩卡加载你的文件并执行它,这意味着describe调用摩卡实际运行testing套件之前马上执行。 这就是它如何计算出你已经声明的一系列testing。

我通常只在函数和variables声明中join一些我将要describe的callback函数。 所有改变testing中使用的对象的状态都属于beforebeforeEachafterafterEach ,或者在testing本身之内。

还有一件事要知道, beforeEachafterEach是在callbackafterEach前后执行的, it 不会调用describe调用的callbackafterEach 。 所以如果你认为beforeEachcallback会在describe('POST /account/register', ...之前执行describe('POST /account/register', ...这是不正确的,它会在it('returns error', ...之前执行it('returns error', ...

这段代码应该说明我在说什么:

 console.log("0"); describe('level A', function () { console.log("1"); beforeEach(function () { console.log("5"); }); describe('level B', function(){ console.log("2"); describe('level C', function(){ console.log("3"); beforeEach(function () { console.log("6"); }); it('foo', function () { console.log("7"); }); }); }); }); console.log("4"); 

如果你在这个代码上运行mocha,你会看到数字以升序排列输出到控制台。 我已经按照您的testing套件的结构来构build它,但是添加了我的build议修补程序。 输出数字0到4,而Mocha正在计算套件中的testing。 testing尚未开始。 其他数字在testing期间输出。