[英]Mocha 'this' in before and beforeEach hooks
使用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);
});
});
});
我不知道任何版本的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
等)的值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);
});
});
});
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
那么多。 實際上,您幾乎不必返回測試代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.