【问题标题】:Mocha and the this context摩卡和这个上下文
【发布时间】:2015-02-18 22:37:45
【问题描述】:

所以我有这个代码:

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

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

我不知道为什么main 中的this.prop afterEachundefined,因为以下代码按预期工作:

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

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

为什么第一个代码不能像我一样工作,尽管 this.prop 应该等于 'test' 而不是 undefined

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

【问题讨论】:

标签: javascript unit-testing mocha.js


【解决方案1】:

是的,每个describe 都有一个新的Context 对象。 (我提到的所有类都可以在 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 是与 it 调用关联的 Contextthis.test 是与 it 调用关联的 Test 对象。 this.test.parent 是与立即包含 it 调用的 describe 调用关联的 Suite 对象。 this.test.parent.ctxdescribe 调用出现 的实际上下文,恰好与afterEach 调用中的this 相同。

我实际上建议不要遍历 Mocha 的内部结构,而是执行以下操作:

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,而stackoverflow.com/a/27363746/271577 列出this.parent.ctx,而github.com/mochajs/mocha/wiki/Shared-Behaviours 只有this,而github.com/mochajs/mocha/issues/2743#issue-214747482 列出this.currentTest.ctx,在某些情况下是this.ctx .这些是别名还是...?
  • @BrettZamir 我不会从别名的角度来考虑它。在describe 回调上设置的thisit 回调或before 回调等上的this 不同。在您链接的我的答案中,起点是@ 987654353@ 回调,而这里是 before 回调。不同的起点需要不同的路径。您链接到的其他案例正在尝试到达不同的端点。这类似于人们使用不同文件路径的方式,因为他们从不同的目录开始,或者想在最后访问不同的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-22
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多