我正在尝试对使用twilio-node包发送SMS消息的功能进行单元测试。对于传递的参数和调用的时间,我正在尝试测试的函数是Twilio.prototype.messages.create
。
sendText.ts
const twilio = new Twilio('ACfakeName', 'SomeAuthToken');
// Need to stub this guy
try {
await twilio.messages.create({body: 'something', to: `1234567890`, from: '1234567890' });
}
catch (e) {
console.log('An error while sending text', e);
}
sendText.spec.ts
twilioCreateStub = sinon.stub(Twilio.prototype.messages, 'create');
it('should call twilio.messages.create() once', async () => {
try {
await sendText();
}
catch (e) {
fail('This should not fail.')
}
expect(twilioCreateStub.callCount).to.equal(1);
});
以这种方式运行它会使callCount
为0的测试失败。我不确定mocha如何运行这些代码,但是如果测试失败,它似乎不会显示任何日志。如果我删除了expect
部分,则似乎正在调用真实的twilio.messages.create
,因为我得到了以下日志:
An error while sending text { [Error: The requested resource /2010-04-01/Accounts/ACfakeName/Messages.json was not found]
status: 404,
message:
'The requested resource /2010-04-01/Accounts/ACfakeName/Messages.json was not found',
code: 20404,
moreInfo: 'https://www.twilio.com/docs/errors/20404',
detail: undefined }
我也尝试过sinon.createStubInstance
并获得类似结果。我看不到任何迹象表明我正在使用深度嵌套的方法。
答案 0 :(得分:2)
我会将Twillio的实例注入您的班级。然后在测试时,您可以创建该类的存根:
class myClass{
constructor(twillio){
this.twilio = twilio;
}
//functions using twillio here
}
然后您可以创建一个存根:
const twilioStub = {messages: {create: sinon.stub()}}; //You might want to give this more functions and put it in a seperate file
myClass = new MyClass(twiliostub);
//call function on myClass using twilio
expect(twilioStub.messages.create.callCount).to.equal(1);