如何在unit testing中用sinon / proxyquire或node.js中的依赖关系模拟twilio

说我想testing一个用户login控制器,通过短信与Twilio发送login代码。 我应该如何设置testing,以便我可以嘲笑Twilio,看看它发回的代码。 我的方法就是恳求客户对象,并用sinon窥探它,但我认为我没有把它做得很正确。

控制器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); } } 

testing文件

 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() 

我很晚才回答,但这可能会帮助某人。

我没有使用proxywire,但它似乎非常相似rewire(只是看你的代码)。 您应该尝试以下操作:

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

我更习惯重新布线。 npm i rewire --save-dev 。 使用rewire你可以尝试以下:(概念保持不变)

在你的testing中:

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