node.jsmongodbmocha.jschaichai-as-promised

How to unit test a method which connects to mongo, without actually connecting to mongo?


I'm trying to write a test to test a method that connects to mongo, but I don't actually want to have to have mongo running and actually make a connection to it to have my tests pass successfully.

Here's my current test which is successful when my mongo daemon is running.

describe('with a valid mongo string parameter', function() {
    it('should return a rejected promise', function(done) {
        var con = mongoFactory.getConnection('mongodb://localhost:27017');
        expect(con).to.be.fulfilled;
        done();
    });
});

mongoFactory.getConnection code:

getConnection: function getConnection(connectionString) {

      // do stuff here

        // Initialize connection once
        MongoClient.connect(connectionString, function(err, database) {
          if (err) {
            def.reject(err);
          }

          def.resolve(database);
        });

      return def.promise;
    }

Solution

  • There are a couple of SO answers related to unit testing code that uses MongoDB as a data store:

    I'll make an attempt at consolidating these solutions.

    Preamble

    First and foremost, you should want MongoDB to be running while performing your tests. MongoDB's query language is complex, so running legitimate queries against a stable MongoDB instance is required to ensure your queries are running as planned and that your application is responding properly to the results. With this in mind, however, you should never run your tests against a production system, but instead a peripheral system to your integration environment. This can be on the same machine as your CI software, or simply relatively close to it (in terms of process, not necessarily network or geographically speaking).

    This ENV could be low-footprint and completely run in memory (resource 1) (resource 2), but would not necessarily require the same performance characteristics as your production ENV. (If you want to performance test, this should be handled in a separate environment from your CI anyway.)

    Setup

    Builds/Tests

    1. Clean the associated database using something like node-database-cleaner.
    2. Populate your fixtures into the now empty database with the help of mongodb-fixtures.
    3. Perform your build and test.
    4. Repeat.

    On the other hand...

    If you still decide that not running MongoDB is the correct approach (and you wouldn't be the only one), then abstracting your data store calls from the driver with an ORM is your best bet (for the entire application, not just testing). For example, something like model claims to be database agnostic, although I've never used it. Utilizing this approach, you would still require fixtures and env configurations, however you would not be required to install MongoDB. The caveat here is that you're at the mercy of the ORM you choose.