如何在我正在测试的方法中模拟模块
的实例?
方法示例:
var item = require('item'); // module to mock
// underTest.js
module.exports = {
parse: function(model) {
return new item(model).parse();
}
}
我想模拟 item
模块并断言已调用 parse
方法。
我的测试套件使用 sinon
和 mocha
任何实现这一目标的示例将不胜感激。
最佳答案
也许你可以通过扩展原型(prototype)来创建一个Mock
// yourmock.js
var item = require("item")
exports = item
exports.parse = function() {
//Override method
}
编辑
举个例子。您有一个请求外部 API 的 NodeJS 应用程序。例如我们有Stripe来完成信用卡支付。此付款由 payment.js 对象完成,其中有一个 processPayment 方法。您期望在回调中返回一个 bool 值。
原始文件可能如下所示:
// 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)
}
因为您希望在测试期间处理 strip 时没有问题,所以需要模拟此函数,以便可以在请求服务器没有任何延迟的情况下使用它。
您可以做的是使用相同的功能,但您接管请求服务器的功能。因此,在真实环境中,您期望带有错误和 bool 值的回调,而此模拟将为您提供这一点。
// 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);
}
这对你来说是不是更容易理解?
关于node.js - 模拟 NodeJs 模块的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582459/