假设我想测试一个用户登录控制器,该控制器通过 SMS 使用 Twilio 发送登录代码。我应该如何设置测试,以便我可以模拟 Twilio 并查看它发回的代码。我的方法是代理获取 twilio 客户端对象并使用 sinon 监视它,但我认为我做得不太正确。
控制器用户.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()
我很晚才回答这个问题,但这可能会对某人有所帮助。
我没有使用过 proxywire,但它看起来与 rewire 非常相似(只需查看您的代码)。您应该尝试以下操作:
var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
我更习惯重新接线。
npm i rewire --save-dev
。使用重新接线,您可以尝试以下操作:(概念保持不变)
在您的测试中:
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');
}));
Twilio 同时提供了一种自己执行此操作的方法:
https://www.twilio.com/docs/openapi/mock-api- Generation-with-twilio-openapi-spec