用Mochatesting访问内部描述块时,外部描述块中的variables是不确定的
我有一个testing套件,如下所示:
(请注意,顶部的accountToPost
variables(在第一个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
,它是未定义的…
我能做些什么来解决这个问题?
保留它的位置,但在beforeEach
callback中包装并执行代码:
beforeEach(function () { accountToPost.password_confirm = 'something'; });
摩卡加载你的文件并执行它,这意味着describe
调用在摩卡实际运行testing套件之前马上执行。 这就是它如何计算出你已经声明的一系列testing。
我通常只在函数和variables声明中join一些我将要describe
的callback函数。 所有改变testing中使用的对象的状态都属于before
, beforeEach
, after
或afterEach
,或者在testing本身之内。
还有一件事要知道, beforeEach
和afterEach
是在callbackafterEach
前后执行的, it
不会调用describe
调用的callbackafterEach
。 所以如果你认为beforeEach
callback会在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期间输出。
- 在整个摩卡testing之前运行asynchronous代码
- testing:摩卡和节点不同
- Sails.js和Mocha:使用supertest:path问题,当控制器在像api \ controllers这样的coustom文件夹被移动到api \ controllers \ admin
- Sinon – 何时使用间谍/嘲笑/存根或只是简单的断言?
- 如何使用mocha和supertesttesting头部参数的快速restapi?
- MongoDB / Mongooseunit testing – 最佳实践?
- 用摩卡回收的sails.js
- 如果一个失败,跳过后续的摩卡testing
- 强制npmtesting来创build新的\新的input副本