Create a Jest test environment with MongoDB and TypeScript, following the guidance provided in the Jest documentation

While attempting to set up a simple test file following the jest documentation, I encountered several linter errors:

https://i.sstatic.net/bAPjC.png

connection:

The type 'Promise<MongoClient> & void' is missing properties such as '{ db: (arg0: any) => any; close: () => any; }': db, closets(2739)

globalThis.MONGO_URI_:

Element implicitly has an 'any' type because type 'typeof globalThis' lacks an index signature.ts(7017)

useNewUrlParser:

No overload matches this call. Overload 1 of 4, '(url: string, callback: Callback<MongoClient>): void', gave the following error. Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'Callback<MongoClient>'....

I tried setting up a global.d.ts (following these solutions) file with the given declarations below:

export interface globalThis {}
declare module globalThis {
    var __MONGO_URI__: string;
    var __MONGO_DB_NAME__: string;
}

export interface global {}
declare global {
    var __MONGO_URI__: string;
    var __MONGO_DB_NAME__: string;
}

Although I initially believed this solved the globalThis.__MONGO_URI__ error, it reappeared after restarting VS Code.

package.json dependencies:

 "dependencies": {
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "node-cron": "^3.0.0",
    "snoostorm": "^1.5.2",
    "snoowrap": "^1.23.0",
    "mongodb": "^4.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.18.2",
    "@babel/preset-env": "^7.18.2",
    "@babel/preset-typescript": "^7.17.12",
    "@shelf/jest-mongodb": "^3.0.1",
    "@types/express": "^4.17.13",
    "@types/jest": "^27.5.1",
    "@types/mongodb": "^4.0.7",
    "@types/node": "^17.0.36",
    "@types/node-cron": "^3.0.1",
    "@types/request": "^2.48.8",
    "jest": "^28.1.0",
    "jest-environment-node": "^28.1.0",
    "ts-jest": "^28.0.3",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.7.2"
  },

Answer №1

Personally, I found success by utilizing process.env.MONGO_URL in place of globalThis._MONGO_URI_:

connection = await MongoClient.connect(process.env.MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})

This approach allows for testing with the database provided by the library @shelf/jest-mongodb.

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

Display the current date in YYYY/MM/DD format using a single method in React and TypeScript

Is there a better way to retrieve YYYY/MM/DD data using just one method? I attempted the following: date = created_at // from API const sendDate = `${String((date.getMonth() + 1)).padStart(2, '0')}${String(date.getDate()).padStart(2, '0&apos ...

How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element: <span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight"> {{ list}} < ...

Can you explain the purpose of the fix unwind operation in MongoDB?

Just a heads up - I've included some screenshots after running code on my PC. Even though I've encountered this issue multiple times, I still can't quite wrap my head around it In this MongoDB $unwind tutorial for nodejs at the 11:10 minute ...

What is the best way to store user home addresses in MongoDB: embedding or referencing?

After researching various forums and blog posts, I have yet to come across a definitive answer regarding the schema structure for MongoDB when referencing another collection. Consider a user collection where each user is associated with a single address ( ...

Regular expression for the validation of emails using a delimiter

Can someone help me create a regex expression for emails? This is what I have so far: \S+@\S+\.\S+ I want to repeat this X times with a ; separator. Any ideas on how to achieve this? For example, the pattern should allow strings like: ...

Sorry, the server cannot be reached at the moment. Please try again later

Recently delving into Node.js and just getting started on using MongoDB. Currently establishing a connection with my MongoDB Cluster that I have set up. const dbURI = 'mongodb+srv://testuser:<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

Creating an endless scrolling feature with Ionic 3

My tech stack includes symfony3 and FosRestBundle for the backend, and Ionic 3 for the frontend development. While attempting to implement an InfiniteScroll feature following the Ionic documentation, I encountered an issue where only the loading text and ...

Tips for testing screen orientation using jest and testing-library/react

While testing a component in nextJs using testing-library/react and jestJs, I encountered an error when trying to access "window.screen.orientation.type". The error message read: "TypeError: Cannot read properties of undefined (reading 'type')". ...

Issue: The function "MyDocument.getInitialProps()" needs to return an object containing an "html" prop with a properly formatted HTML string

Check out my project on GitHub at https://github.com/Talita1996/NLW4 To start the project, I used the command yarn create next-app project_name I made changes to some files by modifying their extensions and adding new code Next, I added typescript to the ...

Tips for configuring the global API baseUrl for useFetch in Nuxt 3

Is there a way to globally set the baseUrl used in the useFetch composable, possibly through nuxt.config.ts? How can I prevent having to specify it in each individual useFetch call? ...

Is it possible to calculate the length of a slice or map in MongoDB and Golang without having to load the data into memory

Within my research labs, I possess the following: { "_id" : ObjectId("57e602ada35ea4db6e4eee27"), "areas" : [ "nanotech", "robotics" ] } The query at hand is: db.labs.find({"_id" : ObjectId("57e602ada35ea4db6e4eee27")},{areas: ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

Expanding a Zod object by merging it with a different object and selecting specific entries

Utilizing Zod, a TypeScript schema validation library, to validate objects within my application has led me to encounter a specific scenario. I find myself in need of validating an object with nested properties and extending it with another object while se ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Get information from MongoDB based on a specific date

I am facing a challenge with my app that has 2 models linking specific leagues to matches. I want to create a query that retrieves all upcoming leagues with matches. How should I proceed - by modifying the model structure or changing the query approach? Th ...

I am having trouble locating my source code within the Typescript module

My issue lies with a file called Server.js, which holds the code for export class Program and includes <reference path='mscorlib.ts'/>. However, when I compile it using the command: tsc -t ES5 Server.ts --module commonjs --out Server.js T ...

Using `querySelector` in TypeScript with Vue 3

Encountered a TypeScript error while using the Vue Composition API let myElement = document.querySelectorAll('my-element') The TS error I'm getting when trying to access it like this: Property '_props' does not exist on type ...

Error: Monger encountered a CompilerException due to java.lang.ClassNotFoundException for the org.bson.types class during the attempt to connect to

Encountered an issue while trying to establish a connection to Mongo using Monger: Received a CompilerException with the error message "java.lang.ClassNotFoundException: org.bson.types" In my project.clj, I have included the dependency [com.novemberai ...

Creating a bullet list from a dynamically parsed object: step-by-step guide

Here is my JSON string foo_json_string: [{"foo_name":"foo_value"},{"foo_name1":"foo_value1"}] I am trying to parse it and display it as an HTML list. This is the method I attempted: <ul> <li v-for=" ...