Guide to simulating Twilio with Jest and TypeScript to perform unit testing

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.

Answer №1

To mimic the class that the module returns, you should utilize

jest.mock('twilio', mockImplementation)
. In the mockImplementation function, create a constructor function that accepts your account SID and auth token as arguments. This constructor function should then return a mockClient implementation. The mockClient object needs to have a messages property, which is an object containing a create property that is a mock function.

The easiest way to understand this concept is by looking at the code example below.

const mockClient = {
  messages: {
    create: jest.fn().mockResolvedValue({ ...smsMessageMock });
  }
};

jest.mock("twilio", () => {
  return function(accountSid, authToken) {
    return mockClient;
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

Discover the method for retrieving information through AJAX requests and dynamically displaying or hiding content based on the received

Currently, I'm in the process of developing a PHP script that outputs a numerical value indicating the number of unread messages. The snippet below showcases my code that triggers the PHP function every 30 seconds: setInterval(function (){ ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Backing up a mongodb collection can be easily achieved with the help of express.js and Node.js

I am looking to create a monthly backup of my userdatas collection. The backup process involves: I intend to transfer the data from the userdatas collection to a designated backupuserdatas collection. A batch program should be scheduled to run automatica ...

Tips for resolving the 'node-gyp rebuild' problem on Windows 10

While attempting to incorporate a node NPM dependency into my project, I encountered an issue with node-gyp rebuild, which I have already reported. I am aware of a potential solution from this Stack Overflow post, but unfortunately it is not effective for ...

The component is expected to return a JSX.Element, however it is failing to return any value

The issue lies with this component: const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => { props.map((item, index) => { return <a href={item.href} key={index}>{item.name}</a> }) }; export default Naviga ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

React function failing to utilize the latest state

I'm facing an issue with my handleKeyUp function where it doesn't seem to recognize the updated state value for playingTrackInd. Even though I update the state using setPlayingTrackInd, the function always reads playingTrackInd as -1. It's p ...

Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with: { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name": "test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "fr ...

The chosen state does not save the newly selected option

Operating System: Windows 10 Pro Browser: Opera I am currently experiencing an issue where, upon making a selection using onChange(), the selected option reverts back to its previous state immediately. Below is the code I am using: cont options = [ ...

Nodejs cookie settings

I am currently working on a small petition project and I want to implement a feature where a user who signs the petition will have a cookie set so that when they try to access the page again, they are redirected to a "thanks page". If the user has not sign ...

When publishing, TypeScript-compiled JS files fail to be included, even though they are included during the build process in Debug and Release modes

My .NET MAUI project includes TypeScript files in the Scripts\scriptfiles.ts folder, which are compiled into wwwroot\js\scriptfiles.js. Everything functions properly until my client attempts to publish it, at which point all script files go ...

object passed as value to competent parent

I'm facing an issue where I am trying to pass a value to the parent component, but it is returning an object instead of the expected value. Here's what I have: Child Component render() { return ( this.props.data.map((val, idx) => { ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

Node.js bypasses unit test validation

As a beginner in BDD with Node.js, I have a controller function defined as follows: var getUser = function(username, done) { console.log('prints'); User.findOne({ 'local.username': username }, function (err, user) { ...

Iterate through an array and append individual elements to a fresh array - ensuring only a single item is present in the new

I have been working on a project where I need to call a backend API and retrieve a JSON response. I have come across various solutions, but none seem to address my specific problem. The JSON data returned from the API is structured like this: [ { ...

Create dynamic cells for CSS grid using JavaScript

I have been manually generating grid cells in a specific pattern by copying and adjusting <div> elements. Although this method works, I am interested in creating an algorithm that can automatically generate the desired layout. The left box in the exa ...

Exploring AngularJS and Jasmine: Testing a controller function that interacts with a service via $http

I encountered an issue while testing a controller that relies on a service. The problem arises because the service is currently set to null in order to focus solely on testing the controller. The current test setup is failing due to the BoardService being ...

Using PHP to reset variables for dynamic display in JavaScript

I've been working on retrieving values from a database and storing them in JavaScript variables. While I was successful in accomplishing this task, I encountered an issue when the values in the database are updated - the values of the variables remain ...