Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with:
import { SQSEvent } from "aws-lambda";
import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanager";
export async function sendSms(event: SQSEvent, data: GetSecretValueResponse) {
const secrets = JSON.parse(data.SecretString);
const accountSid = secrets.TWILIO_ACCOUNT_SID;
const authToken = secrets.TWILIO_AUTH_TOKEN;
const twilioNumber = secrets.TWILIO_PHONE_NUMBER;
if (accountSid && authToken && twilioNumber) {
//Create a Twilio Client
const client = new Twilio(accountSid, authToken);
//Loop through all records of the event, where each record represents a message sent from Sqs
for (const record of event.Records) {
const body = JSON.parse(record.body);
const userNumber = "+" + body.number;
//SendMessage function
try {
const message = client.messages.create({
from: twilioNumber,
to: userNumber,
body: body.message,
});
return message;
} catch (error) {
return `Failed to send sms message. Error Code: ${error.errorCode} / Error Message: ${error.errorMessage}`;
}
}
} else {
return "You are missing one of the variables you need to send a message";
}
}
Then I call this function from my index:
I have already conducted some tests, however, they always connect to the actual Twilio API (requiring real token, sid, etc.), and I need to mock the Twilio service so that the function called in my test.ts does not connect to the internet.
(event and data are simulated responses of SqsEvent and GetSecretValueResponse)
When running npm test, it throws an error related to Twilio's authentication because I am passing self-created tokens.
Hence, what I suspect is that the test is making an internet connection and calling the Twilio API.
Your assistance in resolving this issue is greatly appreciated.