Provide an official mocking library for mocking Node-Redis in Jest tests
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 17.6k
- Forks
- 2k
- Avg merge
- 2d 3h
- Merged PRs (30d)
- 40
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with lib/redis-client.ts and the failing lib/services/tests/area.spec.ts, then compare package.json's Jest setup and jest.setup.redis-mock.js with the Redis v4 client API. Done means an official mocking approach or library supports the shown createClient, connect, duplicate, and TypeScript/Jest usage without requiring a live Redis service.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- node.js, redis, typescript
- Domain
- testing
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100