I’m setting up a MongoDB container for my Jest tests using the testcontainers library and Mongoose. However, I’m encountering an issue where the MongoDB connection established in the global setup file is not available in my Jest tests.
Here is my setup:
e2e/setup/globalSetup.js:
const ContainerFactory = require('./index');
const containerManager = new ContainerFactory();
module.exports = async () => {
await containerManager.setUpContainers();
};
Jest Configuration (jest.config.js):
{
"testMatch": ["<rootDir>/e2e/**/*e2e.js"],
"testEnvironment": "node",
"coverageDirectory": "./coverage/e2e",
"setupFiles": ["./setupJest.js"],
"globalSetup": "<rootDir>/e2e/setup/globalSetup.js",
"globalTeardown": "<rootDir>/e2e/setup/teardown.js"
}
MongoDB Setup (e2e/setup/index.js):
const mongoose = require('mongoose');
const { GenericContainer, Wait } = require('testcontainers');
class MongoDBIntegration {
constructor() {
this.mongoContainer = null;
}
async startMongoDBContainer() {
try {
console.log('Starting MongoDB container...');
this.mongoContainer = await new GenericContainer("mongo")
.withExposedPorts(27017)
.withWaitStrategy(Wait.forLogMessage(/waiting for connections/i))
.start();
const port = this.mongoContainer.getMappedPort(27017);
const host = 'localhost';
const uri = `mongodb://${host}:${port}/cami`;
mongoose.set('strictQuery', true);
const connection = await mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
global.mongoConfig = {
connection,
uri
};
// global.testContainers = global.testContainers || [];
global.testContainers.push(this.mongoContainer);
console.log(`MongoDB container started at: ${uri}`);
return connection;
} catch (err) {
console.error('Error during MongoDB setup:', err);
throw err;
}
}
async disconnect() {
try {
if (global.mongoConfig.connection) {
await mongoose.disconnect();
console.log('MongoDB disconnected.');
}
} catch (err) {
console.error('Error during MongoDB disconnection:', err);
throw err;
}
}
}
module.exports = MongoDBIntegration;
Test File (e2e/test/testFile.e2e.js):
const mongoose = require('mongoose');
describe('Integration Tests', () => {
it('MongoDB: should insert and retrieve a document in test collection', async () => {
if (mongoose.connection.readyState !== 1) {
// Connection not established
console.log("MongoDB is Not connected");
throw new Error('MongoDB connection not established');
} else {
console.log("MongoDB is connected", mongoose.connection);
}
const TestModel = mongoose.model('Test', new mongoose.Schema({ name: String, value: Number }));
const testDocument = { name: 'Test Document', value: 42 };
// Insert document
const insertedDocument = new TestModel(testDocument);
await insertedDocument.save();
// Retrieve document
const retrievedDocument = await TestModel.findOne({ name: 'Test Document' });
expect(retrievedDocument).toBeTruthy();
expect(retrievedDocument.name).toBe('Test Document');
expect(retrievedDocument.value).toBe(42);
}, 10000);
});
Issue:
The MongoDB connection established in the globalSetup
file is not available in my Jest tests. When I check the mongoose.connection.readyState, it shows that the connection is not established.
What I’ve Tried:
- Ensured that
mongoose.connect()
is properly awaited in the globalSetup file. - Verified that
global.mongoConfig
is correctly set up. - Added debug logs to confirm that the MongoDB container starts correctly.
How can I ensure that the Mongoose connection is available in my Jest tests?