Reputation: 5947
How can I mock an instance of a module
in a method that I'm testing?
Method example:
var item = require('item'); // module to mock
// underTest.js
module.exports = {
parse: function(model) {
return new item(model).parse();
}
}
I would like mock the item
module and assert that the parse
method has been called.
My test suite use sinon
and mocha
any example to achieve that will be appreciated.
Upvotes: 1
Views: 520
Reputation: 659
Maybe you can create a Mock through extending the prototype
// yourmock.js
var item = require("item")
exports = item
exports.parse = function() {
//Override method
}
EDIT
An example. You have a NodeJS application that request an external API. For example we have Stripe to complete a credit card payment. This payment is done by the payment.js object and in there you have a processPayment
method. You expect a boolean
to come back inside a callback.
The original file could look like:
// 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)
}
Because you want to have no problems with handling stripe during tests, you need to mock this function so that it can be used without any delays of requesting servers.
What you can do is use the same functionality, but you take over the functions that request the server. So in the real environment you expect a callback with an Error and boolean and this mock will provide you that.
// 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);
}
Is this maybe easier for you to understand?
Upvotes: 1