MongoMemoryServer - Dealing with Unexpected Errors

Currently, I am conducting tests on a typescript express-mongoose app using jest, supertest, and mongo-memory-server. Interestingly, all the tests are passing successfully, but an error keeps popping up in every test involving mongo-memory-server. It seems like the root cause of this error is the mongoose.disconnect function, yet I have been unable to resolve it so far.

import { MongoMemoryServer } from 'mongodb-memory-server';
let mongoServer: any;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 600000;
describe('createUser', (): void => {
  let mongoServer: any;
  const opts = {}; 
  beforeAll(async () => {
    mongoServer = new MongoMemoryServer();
    const mongoUri = await mongoServer.getConnectionString();
    await mongoose.connect(mongoUri, opts, err => {});
  });

  afterAll(async () => {
    mongoose.disconnect();
    await mongoServer.stop();
  });

  it('creating user', async (): Promise<void> => {
    const email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8bcadbbbc88a5a9a1a4e6aba7a5">[email protected]</a>';
    const username = 'testUser';
    const password = 'testPassword';
    const { userId } = await createUser(email, username, password);
    expect(userId).toBeTruthy();
    expect(typeof userId).toMatch('string');
  });
});
console.error node_modules/jest-jasmine2/build/jasmine/Env.js:289
   Unhandled error
    console.error node_modules/jest-jasmine2/build/jasmine/Env.js:290
      Error [ERR_UNHANDLED_ERROR]: Unhandled error. (MongoNetworkError: read ECONNRESET)
          at Connection.emit (events.js:178:17)
          at Socket.<anonymous> (C:\Users\PC\Desktop\typescript-mern-budget-app\server\node_modules\mongodb-core\lib\connection\connection.js:321:10)
          at Object.onceWrapper (events.js:277:13)
          at Socket.emit (events.js:189:13)
          at emitErrorNT (internal/streams/destroy.js:82:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
          at process._tickCallback (internal/process/next_tick.js:63:19)

Answer №1

whenEverythingIsDone(async () => {
  await stopMango();
  await closeMongooseConnection();
});

Make sure to await both functions to avoid any issues.

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

When the last character in the route is a forward slash, the Express server will load the HTML page with CSS and JavaScript. Conversely, if the last route character

On my second html page model.html, I noticed the following issue: When I include a '/' at the end of my route address in the browser like this: http://localhost:3002/home/model/, the correct html page is loaded, but the css/js files do not load. ...

The Seamless Integration of RESTful APIs and User Sessions

If a RESTful API is stateless, what is the best way to manage user sessions in this scenario? For example, if I have an API that enables users to borrow books without requiring them to log in to browse the collection, how should I handle this situation? ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

What is the best way to verify a field against a set of string values using Typescript in a NestJS application

I currently have an Enum containing various timezones listed below export enum Timezones { 'Europe/Andorra', 'Asia/Dubai', 'Asia/Kabul', 'America/Antigua' } In the DTO file, I am attempting to valid ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

Ensure Jest returns the accurate file paths for images in a TypeScript and React environment

I'm currently developing a React application and I have come across an issue with importing images. My usual method of importing images is as follows: import image1Src from 'assets/img1.png"; For testing purposes, I need to be able to make ...

How can we use Node.js and Express to create routes with functions that accept multiple parameters?

When it comes to Express routes, I often come across different formats and have some questions about passing multiple parameters to app.get(). I am familiar with the standard usage involving a callback function like function(req, res), but I am confused a ...

What is the significance of having multiple route parameters in Express?

The RESTful API provided by cex.io offers a route that can return pairs of all currencies with a variable amount of parameters. In express, how can we achieve similar functionality? Consider the following pseudo code example... app.get('/pairs/:arg ...

Is there a way to track all Angular form controls that have switched between being enabled and disabled?

Summary: When a FormGroup contains a nested FormControl that changes from disabled to enabled or vice versa, the FormGroup is not marked as dirty. Details: How can you identify all form controls within a FormGroup that have switched between being enabled ...

Utilizing TypeScript generic types as a key for an object

function createRecord<T extends string>(key: T): Record<T, string> { return { [key]: 'asdf' }; } Encountering an issue: The type '{ [x: string]: string; }' is not matching with the expected 'Record<T, st ...

What could be causing selenium to struggle in locating specific text on a webpage

In my webpage, I have a "tree menu" that can be opened by clicking on a button. Once the tree menu is open, I need to follow certain steps and click on different titles. For example, I would click on "19,20", then "may", and finally "2". At the top of the ...

Surprising block of text suddenly popped up on the browser screen while I was in the middle of working on

Currently delving into the world of MERN stack and working on a simple project. Everything was going smoothly on localhost until out of nowhere, some garbled text appeared on the screen, hindering my progress. I'm completely stumped as to what this my ...

The npm package has been successfully installed, but VS Code is having trouble locating it

Currently, I am in the process of developing a simple npm package known as type-exception using TypeScript. After successful test runs and publication on NPM, I have been able to install it into another project (project B). However, upon importing it as a ...

What is the process for sending a GET request to a different endpoint using Node.js?

I want to create a Node server where one endpoint can make a GET request to another endpoint within the same server. Here is the code I am using to test this: const express = require('express'); const app=express(); const https=require("https") ...

Unable to catch 404 errors using Express in Node.js

Here is the code snippet: var express = require('express'); var app = express(); app.use(express.static(__dirname + '/public')); app.get('/', function (req, res) { res.sendFile(__dirname + '/public/test-angular.htm ...

Difficulty in establishing connections with modules in the express.js framework

I'm encountering an issue with using express.js submodules and I believe there may be a fundamental aspect of npm that I am overlooking. Following this tutorial to create a basic authentication system. The path to express in my app directory: ./node ...

Issue encountered when using express-session in conjunction with the express framework

Challenge: I encountered an issue while trying to utilize session = require("express-session"). Despite previously installing express-session using npm install express-session, I am prompted with an error message: vishal@rocker:~/clg/project1/node_module ...

Passing properties to a component from Material UI Tab

I have been attempting to combine react-router with Material-UI V1 Tabs, following guidance from this GitHub issue and this Stack Overflow post, but the solution provided is leading to errors for me. As far as I understand, this is how it should be implem ...

"Combining the power of AngularJS2 beta with Spring Boot: the ultimate

I am currently using Atom 1.4.0 with the atom-typescript package to develop AngularJS2 modules in TypeScript. On the backend, I have a spring-boot application for handling the REST APIs. After making changes to the .ts files in Atom, it seems to compile t ...

Error: mangosse is not recognized

Node keeps throwing the error 'ReferenceError: mangoose is not defined' in my face. The culprit seems to be this line: const dogSchema = new mangoose.Schema({ I made sure to install mongoose using npm $ npm i mongoose Check out the code belo ...