首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >构造函数属性的存根方法

构造函数属性的存根方法
EN

Stack Overflow用户
提问于 2019-03-07 22:12:48
回答 1查看 234关注 0票数 1

我正在尝试对一个使用twilio-node包发送短信的函数进行单元测试。我尝试测试的函数是Twilio.prototype.messages.create,无论是传入的参数还是调用的次数。

sendText.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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,因为我得到了以下日志:

代码语言:javascript
复制
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,也有类似的结果。我看不到任何迹象表明我正在截断深度嵌套的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-09 23:32:34

我会将Twillio的实例注入到您的类中。然后,在测试时,您可以创建类的存根:

代码语言:javascript
复制
class myClass{
    constructor(twillio){
        this.twilio = twilio;
    }

    //functions using twillio here
}

然后,您可以生成一个存根:

代码语言:javascript
复制
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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55045851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档