摩卡和这个背景

rya*_*zec 5 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';
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我不知道为什么this.propmain afterEachundefined因为后续的代码按预期方式工作:

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

    it('should do something', function() {
        this.prop = 'test';
    });
});
Run Code Online (Sandbox Code Playgroud)

为什么第一个代码不能正常工作,尽管this.prop应该相等'test'而不是undefined

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

Lou*_*uis 24

是的,每个人都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';
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

这条线this.test.parent.ctx.prop是关键.thisContext与相关it的呼叫.this.testTestit调用关联的对象.this.test.parentSuitedescribe立即包含该it调用的调用关联的对象.this.test.parent.ctxdescribe调用出现的有效上下文,它恰好thisafterEach调用中的上下文相同.

我实际上建议不要遍历Mocha的内部结构,而是做以下事情:

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

    describe('sub', function() {
        it('should do something', function() {
            prop = 'test';
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 知道为什么你有 `this.test.parent.ctx` 而 /sf/answers/1915462251/ 列出了 `this.parent.ctx` 和 https://github.com/mochajs/mocha/ wiki/Shared-Behaviours 只有 `this`,而 https://github.com/mochajs/mocha/issues/2743#issue-214747482 列出了 `this.currentTest.ctx` 和在某些情况下的 `this.ctx`。这些是别名还是……? (2认同)
  • @BrettZamir我不会以*别名*来考虑它。在`describe`回调函数上设置的`this`与在`it`回调函数或`before`回调函数上的`this`是不同的。在我链接的答案中,起点是`描述回调,而这里是一个之前回调。不同的起点要求不同的路径。您链接到的其他情况正在尝试到达不同的终点。这类似于人们使用不同文件路径的方式,因为它们是从不同目录开始的,或者希望在末尾访问不同的文件。 (2认同)