我正在尝试使用mocha框架编写一个单元测试用例,在这里我必须模拟azureredis缓存…有人能帮助我如何使用node.js模拟用于单元测试用例目的的缓存吗。
const redis = require('redis');
const redisHostName = process.env['hostName'];
const redisPort = process.env['port'];
const redisKey = process.env['key'];
let client = redis.createClient(redisPort, redisHostName, { auth_pass: redisKey, tls: { serverName: redisHostName } });
async function getKeyValue(key, ctx) {
context = ctx;
return new Promise((resolve, reject) => {
client.get(key, function (err, result) {
if (err) {
resolve(err);
}
resolve(result);
});
});
}
getKeyValue();
1条答案
按热度按时间kupeojn61#
以下是单元测试解决方案:
index.js
```const redis = require('redis');
const redisHostName = process.env['hostName'];
const redisPort = process.env['port'];
const redisKey = process.env['key'];
let client = redis.createClient(redisPort, redisHostName, { auth_pass: redisKey, tls: { serverName: redisHostName } });
async function getKeyValue(key, ctx) {
context = ctx;
return new Promise((resolve, reject) => {
client.get(key, function(err, result) {
if (err) {
return resolve(err);
}
resolve(result);
});
});
}
exports.getKeyValue = getKeyValue;
```
index.test.js
:100%覆盖率的单元测试结果: