So I want to test my integration with mongodb-memory-server. I created two seperate test files for different use cases, and both connect and disconnect to mongodb in before and after functions. This is my db.js file, where I have my connect and disconnect functions:
const { MongoMemoryServer } = require("mongodb-memory-server");
const mongoose = require("mongoose");
let mongoServer;
async function start() {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri);
}
async function stop() {
await mongoose.disconnect();
await mongoServer.stop();
}
module.exports = {
start,
stop,
};
And then in my test files this is how my before and after functions look:
before(async () => {
await start();
});
after(async () => {
await stop();
});
And when I run yarn test
this is the error I get:
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
So my question is, how to work around it? As I understand, tests create connections before the previous one is closed. I tried to create instances with different db names on mongoServer = await MongoMemoryServer.create()
according to docs, but it didn't quite work. Do you guys have any recommendations?