node.js - Can't connect to the fakeredis instance (Nodejs + Redis + Fakeredis) -


i write nodejs app redis. want mock redis connection in unit tests. use fakeredis module stub data. have problem getting redis keys created in tests. can keys in tests, unavaiable in code.

it's code doesn't connect fakeredis instance. tried set port , host, tried module redis-mock.

app:

var redis = require('redis'); var redisclient = redis.createclient(6379, '127.0.0.1', {});  redisclient.keys('*', function(error, reply){     console.log('keys', reply); // problem: it's empty array  }); 

spec:

var assert    = require('chai').assert; var fakeredis = require('fakeredis'); var fakeredisclient;  before(function() {     fakeredisclient = fakeredis.createclient(); });  beforeeach(function() {      // mock data - set random keys     fakeredisclient.set('foo', 'bar');  });  aftereach(function(done){     fakeredisclient.flushdb(function(err, reply){         assert.ok(reply);         done();     }); }); 

there few things incorrect in code above.

first need mock fakeredis module in place of redis module in application code. 1 way using mockery library.

the next issue fakeredis.createclient(...) call in test must match redis.createclient(...) call in application code. means need read in same configuration variables test. option use sinon overload fakeredis.createclient() function return our test client.

var mockery = require('mockery')   , fakeredis = require('fakeredis')    /* should match app connection settings       if aren't stubbing createclient() method using       sinon. */   , client = fakeredis.createclient('test')     /* if connection settings aren't exact match (or       use defaults via empty constructor, need       stub using sinon */   , sinon = require('sinon')  // run before tests start before(function() {      // enable mockery mock objects     mockery.enable({         warnonunregistered: false     });      // stub createclient method *always* return client created above     sinon.stub(fakeredis, 'createclient', function(){ return client; } );      // override redis module our fakeredis instance     mockery.registermock('redis', fakeredis); }  // run after each test aftereach(function(){     client.flushdb(); }); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -