1

For the following snippet of nodejs code, how would I stub the send method using proxyquire and sinon, given that this belongs to file index.js? I have tried many ways but constantly get errors.

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;
                    }
                });

So far in my tests I have the following set-up, but get 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
      }
    }
  }
});
hyprstack
  • 4,043
  • 6
  • 46
  • 89

1 Answers1

6

Looks like you're almost there. Just assign connectStub instead:

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

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

When connectStub is called, it will return the sendStub, which will in turn be immediately invoked.

EDIT:

Right, sorry - make connectStub return an object.

tandrewnichols
  • 3,456
  • 1
  • 28
  • 33
  • I have tried that, it returns an error: `Uncaught TypeError: Object stub has no method 'send'`. I think the issue is that `connect` is not a function, but an object. – hyprstack Apr 30 '15 at 16:08
  • @hyprstack `connect` _is_ a function; it takes an object. The issue was needing to _return_ an object with a `send` stub, instead of the `send` stub directly. – tandrewnichols Apr 30 '15 at 18:09
  • Makes sense. I totally thought that would solve my issues. Now my tests are timing-out. – hyprstack Apr 30 '15 at 19:32
  • Is that a followup question? What are you doing with `sendStub`? – tandrewnichols Apr 30 '15 at 19:56
  • I had a similar problem but with the extra complexity of ES6 destructuring assignment. You have to add a destructuring brace wrapper around the top level proxyquire setting, e.g. 'emailjs': { emailJs: { //everything else the same in here }} – – starmandeluxe Jul 11 '19 at 05:34