2013-08-23 38 views
2

是否有一種方法來對一個Mongoose模型的虛擬屬性進行存根?對Mongoose模型的虛擬屬性進行存根

假設Problem是一個模型類,並且difficulty是虛擬屬性。 delete Problem.prototype.difficulty返回false,並且該屬性仍然存在,所以我無法用我想要的任何值替換它。

我也試過

var p = new Problem(); 
delete p.difficulty; 
p.difficulty = Problem.INT_EASY; 

它沒有工作。

分配未定義Problem.prototype.difficulty或使用sinon.stub(Problem.prototype, 'difficulty').returns(Problem.INT_EASY); 會拋出異常「類型錯誤:無法讀取財產‘範圍’的未定義」,而這樣做

var p = new Problem(); 
    sinon.stub(p, 'difficulty').returns(Problem.INT_EASY); 

將拋出一個錯誤「類型錯誤:試圖包裝字符串屬性難度作爲功​​能「。

我運行的想法。幫幫我!謝謝!

回答

2

貓鼬internally usesObject.defineProperty所有屬性。由於它們被定義爲不可配置,所以它們不能被delete所識別,也不能被re-configure所識別。

你能做什麼,不過,是覆蓋模型的getset方法,這是用來獲取和設置的任何屬性:

var p = new Problem(); 
p.get = function (path, type) { 
    if (path === 'difficulty') { 
    return Problem.INT_EASY; 
    } 
    return Problem.prototype.get.apply(this, arguments); 
}; 

或者,一個完整的示例使用sinon.js:

var mongoose = require('mongoose'); 
var sinon = require('sinon'); 

var problemSchema = new mongoose.Schema({}); 
problemSchema.virtual('difficulty').get(function() { 
    return Problem.INT_HARD; 
}); 

var Problem = mongoose.model('Problem', problemSchema); 
Problem.INT_EASY = 1; 
Problem.INT_HARD = 2; 

var p = new Problem(); 
console.log(p.difficulty); 
sinon.stub(p, 'get').withArgs('difficulty').returns(Problem.INT_EASY); 
console.log(p.difficulty); 
+0

重寫'GET'作品,但與興農磕碰會拋出一個TypeError:無法讀取的未定義的屬性的構造函數「。所以我使用了第一個解決方案。謝謝! –

+0

我發佈了一個適用於我的sinon的完整示例([email protected],[email protected],[email protected])。 –

+0

我在您的示例的problemSchema中添加了'regionId',現在regionId不能在用sinon存根後分配。這就是爲什麼我得到的錯誤,當我嘗試斷言,'[「摩Silversword」,「艾因斯利場」] should.include(p.regionId);' –

0

截至2017年底和當前的Sinon版本,可以通過以下方式來實現僅部分參數(例如,僅適用於貓鼬模型)

const ingr = new Model.ingredientModel({ 
    productId: new ObjectID(), 
    }); 

    // memorizing the original function + binding to the context 
    const getOrigin = ingr.get.bind(ingr); 

    const getStub = S.stub(ingr, 'get').callsFake(key => { 

    // stubbing ingr.$product virtual 
    if (key === '$product') { 
     return { nutrition: productNutrition }; 
    } 

    // stubbing ingr.qty 
    else if (key === 'qty') { 
     return { numericAmount: 0.5 }; 
    } 

    // otherwise return the original 
    else { 
     return getOrigin(key); 
    } 

    }); 

該解決方案是由一羣不同的啓發建議,其中包括由@Adrian海涅

相關問題