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.