简体   繁体   中英

node.js proxyquire stub asynchronous function from module required by another module

Module under test:

'use strict';
const config = require('config');
const q      = require('q');

class RedisAccess {
    static getValue(key) {
        let deferred = q.defer();

        if (config.redis.disableInteraction) {
            deferred.resolve();
            return deferred.promise;
        }

        config.redisClient.get(key, function handleResults(err, result) {
        ...
        return deferred.promise;
    }        
}

exports = module.exports = RedisAccess;

Test:

var proxyquire = require('proxyquire').noPreserveCache();
var assert = require('assert');
var readdirError = new Error('some error');
var redisClientStub = { };
var calledBack;

// Override redisClient used by RedisAccess.js.
var redisClientProxy = proxyquire('../../../lib/data/redis/RedisAccess.js', { 'config' : redisClientStub });

// Test redisClient.get(...) to retrieve value given key using proxyquire for redisClient.
redisClientStub.redisClient.get = function (key, cb) {
    cb(null, 'hello world'); 
};

calledBack = false;

// Test redisClient getValue async function.
redisClientProxy.getValue('some_key', function (err, value) {
    assert.equal(err, null);
    assert.equal('value', 'hello world');
    callback = true;
});

The error when I execute the test is:

redisClientStub.redisClient.get = function (key, cb) { ^

TypeError: Cannot set property 'get' of undefined

How do I properly stub the config.redisClient.get(...) function?

I figured this out. I had to put a "stub within a stub" to stub the config.redisClient.get() function:

// Proxyquire allows unobstrusively overriding dependencies during testing. 
// Override config used by RedisAccess.js.
var configStub = { 
  redisClient : {
    createClient : function (port, address) {
      // redis-mock-js used instead.
    },
    get : function (key, cb) {
      if(key === 'test-rejected') {
        cb(new Error('test-rejected'), 'rejected-promise');
      } 
      else if(key === 'test-true') {
        cb(null, true);
      }
      else if(key === 'test-get-valid') {
        cb(null, 'valid-value');
      }
      else {
        cb(new Error('Should not have gotten here!'), 'value');
      }
    },
  }
};

which allowed me to construct this proxyquire:

var redisAccessProxy = proxyquire('lib/data/redis/RedisAccess.js', { 'config' : configStub });

and run this test using a proxy function for redisClient.get(...) which is called inside of RedisAccess.getValue(...):

var val = redisAccessProxy.getValue('test-get-valid');
assert.equal(val.isFulfilled(), true);
assert.equal(val.isRejected(), false);
assert.equal(val, 'valid-value');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM