Skip to content

test: add health endpoint smoke test and make redis test-safe - #26

Closed
alok-kumar0421 wants to merge 2 commits into
geturbackend:mainfrom
alok-kumar0421:health-endpoint
Closed

test: add health endpoint smoke test and make redis test-safe#26
alok-kumar0421 wants to merge 2 commits into
geturbackend:mainfrom
alok-kumar0421:health-endpoint

Conversation

@alok-kumar0421

@alok-kumar0421 alok-kumar0421 commented Feb 11, 2026

Copy link
Copy Markdown
Contributor

Added a smoke test for the root health endpoint.

The test verifies that:

  • the API responds with HTTP 200
  • the response body contains status: "success"

Additionally, Redis has been made test-safe by providing a lightweight mock implementation when NODE_ENV=test.
This ensures existing test suites run without requiring an active Redis instance.

Summary by CodeRabbit

  • Tests

    • Added a health-check test and expanded authentication tests with environment fallbacks, service mocks, improved setup/validation, and lifecycle cleanup.
  • Chores

    • Enhanced test environment: a dummy Redis-like object is used in tests to avoid real connections; env validation skips in test mode; improved test configuration and cleanup.

@vercel

vercel Bot commented Feb 11, 2026

Copy link
Copy Markdown
Contributor

@alok-kumar0421 is attempting to deploy a commit to the Yash Pouranik's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Feb 11, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds test-mode support by exporting a dummy Redis client when NODE_ENV === "test", skips environment variable validation during tests, and introduces tests and mocks including a new health-check test and enhanced test setup/mocks for auth tests.

Changes

Cohort / File(s) Summary
Test environment: Redis & validation
backend/config/redis.js, backend/utils/validateEnv.js
When NODE_ENV === "test", redis.js exports a dummyRedis object (stubs for get, set, del, quit, on, status); validateEnv.js returns early in test mode to skip missing env var checks. Retry logic and logging formatting adjusted in redis.js.
Tests & mocks
backend/tests/health.test.js, backend/tests/auth.test.js
Adds a health-check test (GET / → 200, { status: "success" }); enhances auth.test.js with dotenv fallbacks, default TEST_MONGO_URL/JWT_SECRET, and richer mocks for ioredis and the resend email service.
Minor formatting/cleanup
backend/config/redis.js, backend/tests/auth.test.js
Consistent use of double quotes, comment adjustments, minor refactors and removal of duplicate dotenv calls or debug logs in tests.

Sequence Diagram(s)

(omitted — changes are small and do not introduce a multi-component sequential flow requiring visualization)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🐰 In test-time burrows I quietly play,
Dummy Redis naps where real sockets lay,
Health pings return "success" with a cheer,
Env checks snooze while tests hop near,
Code carrots saved — review, then hooray! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the two main changes: adding a health endpoint smoke test and making Redis test-safe for test environments.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
backend/tests/auth.test.js (1)

50-57: Remove debug console.log calls and the now-redundant URI validation.

Lines 52–53 are debug artifacts that add noise to test output. The validation block on lines 55–57 can never trigger because line 9–10 already guarantees TEST_MONGO_URL is a valid mongodb:// string. Consider cleaning both up.

