Mad*_*mme 10 javascript mocha.js
使用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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
我不知道任何版本的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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
内传递给函数describe
,并传递给一个的钩子的功能describe
块(before
,beforeAll
等)的值this
是"上下文"对象这对于相同的describe
和它的所有的自己的挂钩(不钩其它 describe
嵌套调用在里面).因此,当您分配时this
,它会分配给上下文.如果要在嵌套调用中describe
或在测试中访问此上下文,则必须向上遍历树describe
和测试对象.
我会按照第二个Rikudo建议的方式完全相同:使用一个作用于最上面describe
调用的变量.为了完整起见:
require("chai").should();
describe('increasing 3 times', function() {
var someVal;
before(function() {
someVal = 0;
});
beforeEach(function() {
someVal += 1;
});
describe('going deeper', function() {
before(function() {
someVal += 1;
});
beforeEach(function() {
someVal += 1;
});
it('has increased someVal to 3', function() {
someVal.should.equal(3);
});
});
});
Run Code Online (Sandbox Code Playgroud)
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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
另外,你不需要return
那么多。事实上,您几乎不需要在测试代码中返回。
归档时间: |
|
查看次数: |
5671 次 |
最近记录: |