2012-11-14 51 views
0

我需要確保在以下所示的UserMock-類中調用了某個方法。我創建了這個模擬版本來注入另一個模塊來防止測試期間的默認行爲。如何訪問此Javascript屬性?

我已經在使用sinon.js,那麼如何訪問諸如isValid()之類的方法並將其替換爲間諜/存根?沒有實例化類可以做到這一點嗎?

var UserMock = (function() { 
    var User; 
    User = function() {}; 
    User.prototype.isValid = function() {}; 
    return User; 
})(); 

謝謝

回答

3
var UserMock = (function() { 
    var User; 
    User = function() {}; 
    User.prototype.isValid = function() {}; 
    return User; 
})(); 

只需通過prototype

(function(_old) { 
    UserMock.prototype.isValid = function() { 
     // my spy stuff 
     return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing 
    } 
})(UserMock.prototype.isValid); 

說明:

(function(_old) { 

})(UserMock.prototype.isValid); 

使一個參考方法isValue到可變_old。關閉是這樣做的,所以我們不會在變量的父範圍內發生。

UserMock.prototype.isValid = function() { 

Redeclares原型方法

return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing 

調用舊方法和結果從它返回。

使用應用放在正確的範圍(this)與傳遞給函數
例如,所有的參數讓。如果我們做一個簡單的函數並應用它。

function a(a, b, c) { 
    console.log(this, a, b, c); 
} 

//a.apply(scope, args[]); 
a.apply({a: 1}, [1, 2, 3]); 

a(); // {a: 1}, 1, 2, 3 
+0

你忘了返回結果。 – xiaoyi

+0

ahha你知道了嗎 – xiaoyi

+0

你介意告訴我在哪裏可以找到關於如何工作的解釋 - 我從來沒有在 – Industrial