背景
我正在尝试测试一个简单的缓存模块,但我找不到在注入(inject)依赖项时保持 API 不变的方法。
代码
const myCache = () => {
//this is a dependency.
//Ideally I would inject it ( a map already created), but if I do it, I will loose connect !
let map;
const connect = url => {
map = new Map();
console.log(`This url ${url} exists for illustration purposes only!`);
};
const get = key => {
console.log(`You requested an object with key: ${key}`);
return map.get(key);
};
const set = ( key, value ) => {
ma.set(key, value);
console.log(`You want to save value ${value} with key ${key}`);
};
return {
connect,
get,
set
};
};
module.exports.myCache = myCache;
这是一个使用 map 的简单缓存模块,用于演示目的。
在此示例中,我有一个变量 map
,当我调用 connect
时会分配该变量。
问题
这里的问题是我需要知道是否使用正确的参数调用 map 中的方法 get
和 set
。
因为 map 是在运行connect
后设置的,所以我无法监视它(例如使用sinonjs)。一个可能的解决方案是在 myCache
中内置 map ,但随后 API 会发生变化,这是我想避免的。
问题
如何测试是否使用正确的参数调用 map
中的方法而不更改此模块的 API?
最佳答案
I can't see a way to keep the API unchanged while injecting the dependencies.
通常情况下,您不会保持 API 不变。所发生的情况是,您扩展 API 以允许更精细的控制。
const connect = url => {
map = new Map();
console.log(`This url ${url} exists for illustration purposes only!`);
};
为了让客户端控制 map ,我们创建了一个新版本的函数,该函数接受 map 作为参数
const connect_v2 = url, injected_map => {
map = injected_map;
console.log(`This url ${url} exists for illustration purposes only!`);
};
然后,您可以通过让旧 map 调用新 map 来删除重复项,而无需更改其 API
const connect = url => {
connect_v2(url, new Map())
};
const connect_v2 = url, injected_map => {
map = injected_map;
console.log(`This url ${url} exists for illustration purposes only!`);
};
关于javascript - 如何测试这种依赖性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48205397/