我正在尝试对一个使用twilio-node包发送短信的函数进行单元测试。我尝试测试的函数是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,也有类似的结果。我看不到任何迹象表明我正在截断深度嵌套的方法。
发布于 2019-03-09 23:32:34
我会将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);https://stackoverflow.com/questions/55045851
复制相似问题