使用Mocha.js编写的以下测试代码失败。我希望 someVal 在最后一次测试中增加3倍并且等于3。这个问题出现在更复杂的场景中,我在块之前使用外部中的值设置在内部 beforeEach 块中设置另一个。简化案例:
describe('increasing 3 times', function() {
before(function() {
this.instanceThis = this;
return this.someVal = 0;
});
beforeEach(function() {
return this.someVal += 1;
});
return describe('going deeper', function() {
before(function() {
return this.someVal += 1;
});
beforeEach(function() {
return this.someVal += 1;
});
return it('has increased someVal to 3', function() {
return this.someVal.should.equal(3);
});
});
});
答案 0 :(得分:6)
我不知道任何版本的Mocha会运行您在问题中显示的代码而不会出错。为了让你的代码能够工作,必须这样编写:
require("chai").should();
describe('increasing 3 times', function() {
before(function() {
this.someVal = 0;
});
beforeEach(function() {
this.someVal += 1;
});
describe('going deeper', function() {
var parent_ctx = this.parent.ctx;
before(function() {
parent_ctx.someVal += 1;
// The line above is equivalent to this:
// this.test.parent.ctx.someVal += 1;
});
beforeEach(function() {
parent_ctx.someVal += 1;
});
it('has increased someVal to 3', function() {
parent_ctx.someVal.should.equal(3);
// The above line is equivalent to this:
// this.test.parent.parent.ctx.someVal.should.equal(3);
});
});
});
传递给describe
的函数内部以及传递给describe
块(before
,beforeAll
等等的钩子的函数){{1}的值是一个“上下文”对象,它与this
及其所有自己的挂钩相同(不是其他 describe
的挂钩嵌套在其中的调用)。因此,当您分配到describe
时,它会分配给上下文。如果要在嵌套调用this
中访问此上下文,或者在测试中,则必须向上走describe
树并测试对象。</ p>
我会按照第二个Rikudo建议的方式完成相同的操作:使用一个作用于最上面的describe
调用的变量。为了完整起见:
describe
答案 1 :(得分:2)
this
不是您认为的那样。 this
在每个function() {}
块中被重新定义(除非Mocha以某种我不熟悉的特定方式调用它们)。
你想要的是使用范围:
describe('increasing 3 times', function() {
var someVal; // Initialization.
before(function() {
someVal = 0; //No need to return from before()
});
beforeEach(function() {
someVal += 1;
});
describe('going deeper', function() {
before(function() {
someVal += 1;
});
beforeEach(function() {
someVal += 1;
});
return it('has increased someVal to 3', function() {
someVal.should.equal(3);
});
});
});
此外,您不需要return
这么多。实际上,您几乎不必返回测试代码。