1

I am trying to mock Cassandra for unit test cases , I am using npm Cassandra-driver for connecting/querying cassandra. for mocking the stub this is my code.

beforeEach(function () {
        let CassandraClient = sinon.stub();
    CassandraClient.prototype.execute = sinon.stub().returns(new Promise((fulfill, reject) => {
        console.log("Inside execute method");
        fulfill(cassndaraExperimentQueryData);
    }));
    const CassandraClientWrapper = proxyquire('../../../../api/services/index.js', { 'cassandra-driver': { Client: CassandraClient } });
    console.log(typeof CassandraClientWrapper);
    CassandraClientWrapper.init();
    });

this is how my index.js looks

   const cassandra = require('cassandra-driver');
    module.exports = class DBServices {
    init(){
    const contactPoint = process.env['cassndraIP'] || '127.0.0.1';
    var casssandraClient = new cassandra.Client({
              contactPoints: [contactPoint]
            });
let persistentObject  = new persistent(redisMockClient, casssandraClient)
    }
    }

but here instead of creating the mock object it creates the object from Cassandra-driver which connect to actual DB.

Erick Ramirez
  • 13,964
  • 1
  • 18
  • 23
user3649361
  • 944
  • 4
  • 20
  • 40
  • are you sure your path is correct? one way could be to get the base project path in some sort of settings/initialization file, and then make sure the path is relative to that path – dm03514 Dec 13 '17 at 16:00

1 Answers1

0

Restructuring your code might allow you to stub out cassandra-client and remove the dependency on proxyquire.

By providing a constructor to DBServices and haveing the caller "inject" the dependency it should allow for easier testing:

    module.exports = class DBServices {
    constructor(cassandra) {
       this.cassandra = cassandra;
    }

    init(){
      const contactPoint = process.env['cassndraIP'] || '127.0.0.1';
      var casssandraClient = new this.cassandra.Client({
        contactPoints: [contactPoint]
      });
      let persistentObject  = new persistent(redisMockClient, casssandraClient)
      }
    }

Now your test can construct the stub, import your DBServices and create a new DBservices with the stub, and exercise the DBServices and make assertions on your stub!

This now requires the caller to import the actual production cassandra and make calls on it:

const cassandra = require('cassandra-driver');
let db = new DBServices(cassandra);
db.init()

Testing these higher level callers though could take place in integration or system tests were you can actually use the real cassandra-driver, since the DBServices is already unit tested.

dm03514
  • 54,664
  • 18
  • 108
  • 145