Mocha experiences a timeout when the method attempts to parse the body of the

Preamble: Despite looking at this question on Stack Overflow, I did not find any helpful solutions. The suggested solution of using async and await did not resolve the issue for me.


This TypeScript test was created using Mocha and Supertest:

it('returns 400 when redirectURL is missing', async () => {
  const isAuthorized = (_req: Request) => true;
  const hooks = { onPostAuth: async (_req: Request) => {} };
  const app = createApp(isAuthorized, hooks);

  await request(app)
    .post('/')
    .set('Content-Type', 'application/json')
    .send({ }) // Body is missing redirectURL

    .expect(400);
});

The test failed as expected:

  1) POST
       returns 400 when redirectURL is missing:
     Error: expected 400 "Bad Request", got 200 "OK"

Here is the current state of the HTTP API:

export function createApp(
  isAuthorized: (_: Request) => boolean,
  hooks: { onPostAuth: (_: Request) => any; })
{
  const app = express();
  const authorize = createAuthorizationHandler(isAuthorized);

  app.post("/", authorize, async (req, res) => {
    const result = await hooks.onPostAuth(req);
    return res.send(result);
  })

  return app;
}

After adding an if statement to handle missing properties, the test started failing with a timeout error:

  3) POST
       returns 400 when redirectURL is missing:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\Users\mark\Documents\Criipto\fusebit-extensibility\tests\index.test.ts)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7)

I encountered this issue even without any actual logic inside the if statement. Why is this happening and how can I fix it?


Simply accessing req.body.redirectURL seems to trigger the timeout problem:

app.post("/", authorize, async (req, res) => {
  if (!req.body.redirectURL) {
  }

  const result = await hooks.onPostAuth(req);
  return res.send(result);
})

Despite the empty condition in the if statement, the test continues to hang and time out.

Answer №1

Big shoutout to cdimitroulas for pointing out that I forgot to configure Express for parsing request bodies. Just had to include this line of code:

app.use(express.json());

And just like that, the issue was resolved.

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

Subclass method overloading in Typescript

Take a look at this example: class A { method(): void {} } class B extends A { method(a: number, b: string): void {} } An error occurs when trying to implement method() in class B. My goal is to achieve the following functionality: var b: B; b.met ...

Implementing Firebase for OTP verification in an Express API backend

Currently I am working on authenticating phone numbers using Firebase OTP in my NodeJS Express API. The data is being stored in MongoDB and now I also need to integrate Firebase. Can anyone provide guidance on how to add Firebase to my NodeJS application ...

When attempting to utilize expo-av in a React-Native project on iOS, the recorded MP4 file encountered an issue when trying to submit it as form data for Open

I've been working tirelessly through the night, trying to record myself on my iPhone using expo-av to capture speech and then upload it to openai's transcriptions endpoint with the whisper-1 model. The recording is saved as an mp4 file, which I ...

Cannon-js: Experience dynamic body bouncing on the y axis as it reacts to force applied on the x and z axes

Currently, I am working on an FPS game where the player controller applies force based on keyboard inputs to a dynamic cannon body. The angular dampening is set to 1 on the player body. The PlayerController class takes both the player class (which extends ...

Controlling CSS Styles in Angular using TypeScript

Currently, I am working on an Angular project that involves dynamically populating a calendar. In addition to this, I have a range of dates and the task at hand is to modify the background for specific days within this date range. To manage dates effective ...

Email attachments not functioning properly with Nodemailer

I'm encountering an issue while trying to send an attachment via email using Nodemailer. I keep getting an "Unexpected identifier" error for attachments. It seems like Node.js is not recognizing the "attachments" property. Is there something else that ...

I am encountering an issue with importing modules from the public folder in Next.js when using TypeScript, as I am

I've been running into an issue with importing files in Next.js using TypeScript. I'm trying to use regular imports with custom absolute paths, but I keep getting a module not found error. Oddly enough, my IDE is able to locate the file when I cl ...

What is preventing me from setting headers after a redirect?

After making a json request in ExpressJS (node), this is the callback function I use: function handleQuestion(req, res){ request(req, res, function(response){ //redirect to the right url if page doesn't exist. var params = app.req ...

Error encountered while attempting to utilize 'load' in the fetch function of a layer

I've been exploring ways to implement some pre-update logic for a layer, and I believe the fetch method within the layer's props could be the key. Initially, my aim is to understand the default behavior before incorporating custom logic, but I&ap ...

Leveraging external Javascript files in Ionic framework version 3 and above

Hey there, I'm currently working on integrating the Mapwize SDK, an external Javascript library, with the latest version of Ionic. I've encountered the common challenge of getting Javascript to function smoothly with Typescript. Although I'm ...

There is no index signature in the type 'string | number | EnvType' that accepts a parameter of type 'string'

Can someone help me troubleshoot this issue with config[curr][targetEnv] ??? interface EnvType { dev: string; staging: string; production: string; } type Config = { [key: string]: number | string | EnvType; }; const config: Config = { network ...

What is the process for parameterizing a tuple in coding?

In my scenario, I have a tuple with interrelated types. Specifically, it involves an extractor function that retrieves a value, which is then used as input for another function. What I envision conceptually looks like this code snippet, although it does n ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

Efficient Searching with Typescript and Lodash: Boosting Performance with Arrays and Objects

I am faced with the challenge of converting between two classes called MyObject and MyObjectJSON, which have helper methods to assist in the conversion process: myObj.toJSON() and MyObject.fromJSON(). Currently, I have instances of these classes represent ...

Unable to display information stored in the Firebase database

I am struggling with a frustrating issue. My goal is to showcase the information stored in the Firebase database in a clear and organized manner, but I'm having trouble achieving this because it's being treated as an object. getData(){ firebas ...

GlobalsService is encountering an issue resolving all parameters: (?)

I am currently working on implementing a service to store globally used information. Initially, the stored data will only include details of the current user. import {Injectable} from '@angular/core'; import {UserService} from "../user/user.serv ...

The interface is incompatible with the constant material ui BoxProps['sx'] type

How can I make the interface work for type const material ui? I tried to register an interface for sx here, but it keeps giving me an error. import { BoxProps } from '@mui/material'; interface CustomProps { sx: BoxProps['sx&apo ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...

What causes TypeScript to malfunction when using spread in components?

What is the reason for typescript breaking when props are sent to a component using a spread statement? Here's an example code snippet: type SomeComponentProps = Readonly<{ someTitle: string }> const SomeComponent = ({ someTitle }: SomeCompo ...

Trouble arises when attempting to transfer cookies between server in Fastify and application in Svelte Kit

In the process of developing a web application, I am utilizing Fastify for the backend server and Svelte Kit for the frontend. My current challenge lies in sending cookies from the server to the client effectively. Despite configuring Fastify with the @fas ...