我不得不编写一个单元测试,用于redisClient调用失败时的测试。知道我该怎么写这个。下面你会找到我目前所拥有的。
const asyncRedis = require("async-redis");
class redis {
constructor(redisHost, redisPort) {
this.redisHost = redisHost;
this.redisPort = redisPort;
}
async init() {
try {
this.redisClient = asyncRedis.createClient({
port: this.redisPort,
host: this.redisHost
});
} catch(error) {
console.log(`Error creating client due to: ${error}`)
}
}
}
module.exports = redis;redis-test.js
test('init on error', async () => {
jest.mock('../../src/redis/redis')
const redis = require('../../src/redis/Redis');
redis.mockImplementation(() => {
return {
init: jest.fn(() => { throw new Error(); }
)};
})
expect(await redis.init()).toThrowError(Error());
})发布于 2021-07-25 14:33:20
你在嘲笑你的代码,你应该是在模仿async-redis库代码。
您需要模拟createClient方法以始终抛出错误。这样您就可以检查是否执行了捕获流。
这一部分,你得到了正确的jest.fn(() => { throw new Error(); },总是返回一个错误。
我不是专家在NodeJS,对不起,我不能提供详细的源代码。
https://stackoverflow.com/questions/68503035
复制相似问题