2014-12-20 114 views
1

如何在我測試的方法中模擬module的實例?模擬模塊的一個實例NodeJs

方法例如:

var item = require('item'); // module to mock 

// underTest.js 
module.exports = { 

    parse: function(model) { 
     return new item(model).parse(); 
    } 

} 

我想模擬的item模塊和斷言parse方法被調用。

我的測試套件使用sinonmocha任何可以實現的例子都將被理解。

回答

1

也許你可以通過擴展原型

// yourmock.js 
var item = require("item") 

exports = item 
exports.parse = function() { 
    //Override method 
} 

編輯

一個例子創建一個模擬。您有一個請求外部API的NodeJS應用程序。例如,我們有條紋來完成信用卡付款。該付款由payment.js對象完成,並且在那裏您有一個processPayment方法。您預計boolean會在回調中回來。

原始文件可能看起來像:

// payment.js 
exports.processPayment = function(credicardNumber, cvc, expiration, callBack) { 
    // logic here, that requests the Stripe API 
    // A long time processing and requesting etc. 
    callback(err, boolean) 
} 

因爲你想有在測試過程中處理條紋沒有問題,你需要模擬這個功能,這樣它可以在不請求服務器的任何延遲使用。

你可以做的是使用相同的功能,但你接管了請求服務器的功能。因此,在真實環境中,您期望使用Error和布爾值進行回調,並且此模擬將爲您提供該回調。

// paymentMock.js 
var payment = require('./payment'); 

// exports everything what normally is inside the payment.js functionality 
exports = payment 

// override the functionality that is requesting the stripe server 
exports.processPayment = function(creditCardNumber, cvc, expirationDate, callBack) { 
    // now just return the callback withouth having any problems with requesting Stripe 
    callBack(null, true); 
} 

這可能對您更容易理解嗎?

+0

非常感謝保羅,但我在節點測試方面比較新,你可以給我一個例子,你如何測試這個小方法。你認爲正確的方法是覆蓋他的默認方法來做出預期嗎? Cheerse – Fabrizio

+0

@Fabrizio我編輯了答案,也許你會對我試圖解釋你的事情有更多的瞭解? –