Testing with Jest after establishing a connection with MongoDB: A step-by-step guide

I am currently in the process of setting up testing for various routes within my Express server that rely on connectivity to my MongoDB database.

I am facing a challenge in structuring the Jest file to enable seamless testing. In my regular index.js file, I import the app and execute app.listen within the connect .then call, as shown below:

const connect = require("../dbs/mongodb/connect");

connect()
   .then(_ => {
      app.listen(process.env.PORT, _ => logger.info('this is running')
   })
   .catch(_ => logger.error('The app could not connect.');

I attempted to replicate the same setup in my test.js files, but it did not yield the desired results.

Here is an example:

  const connect = require("../dbs/mongodb/connect");
  const request = require("supertest");

  const runTests = () => {
    describe("Test the home page", () => {
      test("It should give a 200 response.", async () => {
        let res = await request(app).get("/");
        expect(res.statusCode).toBe(200);
      });
    });
  };

  connect()
    .then(_ => app.listen(process.env.PORT))
    .then(runTests)
    .catch(err => {
      console.error(`Could not connect to mongodb`, err);
    });

Is there a way to ensure a connection to MongoDB is established before executing my tests?

Answer №1

After encountering some issues, I realized that there were a couple of adjustments I needed to make. To begin with, I had to ensure that my .env file was loaded before running the tests. This was achieved by creating a jest.config.js file at the root of my project:

module.exports = {
  verbose: true,
  setupFiles: ["dotenv/config"]
};

Next, in the testing suite itself, I implemented the use of beforeEach to establish a connection to the MongoDB server.

const connect = require("../dbs/mongodb/connect");
const app = require("../app");
const request = require("supertest");

beforeEach(async() => {
  await connect();
});

describe("Executing the test", () => {
  test("Verifying functionality", async done => {
    let res = await request(app).get("/home");
    expect(res.statusCode).toBe(200);
    done();
  })
});

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

Setting up dynamic routes in a Vue.js Express application

I am currently working on a project that involves creating a basic Vue.js Express profile interface. This interface is responsible for retrieving profile information of a specific user based on a unique ID assigned to each user. The .get() request in Vue.j ...

Working with MongoDB in Express using Mongoose

I am currently working with express js and mongoose, storing data in a collection named 'users'. I'm curious about how to change the name of the collection. Below is the snippet of my code: app.post('/signup', (req, res, next) =&g ...

Retrieve the id within the parentheses for each checkbox that is checked and re-check each time a checkbox is selected using Kendo UI

Working with the tricky kendo-ui has made adding selectors quite challenging; however, my current task involves simply obtaining the inner contents of the id selector upon clicking an input checkbox element. Specifically, I need to extract the text between ...

Having trouble accessing jQuery function within WordPress

Why is there a ReferenceError: Error message that says "manualEntry is not defined," appearing while trying to use the code snippet below in a Wordpress environment? <a href="#" onclick="manualEntry()">hide</a> <script ...

Encountering a problem in Express where headers cannot be set after already being sent to the client

The goal of the code is to verify a password by comparing it with the one stored in the database and then return the result. However, regardless of what I try, it keeps giving the same error message. Using Express JS: app.post('/', (req, res) =& ...

A simple way to deactivate a React component (or the onClick event itself) using the onClick event

I have come across similar inquiries, but unfortunately, none of the solutions provided seem to work in my particular scenario. I am hopeful that someone can shed some light on what might be causing the issue. In my ReactApp, there are 3 card components t ...

Having trouble serving static files with express.Router?

With my file system becoming more complex, I decided to switch from using app.use(express.static()) to utilizing express.Router(). Initially, I thought I could just replace app.use(express.static()) with router.use(express.static()), but unfortunately, thi ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Mongodb's feature allows for the creation of a field in a document that calculates the sum of various values

Is there a way to create a function that calculates the total number of coins for a specific user in MongoDB? I came across the $add operator, but I'm struggling to implement it effectively. Note: I'm working with MongoDB, Mongoose, Node.js, and ...

Ways to incorporate various time intervals between individual slides in bxslider

Can individual delay times be set between each slide in a bxslider? For example, having a 1000ms delay between the 1st and 2nd slide, and a 2000ms delay between the 3rd and 4th slide. Is it feasible to achieve this? ...

React application not functioning on localhost:3000 despite successful compilation with no errors, only displaying the title on localhost but failing to show any content

I recently started developing a new website with React. Everything was running smoothly on localhost until I made some changes, and now the homepage content is not displaying when I visit localhost:3000. I suspect there may be an issue with my routing or s ...

Validating a single field for City, State, and ZIP in jQuery/JavaScript

I am trying to validate an input field that requires City, State (two letter abbreviation), and ZIP code (5 numeric digits) in the format 'City, State ZIP'. Could someone please help me with validating this specific format and characters? Appre ...

Storing a Nested Struct in Rust mongodb Triggers an Error: The `From<T>` Trait is Missing for `Bson`

I've defined a struct to represent an Item, but some of its fields rely on another struct. I'm looking to store this nested object in MongoDB using the MongoDB Rust Driver. (https://github.com/mongodb/mongo-rust-driver) use mongodb::bson::do ...

Troubleshooting Coffeescript Jasmine-Node Tests in Webstorm/Intellij

Using node-jasmine 2 beta4 and writing in Coffeescript, I have successfully set up my tests to run in Intellij 13.1 by configuring the following Run Settings: Node interpreter: /usr/local/bin/node Working Dir: [Project Directory] Javascript File: node_mo ...

AngularJS Bootstrap Datepicker populating date from input field

I'm currently utilizing Bootstrap for my web application. I've developed a method that initializes all input fields of type date with a class called form_datetime: function initDatepicker(){ $(".form_datetime").datepicker({ ...

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

What is the best way to transform an array of strings into a JSON object?

When navigating back to a list page, I want to make sure that the filter criteria are still retained. My solution involves using cookies, which are set when the form filter is submitted. In the list page's mounted hook, I retrieve the specific cookie ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

Using Javascript in the Model-View-Controller (MVC) pattern to load images stored as byte

Despite the numerous solutions available on Stack Overflow, I am still unable to get any of them to work... I am faced with the challenge of setting the "src" attribute of an image tag using a byte array obtained from an ajax call to my controller in Java ...