如何使用Sinon.js对动态对象方法进行存根?

3

我有以下模块。

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;

我在 stub sc.send 方法时遇到了问题。如何使用 sinon.js 正确地覆盖这个点?或者我需要替换 sendcloud 模块吗?


1
尝试使用 stub = sinon.stub(SendCloud.prototype, 'send'); - undefined
1个回答

5

您需要使用proxyquire 模块rewire 模块

以下是使用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();
    });
  });
});


谢谢你,Alexey! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接