Node.js 在EconRefused中使用redis模拟结果进行Nodejs单元测试

Node.js 在EconRefused中使用redis模拟结果进行Nodejs单元测试,node.js,unit-testing,redis,Node.js,Unit Testing,Redis,我目前在NodeJS中有一个类,它将在实例化时创建一个redis客户机。我正试图编写一个单元测试来测试这个类。然而,我不确定在单元测试中使用redis mock是否能使主代码正常工作 在单元测试期间,这行代码返回redis.createClient(config.get('redis.port')、config.get('redis.ip')->连接ECONREFUNCE class Socket { constructor(socketClient) { /** F

我目前在NodeJS中有一个类,它将在实例化时创建一个redis客户机。我正试图编写一个单元测试来测试这个类。然而,我不确定在单元测试中使用redis mock是否能使主代码正常工作

在单元测试期间,这行代码返回
redis.createClient(config.get('redis.port')、config.get('redis.ip')->
连接ECONREFUNCE

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
)自动创建套接字库。相反,它继续依赖“普通”redis
模块

要达到此效果,请尝试在顶部添加一行:

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

在您需要
redis mock

hm如果我使用mocha,它是否仍能像使用jest一样工作?@user990639,啊,抱歉,我是在错误的假设下出现的。有了摩卡咖啡,您需要以不同的方式进行模仿: