【问题标题】:Can't connect to the fakeredis instance (Nodejs + Redis + Fakeredis)无法连接到 fakeredis 实例(Nodejs + Redis + Fakeredis)
【发布时间】:2016-07-19 12:51:00
【问题描述】:

我用 redis 编写 nodejs 应用程序。我想在单元测试中模拟我的 redis 连接。我使用 fakeredis 模块来存根我的数据。 但是我无法在测试中创建 redis 密钥。我可以在测试中获取所有键,但它们在代码中不可用。

好像我的代码没有连接到 fakeredis 实例。 我尝试设置端口和主机,还尝试了另一个模块redis-mock。

应用:

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 
});

规格:

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();
    });
});

【问题讨论】:

    标签: node.js unit-testing redis


    【解决方案1】:

    上面的代码中有一些不正确的地方。

    首先,您需要在应用程序代码中模拟您的 fakeredis 模块来代替 redis 模块。一种方法是使用mockery 库。

    下一个问题是测试中的fakeredis.createClient(...) 调用必须与应用程序代码中的redis.createClient(...) 调用匹配。这意味着您需要将相同的配置变量读入您的测试。另一种选择是使用sinon 重载fakeredis.createClient() 函数以始终返回我们的测试client

    var mockery = require('mockery')
      , fakeredis = require('fakeredis')
    
      /* This should exactly match the app connection settings 
         if you aren't stubbing the createClient() method using 
         sinon. */
      , client = fakeredis.createClient('test') 
    
      /* If your connection settings aren't an exact match (or 
         use the defaults via an empty constructor, you need to 
         stub using sinon */
      , sinon = require('sinon')
    
    // run before the tests start
    before(function() {
    
        // Enable mockery to mock objects
        mockery.enable({
            warnOnUnregistered: false
        });
    
        // Stub the createClient method to *always* return the client created above
        sinon.stub(fakeredis, 'createClient', function(){ return client; } );
    
        // Override the redis module with our fakeredis instance
        mockery.registerMock('redis', fakeredis);
    }
    
    // run after each test
    afterEach(function(){
        client.flushdb();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2014-07-04
      • 2020-04-02
      • 2021-04-05
      • 2012-09-17
      • 2022-06-24
      相关资源
      最近更新 更多