我用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();
});
});发布于 2016-07-19 12:51:01
上面的代码中有一些不正确的地方。
首先,您需要在应用程序代码中模拟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();
});https://stackoverflow.com/questions/31490071
复制相似问题