Aarmora
Aarmora

Reputation: 1153

Stub method of a constructor property

I'm trying to unit test a function that is using the twilio-node package for sending SMS messages. The function I'm trying to test, both for arguments passed in and for times called, is 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);


});

Running it like this fails the test with callCount as 0. I'm not sure how mocha runs these but it seems like if there is a test failure it doesn't display any logs. If I remove the expect part, it seems like the real twilio.messages.create is being called, since I get the following logs:

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 }

I have also tried sinon.createStubInstance and have similar results. I can't see any indication that I am stubbing the deeply nested method.

Upvotes: 1

Views: 355

Answers (1)

Atheist
Atheist

Reputation: 525

I would inject the instance of Twillio into your class. Then when testing you can make a stub of the class:

class myClass{
    constructor(twillio){
        this.twilio = twilio;
    }

    //functions using twillio here
}

Then you can make a stub:

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);

Upvotes: 2

Related Questions