♻️ Suggested cleanup
 beforeAll(async () => {
     const uri = process.env.TEST_MONGO_URL;
 
-    console.log("URI Length:", uri ? uri.length : 0);
-    console.log("URI Starts with mongodb:", uri ? uri.startsWith('mongodb') : false);
-
-    if (!uri || !uri.startsWith('mongodb')) {
-        throw new Error(`Invalid TEST_MONGO_URL! Received: ${uri ? 'invalid format' : 'nothing'}`);
-    }
-
     await mongoose.disconnect();
     await mongoose.connect(uri);
 });

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@backend/config/redis.js`:
- Around line 27-31: The debug line that prints Object.keys(process.env) inside
the REDIS_URL existence check should be removed or replaced because it exposes
sensitive environment variable names; in the REDIS_URL check (the top-level
block that throws "REDIS_URL is not defined in .env") remove the
console.log("DEBUG: ENV KEYS:", Object.keys(process.env)) call and, if you need
runtime context, replace it with a non-sensitive message (e.g., log only
NODE_ENV or a boolean indicating missing vars) so that no environment keys or
secrets are ever printed to logs.

In `@backend/tests/health.test.js`:
- Around line 1-11: The test leaves the server running because app.js calls
app.listen on require; add an afterAll hook that closes the server to avoid port
conflicts. Change the test to require the server instance (e.g., const server =
require("../app");) or adjust app.js to export the server returned by app.listen
(keep symbol name server), then add afterAll(async () => server.close()); (or
call done/return a promise) to properly close the server after tests; reference
afterAll, app, server, and app.listen when making the change.
🧹 Nitpick comments (1)
backend/config/redis.js (1)

34-44: Retry strategy allows the first 3 retries but the delay is computed before the bail-out check.

Minor: delay is computed on every call including when times > 3 (where it's discarded). This is harmless but the logic reads more clearly if the bail-out check comes first.

Also, maxRetriesPerRequest: null means individual commands will retry indefinitely if Redis is down — confirm this is intentional (e.g., for BullMQ compatibility).

Comment thread backend/config/redis.js
Comment on lines +1 to +11
const request = require("supertest");
const app = require("../app");

describe("Health Check API", () => {
it("should return 200 and success message", async () => {
const res = await request(app).get("/");

expect(res.statusCode).toBe(200);
expect(res.body.status).toBe("success");
});
});

@coderabbitai coderabbitai Bot Feb 11, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Find all test files in backend/tests
fd '.test.js' --base-directory backend/tests 2>/dev/null || find backend/tests -name '*.test.js' 2>/dev/null

# Check app.js for app.listen and exports
echo "=== Checking app.js for listen/exports ==="
rg -n 'app\.listen|module\.exports\s*=|exports\s*=' backend/app.js

# Look for auth-related test files
echo "=== Looking for auth test files ==="
fd -e js --base-directory backend/tests | grep -i auth

Repository: yash-pouranik/urBackend

Length of output: 260


🏁 Script executed:

# Check the context around app.listen() call
sed -n '125,145p' backend/app.js

# Check if there's any conditional wrapping around listen
sed -n '120,170p' backend/app.js | head -50

# Read auth.test.js to see what it tests
cat backend/tests/auth.test.js

Repository: yash-pouranik/urBackend

Length of output: 5194


Add afterAll hook to close the server and prevent port conflicts.

The health check test is correct, but it leaves the server running. Since app.js unconditionally calls app.listen(PORT) on require (line 132), running multiple test files in the same suite can cause port binding conflicts or open-handle warnings in Jest.

Add an afterAll hook to close the server:

Required addition
 const request = require("supertest");
 const app = require("../app");
 
 describe("Health Check API", () => {
+  let server;
+  afterAll((done) => {
+    if (server) server.close(done);
+    else done();
+  });
+
   it("should return 200 and success message", async () => {
-    const res = await request(app).get("/");
+    server = app._server || app;
+    const res = await request(app).get("/");
 
     expect(res.statusCode).toBe(200);
     expect(res.body.status).toBe("success");
   });
 });

Alternatively, refactor app.js to defer app.listen() until explicitly called (e.g., only in production or when not being required by tests), which is a cleaner long-term fix.

🧰 Tools
🪛 GitHub Actions: CI (Continuous Integration)

[error] 1-1: Test suite failed: Auth API login expected 200 but received 500 during CI run. Command: 'cd backend && npm test'.

🤖 Prompt for AI Agents
In `@backend/tests/health.test.js` around lines 1 - 11, The test leaves the server
running because app.js calls app.listen on require; add an afterAll hook that
closes the server to avoid port conflicts. Change the test to require the server
instance (e.g., const server = require("../app");) or adjust app.js to export
the server returned by app.listen (keep symbol name server), then add
afterAll(async () => server.close()); (or call done/return a promise) to
properly close the server after tests; reference afterAll, app, server, and
app.listen when making the change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alok-kumar0421 resolve this

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@alok-kumar0421

Copy link
Copy Markdown
Contributor Author

All backend tests are passing locally and in CI.
Redis and environment dependencies have been handled to ensure test reliability.

Please let me know if any further adjustments are needed.

@alok-kumar0421

Copy link
Copy Markdown
Contributor Author

hi mentor,please reeview my pr

@yash-pouranik
yash-pouranik self-requested a review February 12, 2026 15:51
@yash-pouranik

Copy link
Copy Markdown
Member

Really Sorry i forgot to look into the PR, Just reviewing it. @alok-kumar0421

@alok-kumar0421

Copy link
Copy Markdown
Contributor Author

@yash-pouranik no problem at all.

Comment on lines +1 to +11
const request = require("supertest");
const app = require("../app");

describe("Health Check API", () => {
it("should return 200 and success message", async () => {
const res = await request(app).get("/");

expect(res.statusCode).toBe(200);
expect(res.body.status).toBe("success");
});
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alok-kumar0421 resolve this

const requiredEnvVars = ["MONGO_URL", "PORT", "REDIS_URL"];

function validateEnv() {
if (process.env.NODE_ENV === "test") return;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alok-kumar0421 look into ./backend/app.js i prevented the validateEnv function call if env is test
so i think you can remove this. hmm??

@vercel

vercel Bot commented Feb 12, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
ur-backend Ready Ready Preview, Comment Feb 13, 2026 7:41am

@yash-pouranik

Copy link
Copy Markdown
Member

@alok-kumar0421 ??

@yash-pouranik

Copy link
Copy Markdown
Member

closing as there's no response

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

Successfully merging this pull request may close these issues.

2 participants