模拟一个模块NodeJs的实例
如何在我正在testing的方法中模拟一个module
的实例?
方法示例:
var item = require('item'); // module to mock // underTest.js module.exports = { parse: function(model) { return new item(model).parse(); } }
我想嘲笑item
模块并声明parse
方法已被调用。
我的testing套件使用sinon
和mocha
任何例子来实现,将不胜感激。
也许你可以通过扩展原型来创build一个模拟
// yourmock.js var item = require("item") exports = item exports.parse = function() { //Override method }
编辑
一个例子。 您有一个请求外部API的NodeJS应用程序。 例如,我们有条纹来完成信用卡付款。 这个付款是由payment.js对象完成的,并且在那里你有一个processPayment
方法。 你期望一个boolean
在callback中回来。
原始文件可能如下所示:
// 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) }
因为在testing过程中你想要处理分段没有问题,所以你需要模拟这个函数,这样就可以在没有任何请求服务器的延迟的情况下使用它。
你可以做的是使用相同的function,但你接pipe了请求服务器的function。 所以在真实的环境中,你期待一个错误和布尔值的callback,这个模拟会为你提供。
// 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); }
这对你来说可能更容易理解吗?