假设我想测试一个用户登录控制器,该控制器通过SMS与Twilio发送登录代码。我应该如何设置测试,以便我可以模拟Twilio并查看它发回的代码。我的方法是代理twilio客户端对象并使用sinon监视它,但我认为我没有完全正确。
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);
}
}
测试文件
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()
答案 0 :(得分: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');
}));