Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redis.Cluster can't mocked by Jest #1644

Closed
philiptolk opened this issue Sep 2, 2022 · 2 comments
Closed

Redis.Cluster can't mocked by Jest #1644

philiptolk opened this issue Sep 2, 2022 · 2 comments

Comments

@philiptolk
Copy link

I have the same problem as discussed here
#1308

When I use the old "ioredis": "4.28.5",
The code works
But the latest "ioredis": "5.2.3",
throws the error Redis.Cluster is not a constructor

jest.mock("ioredis");
const Redis = require("ioredis");

describe("Test Redis", () => {
	it("create Redis instance", () => {
		const client = new Redis();
		expect(client).toBeInstanceOf(Redis);
		expect(Redis).toBeCalledTimes(1);
	});

	it("create Redis Cluster instance", () => {
		const client = new Redis.Cluster();
		expect(client).toBeInstanceOf(Redis.Cluster);
		expect(Redis.Cluster).toBeCalledTimes(1);
	});
});
@gullerya
Copy link

gullerya commented Dec 6, 2022

There is a need in a slight refactor of your tests, along with, I presume, a changes in your actual code due to this upgrade.
I suggest the following paradigm as the simplest:

import { Redis, Cluster } from 'ioredis';

jest.mock('ioredis');

// and then somewhere within the tests, or before all or however you'd like it
const setMock = jest.spyOn(Cluster.prototype, 'set');
...
expect(setMock).nthCalledWith(1, 'some-key', 'some-val', 'PXAT', 1000);

// or if you wish to actually alter the APIs results
jest.spyOn(Cluster.prototype, 'del').mockResolvedValue(1);

@luin
Copy link
Collaborator

luin commented Jan 25, 2023

Looks like it's more of a usage issue so closing.

@luin luin closed this as completed Jan 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants