Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/459.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 摩卡咖啡和这个背景下的_Javascript_Unit Testing_Mocha.js - Fatal编程技术网

Javascript 摩卡咖啡和这个背景下的

Javascript 摩卡咖啡和这个背景下的,javascript,unit-testing,mocha.js,Javascript,Unit Testing,Mocha.js,所以我有这个代码: describe('main describe', function() { afterEach(function() { //this.prop === undefined }); describe('sub', function() { it('should do something', function() { this.prop = 'test'; }); }); }

所以我有这个代码:

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

    describe('sub', function() {
        it('should do something', function() {
            this.prop = 'test';
        });
    });
});
我不知道为什么
每个
之后
中的
这个.prop
未定义的
,因为下面的代码按预期工作:

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

    it('should do something', function() {
        this.prop = 'test';
    });
});
如果this.prop应该等于
'test'
而不是
未定义的
,为什么第一个代码不能像我想象的那样工作


this
关键字是否仅与直接包含它的
descripe
函数关联?

是的,每个
descripe
都会获得一个新的
上下文对象。(我提到的所有类都可以在Mocha的源代码中找到。)你可以得到你想要做的:

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.test
是与
it
调用关联的
test
对象
this.test.parent
是与
descripe
调用关联的
Suite
对象,该调用立即包含
it
调用
this.test.parent.ctx
是出现
descripe
调用的有效上下文,它恰好与每次
调用后
中的
this
上下文相同

实际上,我建议不要穿过摩卡的内部结构,而是做一些类似的事情:

describe('main describe', function() {
    var prop;
    afterEach(function() {
        console.log(prop);
    });

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

作为参考,这些是我能找到的文档:(到目前为止,他们还没有回答这个特定的问题)你知道为什么你有
this.test.parent.ctx
,而列出
this.parent.ctx
,只有
this
,而列出
this.currentTest.ctx
,在某些情况下还有
this.ctx
。这些是化名还是…?@BrettZamir我不认为它是化名。在
descripe
回调上设置的
this
it
回调或
之前的
回调等上设置的
this
不同。在您链接的我的答案中,起点是
descripe
回调,而这里是
之前的
回调。不同的起点需要不同的路径。您链接到的其他案例正试图到达不同的终点。这类似于人们使用不同的文件路径,因为他们从不同的目录开始,或者希望在最后到达不同的文件。