Mongoose Connection Not Available in Jest Tests After Using Global Setup and Teardown

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?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật