如何使用Sinon.js存根dynamic对象方法?

我有以下模块。

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; 

我遇到sc.send方法的问题。 如何使用sinon.js正确覆盖这一点? 或者,也许我需要更换sendcloud模块?

       

网上收集的解决方案 "如何使用Sinon.js存根dynamic对象方法?"

您需要使用proxyquire 模块或proxyquire 模块 。

这里是使用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(); }); }); });