【问题标题】:How to stub a dynamic object method using Sinon.js?如何使用 Sinon.js 存根动态对象方法?
【发布时间】:2016-06-19 16:18:13
【问题描述】:

我有以下模块。

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 模块?

【问题讨论】:

  • 试试stub = sinon.stub(SendCloud.prototype, 'send');

标签: javascript node.js unit-testing sinon


【解决方案1】:

你需要使用proxyquiremodulerewiremodule

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

【讨论】:

  • 谢谢你,阿列克谢!
猜你喜欢
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2016-12-02
  • 2017-07-12
  • 2012-01-09
  • 2020-07-01
  • 2016-08-16
相关资源
最近更新 更多