4

Say I want to test a a user login controller that sends login codes via SMS with Twilio. How should I set up the test so that I can mock Twilio and see what codes it's sending back. My approach was to proxyquire the twilio client object and spy on it with sinon, but I don't think I'm getting it quite right.

controller user.js

var smsClient = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));

module.exports = {
  checkCode: function(phone){
        var code = getNewCode();
        smsClient.sms.messages.create({
            from: config.get('twilio_phone_number'),
            to: phone,
            body: 'Your code :' + code
        }, callback);
  }
}

test file

var twilioMock = //what goes here??
var smsSpy = sinon.spy(twilioMock.sms.messages, 'create');
var User = proxyquire('../models/user', { 'mongoose': mongooseMock, 'smsClient': twilioMock }); 

... some describe and it statements ...
twilioMock.sms.messages.should.have.been.calledOnce()  //this is where I don't know what I should be checking

// or is this the right way? 
//smsSpy.should.have.been.calledOnce()
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

1 Answers1

2

I am answering this very late but this might help someone.

I haven't used proxywire but it seems very similar to rewire (just by looking at your code). You should try the following:

var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));

I am more used to rewire. npm i rewire --save-dev. Using rewire you may try the following: (concept remains the same)

In your test:

var rewire = require('rewire');
var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
var userController = rewire('./path_to_user.js') // notice use of rewire

beforeEach(function(){
    this.smsClient = twilioMock; // `this` is available within your tests
    userController.__set__('smsClient', this.smsClient);
});

it('should something', sinon.test(function(){
    var smsSpy = this.spy(this.smsClient.sms.messages, 'create');
}));
Lucky Soni
  • 6,811
  • 3
  • 38
  • 57