gpt4 book ai didi

javascript - 来自另一个模块所需的模块的node.js proxyquire stub 异步函数

转载 作者:可可西里 更新时间:2023-11-01 10:55:52 27 4
gpt4 key购买 nike

被测模块:

'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: Cannot set property 'get' of undefined

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

最佳答案

我想通了。我不得不在 stub 中放置一个 stub 来 stub 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');

关于javascript - 来自另一个模块所需的模块的node.js proxyquire stub 异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41857038/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com