Provide an official mocking library for mocking Node-Redis in Jest tests

未关闭
#2,546 13 条评论 7 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
45/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
活跃
技术栈
node.js, redis, typescript
领域
testing

调研方向

从 lib/redis-client.ts 和失败的 lib/services/tests/area.spec.ts 入手,然后将 package.json 中的 Jest 配置和 jest.setup.redis-mock.js 与 Redis v4 客户端 API 进行比较。完成标准是:某种官方 mocking 方案或库支持所示的 createClient、connect、duplicate 以及 TypeScript/Jest 用法,且不要求运行中的 Redis 服务。

由索引模型根据 Issue 内容生成。

描述

feature
Description

I am struggling to find a way to combine the modern Redis v4 client with the jest test framework.

This is my production code:

import redis from 'redis';
import config from './config';
import logger from './logger';

const redisClient = redis.createClient(config.redisConfig);
redisClient.on('error', (e) => logger.error(e));

(async () => {
  await redisClient.connect();
})();

export type RedisClient = typeof redisClient;
export default async () => {
  const clone = redisClient.duplicate();
  await clone.connect();
  return clone;
};

Some of my services of course use redis, and when I try to test them, the entire test suite usually fails at startup. This is a project that was migrated from plain JS to TS, from node-redis 3 to 4, and from mocha to jest.

Below are a few scenarios that don't work.

No config added:

FAIL lib/services/tests/area.spec.ts
  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'createClient')

      4 |
    > 5 | const redisClient = redis.createClient(config.redisConfig);
        |                           ^

      at Object.createClient (lib/redis-client.ts:5:27)

Using the documented scenario with redis-mock:

in package.json
  "jest": {
    "setupFilesAfterEnv": [
      "./jest.setup.redis-mock.js"
    ]
  },
in jest.setup.redis-mock.js
import {jest} from '@jest/globals';
jest.mock('redis', () => jest.requireActual('redis-mock'));

Gives the error:

FAIL lib/services/tests/area.spec.ts
    TypeError: redisClient.connect is not a function

       8 | (async () => {
    >  9 |   await redisClient.connect();
         |                     ^
      10 | })();

      at connect (lib/redis-client.ts:9:21)
      at asyncGeneratorStep (lib/redis-client.ts:3:31)

Messing around in the jest setup file usually ends up with the entire library being undefined, etc.

主要语言
TypeScript
星标
17.6k
派生
2k
平均合并
1 天 22 小时
30 天内合并 PR
62

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

redis/node-redis 的其他 Issue

查看 redis/node-redis 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。