8

Afternoon all

I have been struggling to find a solid solution to the following.

How do I unit tests NodeJS code which makes use of MongoDB ?

I would like to write isolated unit tests, without actually spinning up any database for the purpose of testing.

Example code I would like to test:

DatabaseService.js

var mongodb       = require('mongodb');

var exports = module.exports = (function () {

  var MongoClient   = mongodb.MongoClient;
  var db            = null;

  function getDB(){
    return db;
  }

  const connect = (
    options
  ) => {

    return new Promise((resolve, reject) => {

      var host      = options.host;
      var port      = options.port;
      var dbName    = options.dbName;

      var url = 'mongodb://' + host + ':' + port;

      // Use connect method to connect to the server
      MongoClient.connect(url, function(err, client) {

        if(error){
          return reject(false);
        }

        const db = client.db(dbName);

        return resolve(true);

      });

    });
  };

  return {
    connect: connect,
    getDB: getDB
  };

})();

UserService.js

var DatabaseService   = require("./DatabaseService");

var exports = module.exports = (function () {

  const createUser = (
    options
  ) => {

    return new Promise((resolve, reject) => {

      var db = DatabaseService.getDB();

      var firstName = options.firstName;
      var lastName = options.lastName;

      db.collection('users').insertOne({
          firstName: firstName,
          lastName: lastName
        },
        function(error, result) {

          if (error){
            return reject(false);
          }

          return resolve(result);

      });

    });

  };

  return {
    createUser: createUser
  };

})();
technikfe
  • 121
  • 1
  • 8

1 Answers1

0

You have the option to mock it with a test library, like jest-mongodb as commented before. Or you need to isolate your business code from the mongodb boiler plate and don't unit-test the boiler plate.

Jose Marin
  • 802
  • 1
  • 4
  • 15