2017-08-21 26 views
-3

我的代碼:摩卡測試中sinon.test()中的this是什麼?

it('should', sinon.test(function() { 
    console.log(this); // what `this` refer here? 
    ... 
})); 

在上面的代碼,什麼this指在sinon.test()功能?

我試圖登錄,但是得到了錯誤:

TypeError: Converting circular structure to JSON

興農版本:1.17.6

歡迎任何意見。謝謝。

UPDATE

閱讀下面的答案後,我仍然感到困惑。爲什麼當this.myOnject.log僅存在一次時,以下兩段代碼有效?

it('should', sinon.test(function() { 
    const stubLog = this.stub(this.myObject.log, 'warn'); 
    // ... 
    this.myObject.process(); 
    // expect codes... 
    })); 


    it('should', sinon.test(function() { 
    const stubLog = sinon.stub(this.myObject.log, 'warn'); 
    // ... 
    this.myObject.process(); 
    // expect codes... 
    })); 

UPDATE

如果downvoted,請留下一些評論,讓我知道你爲什麼downvoted。我對發佈的問題感到非常困惑。但我更爲困惑,爲什麼這麼多人低調,但沒有留下任何有用的評論。

回答

0

sinon.test創建用於測試一個新的Sinon sandbox增強該摩卡傳遞到與特定的興農-方法如spystub等,其調用該自動是沙箱的相應方法測試正常this對象創建。它增加對象的事實允許您仍然使用摩卡通常在this上提供的所有庫存摩卡方法,並允許您在任意字段上設置值。測試結束時,會自動調用沙盒的restore方法。這是一種提供測試之間隔離的便捷方式,因此一次測試通過Sinon執行的通用對象修改不會影響其他測試。

下面是一個例子:

const sinon = require("sinon"); 

before(function() { 
    // We set "moo". 
    this.moo = "I'm a cow."; 
}); 

it("test", sinon.test(function() { 
    // We can access "stock" Mocha functions. 
    this.timeout(0); 

    // However, this is augmented with sinon functions. 
    const spy = this.spy(); 
    spy(); 

    // We can access "moo"; 
    console.log("value of moo", this.moo); 
})); 

這產生:

value of moo I'm a cow. 
    ✓ test 

    1 passing (34ms) 

上面的代碼假定興農1.x的在Sinon 2.x及以上sinon.test不再與Sinon捆綁在一起,而是自己獨立的package

+0

謝謝。 'sinon.test()'中的'sinon.stub()'和'this.stub()'有什麼區別? – BAE

+0

區別在於'sinon.test()'中的'this.stub()'使用沙箱。如果你只是調用'sinon.stub()',你不會從sanbox中受益,那麼你必須自己執行任何必要的清理。 – Louis