I’m working on an Express application with a MongoDB database, using Mongoose for database interactions. I’ve set up my tests using Node.js’ built-in node:test
module and Supertest
for API testing. My beforeEach
function connects to the database using connectDB(config.MONGODB_URI)
, but I keep getting the error:
Error connecting to Database MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined".
Here’s a version of my test code:
import test, { beforeEach } from "node:test";
import supertest from "supertest";
import mongoose from "mongoose";
import config from "../utils/config";
import app from "../app"; // If this line is placed before the config import, the error fades
import connectDB from "../db/connectDb";
const api = supertest(app);
beforeEach(async () => {
await connectDB(config.MONGODB_URI);
});
// More test code follows...
Relevant Config File:
const PORT = process.env.PORT || 3001;
const MONGODB_URI =
process.env.NODE_ENV === "test"
? process.env.TEST_MONGODB_URI
: process.env.MONGODB_URI;
export default {
PORT,
MONGODB_URI,
};
I observed that:
- If I import app before config, the error does not occur.
- If I import config before app, I get the error: “uri parameter to openUri() must be a string, got undefined”.
My Questions:
- Why does the import order affect the MONGODB_URI value, causing it to be undefined in some cases?
- Are there known issues with environment variable loading or initialization timing that could be causing this behavior?
What I Tried:
I tried running my tests with different import orders of the app and config modules. Specifically:
I imported config before app, which resulted in the error: MongooseError: The uri parameter to openUri() must be a string, got “undefined”.
I then switched the order, importing app before config, and the error disappeared.
What I Expected:
I expected the import order not to affect the loading of environment variables or configuration values. I expected config.MONGODB_URI to always have the correct value from the environment.
What Actually Happened:
When config was imported before app, config.MONGODB_URI was undefined, leading to the database connection error. Changing the order of imports resolved the issue, but I don’t understand why.