Currently, I am in the process of writing unit tests for a function that utilizes the twilio-node package to send SMS messages. The specific function I am focusing on testing, both for arguments passed and number of times called, is Twilio.prototype.messages.create
.
sendText.ts
const twilio = new Twilio('ACfakeName', 'SomeAuthToken');
// This section needs to be stubbed
try {
await twilio.messages.create({body: 'something', to: `1234567890`, from: '1234567890' });
}
catch (e) {
console.log('An error occurred 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);
});
When executing this code, the test fails with a callCount
value of 0. I am uncertain about how mocha handles these situations, as it appears that if there is a test failure, no logs are displayed. If I eliminate the expect
statement, it seems like the actual twilio.messages.create
method is being invoked, resulting in the following log:
An error occurred 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 attempted using sinon.createStubInstance
with similar outcomes. There is no clear indication that I am successfully stubbing the deeply nested method.