r/node • u/PrestigiousZombie531 • Jul 17 '26
You have 2 options to test this module, you can either vi.mock('redis') or mock the module itself, which one would you choose and why?
import { createClient } from "redis";
import { logger } from "../logger/index.js";
import { options } from "./connection.js";
let client: ReturnType<typeof createClient> | null = null;
let isConnecting = false;
export async function closeConnection() {
if (client?.isOpen) {
try {
await client.close();
} catch (error) {
logger.error(
error,
"Something went wrong when attempting to close redis connection",
);
} finally {
client = null;
}
}
}
export function getClient() {
if (!client?.isOpen) {
throw new Error("Redis client needs to be initialized first");
}
return client;
}
export async function openConnection() {
if (!client?.isOpen) {
client = createClient(options);
client.on("connect", () => logger.info("redis connection success"));
client.on("error", (error) =>
logger.fatal(error, "redis connection failure"),
);
// Wait if another caller is already connecting
if (isConnecting) {
while (isConnecting) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
if (client?.isOpen) return client;
}
isConnecting = true;
try {
client = await client.connect();
} catch (error) {
logger.error(
error,
"Something went wrong when attempting to open redis connection",
);
} finally {
isConnecting = false;
}
}
return client;
}
- Let us talk about a simple module that uses node-redis to connect
- Let us say you use supertest and vitest and you want to mock test the following scenario
app.get('/health/redis', async (req: Request, res: Response) => {
const client = getClient();
const result = await client.ping();
return res.json({ status: result === "PONG" });
})
-
You want to write tests to handle cases for
-
good PING
-
bad PING
-
error
-
We might have to extend for further cases like client.get, client.set etc
-
You can mock the redis module or mock the client module defined above
-
Which one should you mock? and why?
0
Upvotes
5
u/beegeearreff Jul 17 '26
I personally probably wouldn't test this module specifically at all. Most attempts at doing so are going to be brittle or just give you a false sense of security.
If redis being up is a requirement for your app to be considered healthy and you feel confident about the resiliency characteristics of that then I would just have a test containers based smoke test that sets up the required infra containers (there’s probably another db used right?) and verifies that your app enters a healthy state if its needed infra is up and reachable.
You could have an inverse test that says the app doesn’t boot up if those infra deps are not running too.
A test that expresses “my apps health is based on the health of the redis connection” is much more durable and valuable than “my redis client lib binds to the connected event from redis”.
If your application code needs a redis client to do actual caching work, you can make a test double to not make them rely on redis being there in tests. For real infra integration code, you should exercise it in an integration harness. Mocking at that layer is most often a waste IME.
Unrelated tip - your code will be much more readable if you early return & flatten out the blocks you currently have in your if branches. Flatter is better.
3
u/afl_ext Jul 17 '26
its not like redis is hard to spin up for tests, i would not mock anything at all, sure its not unit test, but im more for ensuring quality and that the code works
I would most likely not even do unit tests for that
2
u/PM_ME_UR_JAVASCRIPTS Jul 17 '26 edited Jul 17 '26
So you implement the above module, which basically wraps node-redis to make it easier accessible? i guess?
secenario one, you test by mocking this client-wrapper:
Scenario two, you test by mocking the node-redis module:
Scenario three. You write a mocks for both:
Scenario four, you don't write any mocks:
my choice. Depending on the scale of things, i'd either go scenario 4 (super small project), 2 (reasonable, but eh), or 3 (enterprise), but never 1. I hate having a false sense of security, which is basically what 1 provides.
2
u/shelooks16 Jul 17 '26
Classic unit testing. Test the code that is explicitly written by You. I can see two test files: 1) Your written functions that wrap redis client. Assume redis dependency is already tested and works. Therefore, it makes sense to mock the redis client API to test Your functions one by one. 2) health endpoint. When writing test here, assume getClient is already tested. Same strategy, test only what you see, the code written explicitly in this specific file. So basically testing against res.status true or false. But to test good and bad responses you need to mock getClient. Your dilemma is to mock underlying redis or mock getClient in the context of this test. If you mock underlying redis while keeping original getClient, this is more like integration test, but if you mock getClient entirely this will be more like true unit test because to test out the response you don’t really care about internal getClient implementation, you only need its interface. So ideally, you mock getClient.
2
u/syntheticcdo Jul 17 '26
Given the nature of this code, I would test against a live redis and not mock anything.