Gobliins
Gobliins

Reputation: 4026

Mongodb access in mocha test

So I would like to cleanup my db (before or) after some unit testing.

Basically the code you will see in my codeblocks is in the afterAll block from mocha. I am using webdriver.io testrunner for running my tests.

What I don't understand is, how to use db stuff from outside the connect scope, see:

function createConnection(){
  MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function(err, db) {
    if (err)
      throw err;
    console.log("connected to the mongoDB !");

    let myCollection = db.collection('test_collection');
    // do stuff with myCollection

  });
}

I would prefer, if possible, something like this:

function createConnection(){
  MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function(err, db){
    if (err)
      throw err;
  }
}

function getCollection(name){
  return db.collection(name) //don't have db at this scope, problem?
}

//app.js
createConnection();
let myCollection = getCollection('data');
...//do stuff with myCollection

closeConnection();

Is this possible?

Upvotes: 1

Views: 1231

Answers (2)

Juan Carlos Farah
Juan Carlos Farah

Reputation: 3879

If you want to connect to a MongoDB database in the way you describe, you can use JavaScript promises to make sure you have db defined when you call getCollection. The code that you would include in your afterAll block would then be something like the following:

function createConnection(connection) {
  // return a promise
  return new Promise((resolve, reject) => {
    MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function (err, db) {
      if (err) {
        // rejects with error if connection fails
        reject(err);
      }
      // returns handle to database if connection successful
      resolve(db);
    });
  });
}

// function takes handle to database and collection name
function getCollection(db, name) {
  return db.collection(name);
}

// test it works
createConnection().then((db) => {
  let myCollection = getCollection(db, 'foo');
  // do stuff with one collection
  // e.g. myCollection.deleteOne({ foo: 1 });
  // ...

  // do stuff with another collection
  myCollection = getCollection(db, 'bar');
  // e.g. myCollection.insert({ bar: 1 });
  // ...

// ensure you catch any errors and log them to the console  
}).catch(console.error);

Note that I used a bit of ES6 syntax out of habit, but it works exactly the same with ES5.

Upvotes: 1

lukaleli
lukaleli

Reputation: 3627

The rule of thumb is that you always mock things like databases or http requests in your test cases. Take a look at something like mongo-mock and use it instead.

Upvotes: 0

Related Questions