javascript - Mocha 和 this 上下文

标签 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';
        });
    });
});

我不知道为什么 main afterEach 中的 this.propundefined 因为下面的代码按预期工作:

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

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

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

this 关键字是否仅绑定(bind)到它直接包含的 describe 函数?

最佳答案

是的,每个 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 是与 describe 调用关联的 Suite 对象,它立即包含 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';
        });
    });
});

关于javascript - Mocha 和 this 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27575423/

相关文章:

unit-testing - 使用 Mocha 或 Jasmine 对 Node.js REST 服务进行单元测试

maven-plugin - 有 "mocha maven plugin"吗?

javascript - 从数组中删除一个元素

javascript - 对 HTML 进行编码并将其从 PHP 传递到 Javascript

unit-testing - 如何对 Angular2 中的复选框进行单元测试

c# - 类方法输出字符串消息,由于错误引用从 void 到字符串的转换不适用,因此无法进行单元测试

node.js - mock os.type() 不起作用

javascript - 将参数传递给 Javascript 子类

javascript - 只匹配@而不匹配@@,没有负面回溯

unit-testing - 如何在 rspec 单元测试中隔离 Puppet 函数模拟