Stub方法的构造函数属性

问题描述 投票:0回答:1

我正在尝试对使用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并得到了类似的结果。我看不出任何迹象表明我正在使用深层嵌套方法。

typescript mocha twilio sinon chai
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.