mercredi 31 mai 2017

Mocking Redis Constructor with Sinon

I'm trying to figure out a way to mock redis in this module:

//module.js

const Redis  = require('ioredis');
const myFunction = {
  exists: (thingToCheck) {
    let redis_client = new Redis(
      6379,
      process.env.REDIS_URL,
      {
        connectTimeout: 75,
        dropBufferSupport: true,
        retryStrategy: functionHere
      });

    redis_client.exists(thingToCheck, function (err, resp) {
      // handlings in here
    });
  }
};



// test-module.js

const LambdaTester = require('lambda-tester');
const chai = require('chai');
const expect = chai.expect;
const sinon = require('sinon');
const mockRedis = sinon.mock(require('ioredis'));


describe( 'A Redis Connection error', function() {



  before(() => {

    mockRedis.expects('constructor').returns({
      exists: (sha, callback) => {
        callback('error!', null);
      }
    });

  });
  it( 'It returns a database error', function() {


    return LambdaTester(lambdaToTest)
      .event(thingToCheck)
        .expectError((err) => {
          expect(err.message).to.equal('Database error');
        });
  });
});

I also tried a few variations, but I'm kind of stuck as I basically need to mock the constructor and I'm not sure Sinon supports this?

mockRedis.expects('exists').returns(
  (thing, callback) => {
    callback('error!', null);
  }
);
sinon.stub(mockRedis, 'constructor').callsFake(() => console.log('test!'));
sinon.stub(mockRedis, 'exists').callsFake(() => console.log('test!'));

Not sure what else to try here, I also tried using rewire as suggested here, but using mockRedis.__set__("exists", myMock); never set that private variable.

I want to fake my error paths ultimately.
I would love to hear what others are doing to test redis in node js 😄.

Aucun commentaire:

Enregistrer un commentaire