Test exceeded the maximum allowable time of 5000 ms in the jest timeout error message

I encountered a timeout error while running a unit test case for a controller. I was mocking the request, response, and next, but jest threw an error during the test run.

Can anyone assist me in resolving this issue?

employee.controller.ts

import { Request, Response, NextFunction } from 'express';
import { employeeService } from './employee._service';

const empServices = new employeeService();

module employeeController {
    export async function getEmployee(req: Request, res: Response, next: NextFunction) {
        try {
            const result = await empServices.getEmployee();
            res.send(result);
            return result;
        }
        catch (err) {
            console.log(err);
            res.statusCode = 200;
            res.send("error in getEmployee: " + err);
        };
    };
}
export { employeeController }

employee.controller.spec.ts

import { Request, Response, NextFunction } from 'express';
import { employeeController } from '../employee.controller';
import { employeeService } from '../employee._service';

describe("should return pong message", () => {
    const service = new employeeService();
    it("should return pong message", async () => {

        const mockRequest: any = {
            body: jest.fn(),
            params: jest.fn()
        };

        const mockResponse: any = {
            json: jest.fn(),
            status: jest.fn(),
        };

        const mockNext: NextFunction = jest.fn();

        const spy = jest.spyOn(service, 'getEmployee').mockResolvedValueOnce([]);
        const comments = await employeeController.getEmployee(mockRequest, mockResponse, mockNext);
        expect(comments).toEqual([]);
        expect(spy).toHaveBeenCalledWith()
        expect(spy).toHaveBeenCalledTimes(1)
    });
});

screenshot of error

Thanks

Answer №1

If you're looking for a solution that has helped me in the past, try adjusting the timeout value to better fit your requirements. For instance, you can set it to 60 seconds like so:

beforeEach((): void => {
    jest.setTimeout(60000);
    ...
  });

https://github.com/facebook/jest/issues/11607

Answer №2

If you're using CRA, one helpful tip is to incorporate jest.setTimeout(ms) into the setupTests file. This action can enhance the global timeout, especially when facing multiple failing tests for similar reasons.

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

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

Can Express Handlebars be used solely for rendering a partial without including a layout?

I have successfully configured express handlebars with the following folder structure: views/ layouts/ partials/ User Search Partial HTML (located in views > partials) <div id="user-search"> <h1>Search Users</h1> </ ...

Is it possible to designate a Typescript generic type as a tuple with equal length to that of another tuple?

Imagine having a function that takes in a dataset which is an array of (identically-typed) tuples: type UnknownTuple = any[] function modifyDataStructure<T extends UnknownTuple>(list: T[]) { ... } The goal is to define a second argument with the ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...

Angular does not support the transmission of nested objects within objects

When I use Angular.js to send this JSON to my node.js/express.js service: { "name": "MyGuitar", "type": "electric", "userid": "123", "likes": 0, "dislike": 0, "guitarParts": { "body": { "material": "/content/img/hout.jpg", "_id": "5566d6af ...

"Every time you run mat sort, it works flawlessly once before encountering an

I am having an issue with a dynamic mat table that includes sorting functionality. dataSource: MatTableDataSource<MemberList>; @Output() walkthroughData: EventEmitter<number> = new EventEmitter(); @ViewChild(MatSort, { static: true }) sort ...

When the first element of an array is undefined, Angular's ngFor will not render anything

We have an array called stringArray: var stringArray = new Array(); stringArray[1] = 'one'; In Angular, the ngFor directive displays nothing when stringArray[0] is undefined. How can this issue be resolved? ...

"Enhancing your coding skills: Implementing Typescript in your Redux

Below are the various types of action creators available: export type Calculation = { type: string; }; export type AddAndSubtract = { type: string; value: number; }; export type GetUserInput = { type: s ...

What is the best way to retrieve ejs data within a form when implementing express?

When a user requests, the following HTML file is displayed in the code below. I also need to access the values of clubname and type inside the app.post() function in my app.js file. <!DOCTYPE html> <html> <head> <title><%= t ...

Printing array of API results in NodeJS using ExpressJS

I have been working with the Twitter API to retrieve tweets and store them in an array. I am looking to print the entire array on my HTML document for display purposes. Excited to see it work! Thanks! Check out the code snippet below: var express = requi ...

send data to a hyperlink

I need to pass a parameter to the href based on the first name in the list. The names are links to another page that I retrieve via an _id passed in the URL. The issue I am facing is that the id is not being passed to the URL, resulting in an error. How ...

storing data in a nested child object within an array

I am attempting to include variables into the existing JSON data that is received from an API whenever a user clicks on the add button. However, I encountered this error message: Cannot find a differ supporting object '[object Object]' of type & ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

Tips for accessing a nested object field in JavaScript

Trying to access the field names of an object nested within another object is causing an issue. In this scenario, attempting to loop through the user object was unsuccessful as an error stating Object is possibly 'null' or 'undefined' w ...

Angular 6's tslint feature is generating duplicated warnings and errors for every issue detected

After updating to Angular 6, I've noticed that every tslint error and warning is showing up twice. The versions are Tslint 5.10.0, Angular CLI 6.0.0, Typescript 2.7.2, and Codelyzer 4.3.0. Here's an example of the duplicated errors: ERROR: file. ...

Is it possible to trigger useEffect only after the data has been successfully fetched?

Every time I try to fetch data from the backend mongodb, I encounter an issue where the useEffect only renders once. This causes a delay in fetching the data, resulting in numerous undefined errors. const [xnaLogData,setXnaLogData]=useState([]); const [xna ...

Trouble with Nodemailer functionality on Heroku deployment

Utilizing nodemailer to send emails from my server with express worked flawlessly on localhost. However, after deploying it on Heroku, it seems to not support nodemailer anymore (based on my research). Below is the code, any assistance on resolving this is ...

Is it possible to access Vuex Store from a Node.js environment?

I am trying to access a state from the server and update the twitterName using a mutation once determined. I have already set up a getter, but when I attempt to import the store into my JavaScript file, I encounter an error. How can I successfully import a ...