Stubbing Redis interactions in javascript using Sinon

后端 未结 5 809
陌清茗
陌清茗 2020-12-16 00:15

I am working in node.js. My app interacts with Redis via the node_redis module. I\'m using mocha and sinon to automate testing of my app. My app looks somethi

5条回答
  •  清歌不尽
    2020-12-16 00:52

    This initially seemed very trivial to me, but I was faced with a lot of caveats, particularly because I was using jest for testing, which does not supports proxyquire. My objective was to mock the request dependency of redis, so here's how I achieved it:

    // The objective is to mock this dependency
    const redis = require('redis');
    
    const redisClient = redis.createClient();
    redis.set('key','value');
    

    Mocking dependency with rewiremock:

    const rewiremock = require('rewiremock/node');
    
    const app = rewiremock.proxy('./app', {
      redis: {
        createClient() { 
          console.log('mocking createClient');
        },
        set() {
          console.log('mocking set');
        }
      },
    });
    

    The catch is that you can't use rewire, or proxyquire with jest, that you need a library like rewiremock to mock this dependency.

    REPL example

提交回复
热议问题