如何使用 jest 编写 redisClient 错误时的测试

How to write test for when redisClient errors using jest

我一直在为 redisClient 调用 createClient 失败时编写单元测试。关于如何写这个的任何想法。你会在下面找到我目前所拥有的。

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

    })

你在嘲笑你的代码,你应该嘲笑 async-redis 库代码。

您需要模拟 createClient 方法以始终抛出错误。这样您就可以检查您的捕获流程是否已执行。

这部分,你做对了jest.fn(() => { throw new Error(); },总是return一个错误。

我不是NodeJS专家,抱歉我无法提供详细的源代码。