2014-12-20 115 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我编辑了答案,也许你会对我试图解释你的事情有更多的了解? –