简体   繁体   中英

How to stub a dynamic object method using Sinon.js?

I have following module.

var Sendcloud = require('sendcloud');
var sc = new Sendcloud("key1","key2","key3");

var service = {};

service.restorePassword = function (params, cb) {
if (!params.to || !params.name || !params.token) {
  throw "Miss params"
}

var defaultTemplate = adminBaseUrl + "reset/token/" + params.token;

var subject = params.subject || "Letter";
var template = params.template || defaultTemplate;

// Send email
sc.send(params.to, subject, template).then(function (info) {
 console.log(info)
if (info.message === "success") {
  return cb(null, "success");
} else {
  return cb("failure", null);
}
});

};

module.exports = service;

I experience problems stubbing sc.send method. How to correctly cover this point using sinon.js? Or maybe I need to replace sendcloud module?

You need to use proxyquire module or rewire module .

Here an example of using proxyquire

 var proxyquire = require('proxyquire'); var sinon = require('sinon'); var Sendcloud = require('sendcloud'); require('sinon-as-promised'); describe('service', function() { var service; var sc; beforeEach(function() { delete require.cache['sendcloud']; sc = sinon.createStubInstance(Sendcloud); service = proxyquire('./service', { 'sendcloud': sinon.stub().returns(sc) }); }); it('#restorePassword', function(done) { sc.send.resolves({}); var obj = { to: 'to', name: 'name', token: 'token' }; service.restorePassword(obj, function() { console.log(sc.send.args[0]); done(); }); }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM