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
回调,而这里是之前的回调。不同的起点需要不同的路径。您链接到的其他案例正试图到达不同的终点。这类似于人们使用不同的文件路径,因为他们从不同的目录开始,或者希望在最后到达不同的文件。