mongo-db-memory-server with Jest

Viewed 6875

I am trying to write a sample application for POC of mongodb-memory-server but unfortunately its not working. I checked several links and blogs but seems like code working for all is not working for me. Jest test times out even after increasing timeout to 1 min. getConnectionString or getUrl both times out. I suspect this mongodb-memory-server never starts.

Following is DB Handler for tests

I am using Windows 10

    const mongoose = require('mongoose');
    const { MongoMemoryServer } = require('mongodb-memory-server');
    const mongoUnit = require('mongo-unit');
    const mongod = new MongoMemoryServer();
    jest.setTimeout(60000);
    
    module.exports.connect = function(callback) {
        mongod.getUri().then((mongoUri) => {
        
            const mongooseOpts = {
              autoReconnect: true,
              reconnectTries: Number.MAX_VALUE,
              reconnectInterval: 1000,
            };
          
            mongoose.connect(mongoUri, mongooseOpts);
          
            mongoose.connection.on('error', (e) => {
              if (e.message.code === 'ETIMEDOUT') {
                console.log(e);
                mongoose.connect(mongoUri, mongooseOpts);
              }
              console.log(e);
            });
          
            mongoose.connection.once('open', () => {
              console.log(`MongoDB successfully connected to ${mongoUri}`);
              callback();
            });
          });
        }
    
    module.exports.closeDatabase = async () => {
        await mongoose.connection.dropDatabase();
        await mongoose.connection.close();
        await mongod.stop();
    }
    
    
    module.exports.clearDatabase = async () => {
        const collections = mongoose.connection.collections;
    
        for (const key in collections) {
            const collection = collections[key];
            await collection.deleteMany();
        }
    }
1 Answers

Check this issue: https://github.com/nodkz/mongodb-memory-server/issues/344

I was having the same problem today.I solved this by replacing mongod.exe from node_modules/.cashe/mongodb-memory-server/mongodb-binaries/latest for the older version. But I think the right way would be to state older version in the package.json:

 "config": {
    "mongodbMemoryServer": {
      "version": "4.2.3"
    }
  },
Related