How to mute a method that is called from the outer scope for the function being tested?

I have a Redis client that is created this way using the node_redis library ( https://github.com/NodeRedis/node_redis ):

var client = require('redis').createClient(6379, 'localhost');

I have a method that I want to test, the purpose of which - to establish and publish a value for the wide Redis, so I want to test that the methods setand publishsummoned or called in line with my expectations. The difficulty is that I want this test to work without having to run an instance of the Redis server, so I cannot just create the client because it will generate errors if it cannot detect Redis. So I need to drown out the method createClient().

Method Example:

// require('redis').createClient(port, ip) is called once and the 'client' object is used globally in my module.
module.exports.updateRedis = function (key, oldVal, newVal) {
  if (oldVal != newVal) {
    client.set(key, newVal);
    client.publish(key + "/notify", newVal);
  }
};

, , . , , , , callOnce true . createClient, , :

{
  set: function () { return 'OK'; },
  publish: function () { return 1; }
}

.

:

var key, newVal, oldVal, client, redis;

before(function () {
  key = 'key';
  newVal = 'value';
  oldVal = 'different-value';
  client = {
    set: function () { return 'OK'; },
    publish: function () { return 1; }
  }
  redis = require('redis');
  sinon.stub(redis, 'createClient').returns(client);

  sinon.spy(client, 'set');
  sinon.spy(client, 'publish');
});

after(function () {
  redis.createClient.restore();
});

it('sets and publishes the new value in Redis', function (done) {
  myModule.updateRedis(key, oldVal, newVal);

  expect(client.set.calledOnce).to.equal(true);
  expect(client.publish.calledOnce).to.equal(true);

  done();
});

( Chai)

AssertionError: expected false to equal true

, , , .

Error connecting to redis [Error: Ready check failed: Redis connection gone from end event.]

UPDATE

createClient ( before, ) - , 't , .

before describe .

, Redis, Redis, ( ), , Redis. , , , NodeJS- , Mocha , . , , , , , , createClient() , , . , , , , , , .

: Gulp, , .

+4
1

fakeredis (https://github.com/hdachev/fakeredis), Redis app :

var redis = require('fakeredis'),
    konfig = require('konfig'),
    redisClient = redis.createClient(konfig.redis.port, konfig.redis.host);

sinon.stub(require('redis'), 'createClient').returns(redisClient);

var app = require('../../app.js'),
//... and so on

sinon.spy :

describe('some case I want to test' function () {
  before(function () {
    //...
    sinon.spy(redisClient, 'set');
  });

  after(function () {
    redisClient.set.restore();
  });

  it('should behave some way', function () {
    expect(redisClient.set.called).to.equal(true);
  });
});

, , redisErrorClient, Redis .

, Redis, , redisClient(), . , .

+1

Source: https://habr.com/ru/post/1612461/


All Articles