Integration of Twilio with Cypress

Posted by: admin September 19, 2023 No Comments
Integration of Twilio with Cypress

“Big goals are exciting to set, right? There’s that rush of optimism as you imagine the outcome.”

Recently I have come across a challenge in one of the projects which requires handling 2fa where it involves SMS verification.
When I started to understand, I quickly discovered and found quality advice is exhausting within a single powerful platform. Twilio uses multiple telecommunications for each route so that messages or calls will get through it.

Twilio allows developers to programmatically make and receive calls, send and receive text messages, and other communication functions using its web service APIs.

Cypress:

Cypress is a tool for developing end-to-end tests and running them. It rotates the browser, visits your application, and it works through a set of predefined steps like a normal user. Finally, it verifies that what you’d expect is the outcome.
Compared to unit and integration tests, these types of tests are slow, but they do an amazing job of making sure that your app works for the end-user as expected. You shouldn’t write too many of them, but you should try to cover the main tracks of your application instead.

Twilio:

Twilio is an app that connects phone lines to your device. This means we can create apps that can call, using our code to text. It enables software developers to use its web service APIs to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions.
Twilio is a service-based cloud communications platform (PaaS), here, we will use Twilio to read the SMS that our Web App will send.
There are many other tools (such as bandwidth, plivo, sinch, or nexmo) out there that too are worth considering.

Pre-requisites for Integration:

  • VS Code.
  • Node.js
  • NPM (It will get installed automatically with installing node.js)
  • Cypress

Installing Cypress:
To install Cypress, NPM must first be installed in your environment. NPM is the JavaScript package manager and the biggest program registry in the world. If NPM is missing, Please install the NPM here by following instructions.
(https://www.npmjs.com/get-npm)

After installing NPM, use the command within your project directory to run the following command:

npm install cypress --save-dev

Once you are done with installing cypress in your project then let’s jump on Twilio installation in the cypress project so that we can use Twilio services to fetch SMS.

Trigger the below command to install Twilio:

npm install twilio

Once the Twilio installation is done then we can fetch messages. Let’s create a test where users need to enter an OTP code to get logged in successfully.

Integrate Twilio with Cypress

We are going to create a test where the browser will be launched with a triggering URL. enter username and password then clicking on the sign-in button.
After clicking on the sign button, the user has enabled 2fa(Two Factor authentication) for getting logged in successfully so it will wait for a specific time to find the MFA input field. As soon as it finds the MFA input field it will wait for the OTP code which it has sent on the Twilio number.

 

As we can see in the above screenshot, we are calling “waitForOTPCode” function which contains the definition of get SMS from Twilio and storing it in a code variable to reuse.

So, let’s see the definition of “waitForOTPCode” method down below in the table.

import promisify from "cypress-promise";
import axios from "axios";

const accountSid = "twilio account id";
const token = "twilio token";
const MESSAGES_LIMIT = 10;
const WAIT_MILLISECONDS = 7000;

export default class Twilio {
async getOtp() {
if (!accountSid || !token) {
throw new Error(
`twilioAccountSID or twilioAuthToken environment variables aren't defined!`
);
}
const response = await promisify(
axios.get( `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json?PageSize=${MESSAGES_LIMIT}`,
{
auth: {
username: accountSid,
password: token,
},
}
)
);
return response.data.messages.filter((message) => {
const isInbound = message.direction === "inbound";

if (isInbound) return true;
return isInbound && message.body.includes();
})[0];
}

async OTPCodeFromLastMessage() {
const lastMessage = await promisify(this.getOtp(accountSid, token));
const matches =
lastMessage && lastMessage.body && lastMessage.body.match(/\d+/gi);
return matches ? matches[0] : null;
}

async waitForOTPCode(milliseconds = WAIT_MILLISECONDS) {
cy.wait(milliseconds);

return await this.OTPCodeFromLastMessage();
}}

Axios :

Axios is a popular, promise-based HTTP client that supports an easy-to-use API and can be used in both the browser and Node. js. Making HTTP requests to fetch or save data is one of the most common tasks a client-side JavaScript application will need to do.
As we can see we are using Axios to make an API request to get messages from Twilio and also we can limit the number of messages by providing the message limit in API requests which reduces our time and makes things easier to handle 2fa (Two-factor authentication).

Leave a Reply