I hope you are okay. I am trying to write some tests for my application and I am fairly new to node.js, mongoose, and js in general.
I have this dbconnection file:
const mongoose = require("mongoose");
const logger = require("../utility/logger");
const config = require("config");
const { MongoMemoryServer } = require("mongodb-memory-server");
let mongoServer;
async function connectDB() {
if (mongoose.connection.readyState !== 0) {
await mongoose.connection.close();
}
if (process.env.NODE_ENV === "test") {
if (!mongoServer) {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri);
}
} else {
const url = config.get("db");
await mongoose
.connect(url)
.then(() => logger.info(`Connected to DB: ${url}`))
.catch((err) => logger.error("Could not connect to DB.", err));
}
}
async function disconnectDB() {
if (mongoose.connection.readyState !== 0) {
await mongoose.disconnect();
if (mongoServer) {
await mongoServer.stop();
}
}
}
module.exports = { mongoose, connectDB, disconnectDB };
And the test that I am trying to make it work:
const request = require("supertest");
const app = require("../../../app");
const { User } = require("../../models/userModel");
const {
connectDB,
disconnectDB,
} = require("../../../src/startup/dbconnection");
describe("User Authentication", () => {
let userPayload;
beforeAll(async () => {
await connectDB();
});
afterAll(async () => {
await disconnectDB();
});
beforeEach(() => {
userPayload = {
firstName: "John",
lastName: "Doe",
email: "[email protected]",
password: "password123",
phoneNumber: "1234567890",
};
});
it("should register a user and authenticate the user", async () => {
let res = await request(app).post("/api/auth/register").send(userPayload);
expect(res.status).toBe(200);
expect(res.body).toHaveProperty("email", userPayload.email);
res = await request(app).post("/api/auth/login").send({
email: userPayload.email,
password: userPayload.password,
});
expect(res.status).toBe(200);
expect(res.body).toHaveProperty("token");
});
it("should fail authentication with incorrect credentials", async () => {
await request(app).post("/api/auth/register").send(userPayload);
const res = await request(app).post("/api/auth/login").send({
email: userPayload.email,
password: "wrongPassword",
});
expect(res.status).toBe(400);
expect(res.text).toContain("Invalid email or password");
});
});
I always get this error:
MongooseError: Can't call `openUri()` on an active connection with different connection strings. Make sure you aren't calling `mongoose.connect()` multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections
I have rewritten dbconnection file several times. I have the env set to test, I check if there is an existing connection and if there is to force close it. I am not sure what can I do. I’ve tried debugging with gpt as well but gpt(gpt4) seems to either have old stuff in it or just doesn’t comprehend the problem at hand.
Please help, thank you!