DEV Community

Discussion on: Testing Node.js + Mongoose with an in-memory database

Collapse
 
itbits2 profile image
ItBits2

I implemented this on Windows 10. Unfortunately it is not working. getConnectionString() never returns anything and test times out. This happened even if I increased jest timeout to 1 min. Am I missing something?

Collapse
 
itbits2 profile image
ItBits2
    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();
        }
    }