我目前在 NodeJS 中有一个类,它将在实例化时创建一个 Redis 客户端。我正在尝试编写一个单元测试来测试这个类。但是,我不确定是否能让主要代码与单元测试中的 redis-mock 一起使用。
在单元测试过程中,这行代码返回了 redis.createClient(config.get('redis.port'), config.get('redis.ip'));
-> 连接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
,但它不会自动使用它创建 Sockets lib(以及 redisClient
用它创建的)在引擎盖下。相反,它继续依赖“正常”redis
模块。
要实现该效果,请尝试在顶部添加一行:
jest.mock('redis', () => redis)
在您需要redis-mock
之后。
关于node.js - 使用 redis-mock 进行 Nodejs 单元测试导致 ECONNREFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62907441/