1

待测模块:

'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;

测试:

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;
});

我执行测试时的错误是:

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

TypeError:无法设置未定义的属性“获取”

如何正确存根 config.redisClient.get(...) 函数?

4

1 回答 1

0

我想通了。我必须在 config.redisClient.get() 函数中放置一个“存根”来存根:

// 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');
      }
    },
  }
};

这让我能够构建这个代理查询:

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

并使用在 RedisAccess.getValue(...) 内部调用的 redisClient.get(...) 代理函数运行此测试:

var val = redisAccessProxy.getValue('test-get-valid');
assert.equal(val.isFulfilled(), true);
assert.equal(val.isRejected(), false);
assert.equal(val, 'valid-value');
于 2017-02-01T21:25:23.013 回答