Mocha: Dealing with promises that always time out regardless of the specified time limit

Currently, I am tackling a project for an interview where I need to implement an endpoint that allows me to POST an array of products (listings) and have them created or updated accordingly using MongoDB and Mongoose. The issue I am facing revolves around handling Promises correctly as I keep encountering a timeout error during testing. Here is the task in question:

    it.only('should create listings or update them if they already exist, incrementing the quantity with the difference ' +
      'between the current sold_quantity and the initial_sold_quantity', (done) => {
      var iPhone = { ... };
      var samsung = { ... };
      request(app).post('/listings/myEndpoint').send([iPhone, samsung]).expect(200, {
        created: 1,
        updated: 1
      }, done);
    });
exports.myEndpoint = (req, res) => {
  var listings = req.body;
  var created, updated = 0;

  listings.forEach(reqListing => {
    Listing.findOne({ listing_id: reqListing.listing_id })
      .then(foundListing => {
        if (!foundListing) {
          var newListing = reqListing;
          newListing.initial_sold_quantity = newListing.sold_quantity;
          Listing.create(newListing);
          created++;
        } else {
          var newQuantity = reqListing.sold_quantity - foundListing._doc.initial_sold_quantity;
          if (foundListing._doc.quantity != newQuantity) {
            foundListing._doc.quantity = newQuantity;
            foundListing.save();
            updated++;
          }
        }
      });
      return {
        created: created,
        updated: updated
      };
  });
};

MY TROUBLESHOOTING EFFORTS:

  1. Extending time limit. I attempted adjusting the default timeout for Mocha tests, but regardless of whether it's set to 2 seconds or 20 seconds, the test still times out.

  2. Separating creation and updates. Even when isolating either action, be it solely updating or creating a product, the timeout remains persistent.

  3. Streamlining logic. Regardless of the code inside the if/else blocks, the timeout persistently occurs. Therefore, even with simplified code like this:

exports.myEndpoint = (req, res) => {
  var listings = req.body;
  var created, updated = 0;

  listings.forEach(reqListing => {
    Listing.findOne({ listing_id: reqListing.listing_id })
      .then(foundListing => {
        if (!foundListing) {
          console.log("creating");
        } else {
          console.log("updating");
        }
      });
      return {
        created: created,
        updated: updated
      };
  });
};

The timeout issue persists.

Answer №1

After reaching out for help in the Nodeiflux Discord community, I was able to discover a solution that may not be the most elegant due to its lack of async/await implementation. However, since I couldn't change the project's style too much, I opted to maintain it without using async/await.

The issue stemmed from a simple oversight:

var created = 0, updated = 0;

where created was not properly initialized.

Instead of utilizing forEach with Promises internally, I realized it was more efficient to use map and move the return statement outside the loop. Additionally, I incorporated Promise.all() to ensure all promises were resolved before returning:

exports.upsert = (req, res) => {
  var listings = req.body;
  var created = 0, updated = 0;
  var allowedArrayLength = 50;
  return Promise.all(listings.map(reqListing =>
    Listing.findOne({
        listing_id: reqListing.listing_id
      })
      .then(foundListing => {
        if (!foundListing) {
          createListing(reqListing);
          created++;
        } else {
          var prevQuantity = foundListing.quantity;
          if (updateListing(reqListing, foundListing).quantity > prevQuantity) {
            updated++;
          }
        }
      })
  )).then(() => ({ created: created, updated: updated }));
};

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

Blend express router by chaining the (.route) method with other HTTP methods like (.get, .post, etc) to create

Here is my code structure: let router = require( 'express' ).Router(); Later on, I define my routes like this: router .route( '/' ) .get( listMiddleware ); router .route( '/:id' ) .get( getOneByIdMiddleware ...

Error in Browserify Express App: Unexpected token while parsing the file

I have been attempting to browserify a javascript file. When I run the command: browserify global.js -o bundle.js An error message is returned: Error: Parsing file C:\ocquiz\public\javascripts\global.js: Unexpected token (756 ...

Sequelize flexible relationship

Is it possible to establish an optional relationship between two tables? For example: I am working with 2 tables: - User (id, siteId, email, ...), where multiple users can have the same email - Wallet (id, email, ...), ensuring one wallet per email addres ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Compatibility of NodeJs Passport package with Linux operating systems

Currently, I am referencing the official documentation found at https://www.npmjs.com/package/passport for details on the Passport package. I am specifically investigating whether this package is suitable for use on a Linux operating system. If anyone ha ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Angular does not receive events from Socket.io

Recently I started coding with AngularJS and decided to build a real-time app using Socket.io: The service I'm using shows that the connection is fine on the console. Here's a picture of the Console.log output However, when I attempt to emit c ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Guide to downloading attachments from Outlook using Node.js

When attempting to download Gmail attachments using a particular code, the process runs smoothly on Windows but encounters an error on Linux. Additionally, I am seeking guidance on how to execute a similar operation for Office Outlook, where authentication ...

Error Handling with NPM and Rails in BrowserifyRails

Trying to launch a local application using ruby on rails has been a bit of a challenge. Initially, when attempting to start the local server, it raised an issue regarding nodejs, despite having successfully installed it. Now, the latest error message encou ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Is it possible to extract a string from a file and import the extracted string into another file using require() in NODE.js?

My file structure looks like this: collegesapp ├── node_modules │ ├── express │ ├── connect │ ├── jade │ └── passport ├── routes │ └── routes.js ├── views │ ├── index.jade │ ...

Fixing problems encountered when asynchronously gunzipping an already read file in Node.js

As a newcomer to the world of node.js and asynchronous programming, I have successfully used promises to read files with fs readFile, but I am struggling with getting zlib Gunzip to function as expected in my Coffeescript code: promisifyRun(fs, 'r ...

Node on Ubuntu not supporting arrow functions with --harmony option

When attempting to use arrow functions in node v0.10.33 on Ubuntu 14.04 (with the --harmony flag enabled), I encountered the following error message: console.log( [1,2,3,4].map(x => x*x) ); ^ SyntaxError: Unexpected token &g ...

Error: The object identified as #<Object> does not support the 'Router' method in node

Hey there! I've been trying to follow a tutorial on creating Chat Roulette using Node.js, Socket.io, and OpenTok from this link. After successfully installing express, I updated the code in my Package.json file as per the tutorial with the following: ...

Combine several pages from PDF files into a single document

I am currently working on developing a small electron application that combines multiple PDF files or pages into one larger page to help save paper when printing several CAD drawings. Essentially, I am looking for a cross-platform solution similar to the ...

Error encountered in pre-middleware hooks when querying Mongoose model with findById due to foreign model reference

Within this scenario, I have two distinct models: Protocol and Comment. Each model incorporates a middleware ('pre' or 'remove') that triggers the other model. The issue arises when attempting to call the Comment middleware in Comment.j ...

Module not found in Node.js Express JS

I've read several topics on this issue here at stackoverflow, but I am still unable to get my node application running. When I try to run the command: node app.js local I receive the following error: Error: Cannot find module './config' ...

Error message: "CORS issue arises in NextJS custom server following execution of 'npm run build'"

Everything was running smoothly until I needed to implement a production build with Server Side Rendering. Unable to utilize "next export," I ran into issues after executing "npm run build." Authentication failures led me to discover that the backend serve ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...