模拟NodeJs模块的实例

时间:2014-12-20 17:11:53

标签: node.js mocking sinon

如何在我正在测试的方法中模拟module的实例?

方法示例:

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

// underTest.js
module.exports = {

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

}

我想模拟item模块并断言已调用parse方法。

我的测试套件使用sinonmocha任何示例来实现,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

也许你可以通过扩展原型来创建一个模拟

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

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

修改

一个例子。您有一个请求外部API的NodeJS应用程序。例如,我们有Stripe来完成信用卡付款。这笔付款由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和boolean的回调,这个mock会为你提供。

// 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);
} 

这可能更容易理解吗?