Jest mock module request causing a timeout issue

I am encountering an issue with the code snippet below in my application

request.ts

import request from 'request'

export const funcA = async ( apiToken: string, body: any): Promise<any> => {
    return new Promise((resolve, reject) => {
        const options = {
            method: 'POST',
            url: `https://any_url?api_token=${apiToken}`,
            body: {
                ...body,
            },
            json: true,
        }
        request(options, (err, resp, body) => {
            if (err) {
                log('funcA', err)
                reject(err)
            } else resolve(body)
        })
    })
}

test.ts

import { funcA } from '../funcApath'
import request from 'request'

jest.mock('request')

describe('funcA test', () => {
    test('should call funcA example', async () => {
        const options = await optionsConstructor()
        const mockRequest = await request(options)
        const body = await bodyConstructor()
        const apiToken = 'any_apiToken'
        const result = await funcA(apiToken, body)
        expect(mockRequest).toHaveBeenCalledTimes(1)
    })
})

Here is the error I encountered:

Error: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

I have attempted using the "beforeEach function" but without success. Any suggestions on how to resolve this issue? Thank you!!

Answer №1

It is crucial to ensure that your mock still triggers the callback provided when mocking a request; otherwise, your promise will remain unresolved.

Within your test.ts file:

import { funcA } from '../funcApath'
import request from 'request'

const mockRequest = jest.fn().mockImplementation((options, cb) => cb());
jest.mock('request', () => (options, cb) => mockRequest(options, cb));

describe('funcA test', () => {
    test('should call example of funcA', async () => {
        const options = await constructOptions()
        const response = await request(options)
        const body = await constructBody()
        const apiToken = 'any_apiToken'
        const result = await funcA(apiToken, body)
        expect(mockRequest).toHaveBeenCalledTimes(1)
    })
})

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

Having difficulty initializing a new BehaviourSubject

I'm struggling to instantiate a BehaviourSubject I have a json that needs to be mapped to this Typescript class: export class GetDataAPI { 'some-data':string; constructor (public title:string, public description:string, ...

Incorporating OpenLayers and TypeScript: Issue with Event.map.forEachFeatureAtPixel, where the argument type is not compatible with the parameter type

I am currently attempting to implement Open Layers v7.2.2 with TypeScript. {When not using TypeScript, the code functions properly} function OnMapClick(event: MapBrowserEvent<UIEvent>) { event.map.forEachFeatureAtPixel(event.pixel, function(curren ...

How can I resolve a bug in Nuxt2 when using TypeScript?

I need help with implementing code using Nuxt.js 2 option API with TypeScript. computed: { form: { get: () => this.value, set: (value) => this.$emit('input', value) } } Additionally, I am encountering the fo ...

Tips on pairing elements from a ngFor processed list with another list using ngIf

If we have a list such as the one shown below: elements = [ { id: 1, name: "one" }, { id: 3, name: "three" }, { id: 5, name: "five" }, { id: 6, name: "six" }, ]; lists = [ { id: 5, name: "five" }, { id: 9, ...

A guide on transitioning from using require imports to implementing ES6 imports with the concept of currying

Currently in the process of migrating a Node/Express server to TypeScript. I have been using currying to minimize import statements, but now want to switch to ES6 import syntax. How can I translate these imports to ES6? const app = require("express")(); ...

Translate Typescript into Javascript for use in React applications

Can anyone assist me in converting this Typescript code to Javascript? function ImageMagnifier({ src, width, height, magnifierHeight = 100, magnifieWidth = 100, zoomLevel = 1.5 }: { src: string; width?: string; height?: string; magnifie ...

Ways to modify the datepicker format in Angular Material

I am currently facing an issue with the date format generated by the angular material datepicker...Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time) My requirement is to receive the date in either (YYYY-MM-DD) or (YYYY-MM-DDTHH:mm) format. Here is ...

Leveraging the power of NestJS in conjunction with Apollo Server version 2

I recently delved into learning nestjs and decided to give this graphql example a try. The issue I encountered is that the example was originally designed for apollo-server version 1, and I'm having difficulty adapting it to work with apollo-server v ...

Uploading Files through Reactive Forms in Angular

I tried following a tutorial on integrating file upload functionality into my reactive form, which can be found at the following link: . However, I've encountered an issue where I'm getting an error message stating "this.onChange is not a functio ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Clicking the button fails to trigger the modal popup

Upon clicking a button, I am attempting to open a modal popup but encountering an error: The button click works, however, the popup does not appear after the event. test.only('Create Template', async({ page })=>{ await page.goto('h ...

Best location to define numerous dialog components

Currently, I have 8 custom Modals that are called in various places within my app. These modals are currently located inside the app.component.html as shown below: <agc class="app-content" [rows]="'auto 1fr'" [height]=" ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Next.js Error: Inconsistent text content between server-rendered HTML and hydration. Unicode characters U+202F versus U+0020

Having issues with dates in Next.js development. Encountering three errors that need to be addressed: Warning: Text content did not match. Server: "Tuesday, January 24, 2023 at 11:01 AM" Client: "Tuesday, January 24, 2023 at 11:01 AM" ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

Can anyone suggest a more efficient method for validating checkbox selection in Angular?

I am working with an angular material stepper, where I need to validate user selections at each step before allowing them to proceed. The first step displays a list of 'deliveries' for the user to choose from, and I want to ensure that at least o ...

populating an array with objects

I am working with an array of objects var photos: Photos[] = []; The structure of Photos [] is as follows interface Photos { src: string; width: number; height: number; } I have a component that requires an array of strings export type PhotosArr ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

Using Ionic to send email verification via Firebase

I have encountered an issue while attempting to send an email verification to users upon signing up. Even though the user is successfully added to Firebase, the email verification is not being sent out. Upon checking the console for errors, I found the f ...