title: Redis mock in nodejs cannot stub non-existent property createClient
body: <p>I have a problem trying to mock the redis <code>createClient()</code> method in NodeJS using mocha and sinon. This is a snippet of my index.js. Inside the socket class, there is a create redis connection. Now in my unit test, i encountered this error <code>TypeError: Cannot stub non-existent property createClient</code>. I can't seem to figure out why? Is it due to some ordering of the mocking?</p>
  <pre class="lang-js prettyprint-override"><code>const express = require(&quot;express&quot;);
  const http = require('http');
  const redis = require('redis');
  const expressApp = express();
  const server = http.createServer(expressApp);
  const io = require('socket.io')(server, {
      pingInterval: 10000,
      pingTimeout: 5000
  });
  const config = require('config');
  const log = require('gelf-pro');
  const HTTP_PORT = 3000;
  
  // Socket IO call backs
  io.on(&quot;connection&quot;, (client) =&gt; {    
      new Socket(client);
  });
  
  // export the server so it can be easily called for testing
  exports.server = server.listen(HTTP_PORT, () =&gt; {
      log.info('socketio server started at port ' + HTTP_PORT);
  });
  </code></pre>
  <p>Unit test code:</p>
  <pre class="lang-js prettyprint-override"><code>'use strict'
  
  var expect = require('chai').expect
    , redis = require('redis')
    , redisMock = require('redis-mock')
    , sinon = require('sinon')
    , 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){
  
      sinon
        .stub(redis.RedisClient.prototype, 'createClient')
        .callsFake(function() {
          console.log('mock redis called');
          return redisMock.createClient();
        });
      
      // connect two io clients
      sender = io('http://localhost:3000/', ioOptions)
      receiver = io('http://localhost:3000/', ioOptions)
      
      // finish beforeEach setup
      done()
    })
    afterEach(function(done){
      
      // 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()
        })
      })
    })
  })
  
  </code></pre>