gpt4 book ai didi

node.js - 使用 redis-mock 进行 Nodejs 单元测试导致 ECONNREFUSED

转载 作者:行者123 更新时间:2023-12-03 06:42:17 24 4
gpt4 key购买 nike

我目前在 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来自 redis-mock库,它不会在后台自动使用它(以及用它创建的redisClient)创建 Sockets 库。相反,它继续依赖“正常”redis模块。
要达到这种效果,请尝试在顶部添加一行:

jest.mock('redis', () => redis)
在您要求 redis-mock 之后.

关于node.js - 使用 redis-mock 进行 Nodejs 单元测试导致 ECONNREFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62907441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com