使用sinon和proxyquire定位嵌套方法

hyp*_*ack 1 node.js sinon proxyquire

对于下面的代码片段nodejs,我将如何send使用proxyquire和存根该方法sinon,因为它属于文件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;
                    }
                });
Run Code Online (Sandbox Code Playgroud)

到目前为止,在我的测试中,我有以下设置,但得到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
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

tan*_*ols 6

看起来你几乎就在那里.只需指定connectStub:

readFileStub = sinon.stub();
sendStub = sinon.stub();
connectStub = sinon.stub().returns({
  send: sendStub
});

testedModule = proxyquire('../index', {
  'fs': {readFile: readFileStub},
  'emailjs': {
    'server': {
      'connect': connectStub
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

connectStub调用它时,它将返回sendStub,然后立即调用它.

编辑:

对,抱歉 - connectStub返回一个对象.