【问题标题】:Targeting nested method with sinon and proxyquire使用 sinon 和 proxyquire 定位嵌套方法
【发布时间】:2015-07-10 10:28:37
【问题描述】:

对于nodejs 代码的以下 sn-p,我将如何使用 proxyquiresinon 存根 send 方法,假设这属于文件 index.js? 我尝试了很多方法,但总是出错。

var emailjs = require("emailjs");
emailjs.server.connect({
                    user: obj.user,
                    password: obj.password,
                    host: obj.host,
                    port: obj.port,
                    tls: obj.tls,
                    ssl: obj.ssl
                })
                    .send(mailOptions, function(error, message){
                    if (error) {
                        console.log("ERROR");
                        context.done(new Error("There was an error sending the email: %s", error));
                        return;
                    } else {
                        console.log("SENT");
                        context.done();
                        return;
                    }
                });

到目前为止,在我的测试中,我有以下设置,但得到Uncaught TypeError: Property 'connect' of object #<Object> is not a function

readFileStub = sinon.stub();
sendStub = sinon.stub();
connectStub = sinon.stub().returns(sendStub);

testedModule = proxyquire('../index', {
  'fs': {readFile: readFileStub},
  'emailjs': {
    'server': {
      'connect': {
         'send': sendStub
      }
    }
  }
});

【问题讨论】:

    标签: node.js sinon proxyquire


    【解决方案1】:

    看起来你快到了。只需指定connectStub

    readFileStub = sinon.stub();
    sendStub = sinon.stub();
    connectStub = sinon.stub().returns({
      send: sendStub
    });
    
    testedModule = proxyquire('../index', {
      'fs': {readFile: readFileStub},
      'emailjs': {
        'server': {
          'connect': connectStub
        }
      }
    });
    

    connectStub被调用时,它会返回sendStub,而sendStub又会被立即调用。

    编辑:

    对,对不起 - 让 connectStub 返回一个对象。

    【讨论】:

    • 我试过了,它返回一个错误:Uncaught TypeError: Object stub has no method 'send'。我认为问题在于connect 不是一个函数,而是一个对象。
    • 感谢@CaptEmulation
    • @hyprstack connect 一个函数;它需要一个对象。问题是需要返回一个带有send 存根的对象,而不是直接使用send 存根。
    • 有道理。我完全认为这会解决我的问题。现在我的测试超时了。
    • 这是一个后续问题吗?你在用sendStub做什么?
    猜你喜欢
    • 2018-08-12
    • 2021-01-21
    • 2017-08-02
    • 2020-10-24
    • 2021-02-16
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多