在ECONNREFUSED中使用redis mock进行Nodejs单元测试



我目前在NodeJS中有一个类,它将在实例化时创建一个redis客户端。我正试图写一个单元测试来测试这个类。然而,我不确定在单元测试中使用redis mock来完成主要代码。

在单元测试期间,这行代码返回redis.createClient(config.get('redis.port'), config.get('redis.ip'));->connect ECONNREFUSED

class Socket {
constructor(socketClient) {
/** For socket io */
this.socketClient = socketClient;
log.info("new socketio client connected... " + socketClient.id);        

/** For redis */
// a redis client is created and connects
this.redisClient = redis.createClient(config.get('redis.port'), config.get('redis.ip'));
this.redisClient.on('connect', function() {
log.info('Redis client connected ' + socketClient.id);
});
this.redisClient.on('error', function (err) {
log.error('Redis client something went wrong ' + err);
});
this.redisClient.on('message', function (channel, message) {
log.info('Redis message received...' + socketClient.id + " socketio emitting to " + channel + ": " + message);
socketClient.emit('updatemessage', message)
});
}
}

这是单元测试代码:

'use strict'
var expect = require('chai').expect
, server = require('../index')
, redis = require('redis-mock')
, redisClient
, io = require('socket.io-client')
, ioOptions = { 
transports: ['websocket']
, forceNew: true
, reconnection: false
}
, testMsg = JSON.stringify({message: 'HelloWorld'})
, sender
, receiver


describe('Chat Events', function(){
beforeEach(function(done){

redisClient = redis.createClient();
// start the io server
//server.start()
// connect two io clients
sender = io('http://localhost:3000/', ioOptions)
receiver = io('http://localhost:3000/', ioOptions)

// finish beforeEach setup
done()
})
afterEach(function(done){

redisClient.disconnect
// disconnect io clients after each test
sender.disconnect()
receiver.disconnect()
done()
})
describe('Message Events', function(){
it('Clients should receive a message when the `message` event is emited.', function(done){
sender.emit('message', testMsg)
receiver.on('ackmessage', function(msg){
expect(msg).to.contains(testMsg)
done()
})
})
})
})

尽管您从redis-mock库导入redis,但它不会在后台使用它(以及使用它创建的redisClient(自动生成Sockets lib。相反,它继续依赖于";正常的";CCD_ 6模块。

为了达到这个效果,试着在顶部添加一行:

jest.mock('redis', () => redis)

就在你需要redis-mock之后。

最新更新