Mocha和此上下文

问题描述 投票:0回答:1

我有此代码带有嵌套的描述:

describe('main describe', function() {
    afterEach(function() {
      //this.prop === undefined
    });

    describe('sub', function() {
        it('should do something', function() {
            this.prop = 'test';
        });
    });
});

我不知道为什么在

this.prop
main
中是
afterEach
,因为没有嵌套的以下代码如预期的:
undefined

为什么第一个代码不如我那样行不通,虽然它应该等于
describe('main describe', function() { afterEach(function() { //this.prop === 'test' }); it('should do something', function() { this.prop = 'test'; }); });

是仅与
'test'
函数绑定的关键字直接包含它?
    

是的,每个

undefined
获得了一个新的
this
对象。 (我提到的所有课程都可以在摩卡咖啡的源代码中找到。)您可以得到您要尝试的工作:

javascript unit-testing mocha.js
1个回答
29
投票

线是关键。

describe
是与
Context
调用相关联的

describe('main describe', function() { afterEach(function() { console.log(this.prop); }); describe('sub', function() { it('should do something', function() { this.test.parent.ctx.prop = 'test'; }); }); });
this.test.parent.ctx.prop

是与

this
调用关联的
Context
对象。
it
是与立即包含
this.test
调用的
Test
调用关联的
it
对象。
this.test.parent
是在上下文中,
Suite
呼叫
appears
恰好与
describe
呼叫中的上下文相同。
我实际上建议不要穿越摩卡咖啡的内部结构,而要做类似的事情:
it
	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.