Guide on configuring Jest to utilize a setup file for running beforeEach in numerous test files

Currently, I am facing an issue with my testing setup. I have two Models that I am testing in separate files, where I make use of beforeEach to clear and seed the database, and afterEach to drop the database and close the MongoDB connection.

The problem arises when I encounter a MongoDB error regarding duplicate keys for my users, indicating that the beforeEach operation is not executed properly before each test. Interestingly, if I run the files individually, everything works fine; it's only when running the entire test suite.

user.test.js

const mongoose = require('mongoose');
const request = require('supertest');
const app = require('../app');

const User = require('../models/user.model');
const userData = require('../db/data/userData');

// Valid User for Loggin In
// {
//  username: 'Bcrypt User',
//  password: 'YECm9jCO8b',
// };

beforeEach((done) => {
  mongoose.connect(process.env.DB_URI, () => {
    const seedDB = async () => {
        await User.deleteMany({});
        await User.insertMany(userData);
    };

    seedDB().then(() => {
        done();
    });
  });
});

afterEach((done) => {
  mongoose.connection.db.dropDatabase(() => {
    mongoose.connection.close(() => done());
  });
});

message.test.js

const mongoose = require('mongoose');
const request = require('supertest');
const app = require('../app');

const User = require('../models/user.model');
const userData = require('../db/data/userData');

const messageData = require('../db/data/messageData');
const Message = require('../models/message.model');

const validUserAccount = {
  username: 'Bcrypt User',
  password: 'YECm9jCO8b',
};

beforeEach((done) => {
  mongoose.connect(process.env.DB_URI, () => {
    const seedDB = async () => {
        await User.deleteMany({});
        await User.insertMany(userData);
        await Message.deleteMany({});
        await Message.insertMany(messageData);
    };

    seedDB().then(() => {
        done();
    });
  });
});

afterEach((done) => {
  mongoose.connection.db.dropDatabase(() => {
    mongoose.connection.close(() => done());
  });
});

I have attempted setting up a jest.config.js file and configuring package.json, but I am struggling to find a way to set up a global setup file to run some code before each test.

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

Encountering a "MongoDB error: An error occurred during DNS resolution: proto error: unreachable network" message while attempting to migrate MongoDB with Prisma

Currently, I am working on an application using NextJS with the Prisma ORM and MongoDB as the database. My MongoDB cluster is free and shared, hosted in MongoDB Atlas cloud. To allow anyone to connect to the database, I have added 0.0.0.0/0 to the network ...

What is the best method for displaying a field nested within an object in MongoDB?

I am currently practicing using the "sample_mflix" database provided by MongoDB Atlas and the MongoDB VS Code extension. Here is my code snippet: use('sample_mflix'); db.movies.aggregate([ { $lookup: { from: 'comments', ...

Troubleshooting checkbox problem with AJAX request in PHP

Experiencing an issue with a simple AJAX call that checks if a checkbox is checked. Currently, regardless of whether the checkbox is checked or not, it always prints "not checked". I've attempted changing the "POST"/"GET" methods in the PHP code, howe ...

Implement a document update for a Map value in a MongoDB collection

I am dealing with a document named myPortCollection { "_id" : ObjectId("55efce10f027b1ca77deffaa"), "_class" : "myTest", "deviceIp" : "10.115.75.77", "ports" : { "1/1/x1" : { "portId" : "1/1/x1", healthStat ...

Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks: / | client //housing sta ...

What is the process for retrieving the data from the POST request body on the client side?

Greetings to all, I am a student who is still in the process of learning and have a question about passing data from server to client. Currently, I have an Arduino sensor that sends POST requests containing sensor data to an express server. The server suc ...

Executing asynchronous functions on a local Windows 10 machine with NodeJS

I am currently facing difficulty running an asynchronous function obtained from a Google example alongside Environment Variables on my Windows 10 system. I have set up a bucket on GCS and uploaded my .raw file. Furthermore, I have created a .env file with ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

The conditional statement is failing to execute properly in the JavaScript AJAX response

When checking the value in the alert, it always shows as 'Initial'. However, the condition if(checkoption == 'Initial') always returns false. The actual code is as follows: function changeItem(id,item,option) { var xhttp; xht ...

Utilize a JavaScript function on an element that is generated dynamically

I am encountering an issue with my autocomplete function. It works perfectly fine for the input field with the id "field10" that is already created. However, when I dynamically generate new input fields, the function does not seem to work on them. I have ...

Calculate the size of an array containing non-consecutive indices

Have you ever noticed how JavaScript's .length property calculates the length of an array by adding one to the last numerical index? Do you know a solution for accurately determining the element length of arrays with non-consecutive indexes? //Perf ...

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

Obtain text nodes along with their corresponding parent elements in sequential order (more challenging than anticipated)

Let's take a look at this coding example: <div>Hello, my <span>name</span> is John</div> I am trying to extract both text nodes and their parent elements in sequential order. Here's how it should look: 1: "Hello, my ", ...

What is the best way to include a ref objectId in a Node.js application?

Main Model { name: { type: String, trim: true, required: true }, carModels: [{ type: ObjectId, ref: 'CarModel' }] } Second Model { name: { type: String, trim: true, required: true ...

Achieving dynamic population of a second dropdown menu based on selection from the first dropdown menu using PHP

In my current project, I am faced with the task of populating three different menus. The first menu is generated using a MySQL query in PHP and displays TV shows like "Modern Family" or "Dexter". What I want to achieve is that once a TV show is selected fr ...

Revamping the current text for the circle feature in ProgressBar.js

I am working on a project where I use ProgressBar.js to generate a circle with a percentage displayed in the center. While the circle renders correctly initially, I'm facing an issue when trying to update the text (percentage) after running it again w ...

When an anchor link is dynamically created, the `click()` method does not activate the click event

After creating an anchor element using the document.createElement('a') method, I encountered an issue where the click event was not being triggered as expected. To provide more context, refer to the code snippet below: var link = document.create ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

Ways to substitute a single parameter within Vue.js router

We are working on a complex multi-level multi-tenant application, where the hostname is used to identify the 'supplier' account and the customer account is included in the URL structure. For example, our routes are structured like this: /:local ...

How can I retrieve a formController in AngularJS?

When trying to reset the data in a form and calling form.setPristine(), I encounter an issue where the formController is not registered within the $scope. It may sound like a basic question, but how can I locate the formController? Within the code snippe ...