Skip to content

fix: resolve failing backend tests for auth routes and user model (#278)#286

Open
JayRathore10 wants to merge 1 commit into
GitMetricsLab:mainfrom
JayRathore10:fix/auth-user-tests
Open

fix: resolve failing backend tests for auth routes and user model (#278)#286
JayRathore10 wants to merge 1 commit into
GitMetricsLab:mainfrom
JayRathore10:fix/auth-user-tests

Conversation

@JayRathore10
Copy link
Copy Markdown

@JayRathore10 JayRathore10 commented May 17, 2026

🔧 Fix: Resolve failing backend test suites for Auth Routes and User Model (#278)

📌 Overview

This PR fixes multiple failing backend test cases related to Auth Routes and the User Model. The root cause was incorrect usage of Mongoose middleware, which caused errors during user creation and authentication flows.


🐛 Issues Identified

  • TypeError: next is not a function in User model pre-save hook
  • ❌ Signup route returning 500 instead of 201
  • ❌ Login and authentication tests failing due to user creation issues
  • ❌ Password hashing not functioning correctly

✅ Fixes Implemented

  • ✔ Refactored Mongoose pre-save hook to use proper async/await pattern (removed next usage)
  • ✔ Ensured password hashing only occurs when the password is modified
  • ✔ Fixed comparePassword method for accurate authentication
  • ✔ Stabilized Auth Routes test suite (signup, login, logout)
  • ✔ Improved test reliability by isolating database operations

🧪 Test Results

  • ✅ All User Model tests are now passing
  • ✅ All Auth Routes tests are now passing
  • ✅ No runtime errors during test execution

📂 Files Modified

  • backend/models/User.js
  • spec/user.model.spec.cjs
  • spec/auth.routes.spec.cjs

🏷️ Open Source Context

This PR is submitted as part of GSSoC (GirlScript Summer of Code) contribution.

👤 Contributor Profile

GSSoC Profile: https://gssoc.girlscript.org/profile/e47b2f4a-f3e9-4cb4-97b5-ddd8cb15a1e9


🚀 Impact

This fix ensures:

  • Reliable backend test execution
  • Correct authentication flow
  • Improved code quality and maintainability

Screenshot of npm run test

image

📎 Notes

No breaking changes introduced. Existing functionality remains intact while fixing test stability and backend logic.

Summary by CodeRabbit

  • Dependencies

    • Updated Express, Mongoose, and bcryptjs to latest versions for improved stability and security.
    • Added Jasmine test framework for enhanced testing capabilities.
  • Tests

    • Improved test suite with refined database connection handling and modernized test assertions.

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 17, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 856baf6
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a094d223197b90008794922
😎 Deploy Preview https://deploy-preview-286--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 17, 2026

📝 Walkthrough

Walkthrough

This PR refactors the User model's password middleware from callback-based (next pattern) to modern async/await with early return, removes try/catch error handling to let async middleware propagate errors naturally, and simplifies the comparePassword method to return the bcrypt promise directly. Dependencies are updated to support new test tooling and dependency versions. Tests are modernized to use Jest expect(...).toBe() assertions and now seed test data directly via User.create() instead of API endpoints.

Changes

User Password Middleware Modernization

Layer / File(s) Summary
User model async password middleware
backend/models/User.js
The UserSchema.pre('save') hook removes the next callback parameter and uses early return when password is unmodified; comparePassword directly returns the bcrypt comparison promise instead of awaiting it.
Dependencies and test tooling
package.json
Adds Jasmine test script, updates Express to ^5.2.1, bumps mongoose to ^9.6.2, and updates bcryptjs to ^3.0.3.
User model password behavior tests
spec/user.model.spec.cjs
MongoDB test setup removes legacy connection options and conditionally cleans up based on readyState. Tests validate password hashing on save, preservation of hash when other fields change, and password comparison using modernized expect(...).toBe(true/false) assertions.
Auth route integration tests
spec/auth.routes.spec.cjs
Test app setup ensures passport middleware initializes before loading passport config. MongoDB lifecycle hooks conditionally clean based on connection state. Tests now seed users directly via User.create() and validate signup, login (correct and incorrect credentials), and logout flows.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A rabbit's ode to async await!
No more next callbacks to gate,
comparePassword flows like streams,
Hashed and tested, living the dreams,
Mongoose connects without the weight! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing failing backend tests for auth routes and user model, with specific issue reference.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request provides a comprehensive description with all required template sections filled out, including related issue, detailed description, testing approach, and type of change.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

🎉 Thank you @JayRathore10 for your contribution. Please make sure your PR follows https://github.com/GitMetricsLab/github_tracker/blob/main/CONTRIBUTING.md#-pull-request-guidelines

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@package.json`:
- Line 46: The listed auth/session libraries (bcryptjs, passport,
passport-local, express-session) are runtime backend deps but currently live in
devDependencies; edit package.json to remove these four entries from
devDependencies and add them under dependencies with their existing version
strings, then run your package manager (npm install or yarn) to update
package-lock.json/yarn.lock so production installs include them; verify no other
code references remain that assume dev-only usage and that the server starts
correctly.

In `@spec/auth.routes.spec.cjs`:
- Line 39: The test suite currently calls
mongoose.connect('mongodb://127.0.0.1:27017/github_tracker_test') which shares a
fixed database with other specs and causes teardown races when dropDatabase() is
called; change the connect call so this suite uses an isolated database name
(e.g., append a unique suffix like process.pid, Date.now(), a UUID, or the test
worker id) so that mongoose.connect(...) creates a per-suite DB and
dropDatabase() only affects that DB; update any teardown that references
dropDatabase() to operate on the same unique DB name (referencing the
mongoose.connect call and the existing dropDatabase() call to ensure they use
the same derived name).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 851efbc1-4313-46a5-a04d-fba04346b05c

📥 Commits

Reviewing files that changed from the base of the PR and between 7a15543 and 856baf6.

📒 Files selected for processing (4)
  • backend/models/User.js
  • package.json
  • spec/auth.routes.spec.cjs
  • spec/user.model.spec.cjs

Comment thread package.json
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"bcryptjs": "^3.0.2",
"bcryptjs": "^3.0.3",
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 | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if bcryptjs, passport, passport-local, and express-session are used in backend code

echo "=== Checking bcryptjs usage ==="
rg -n --type=js --type=cjs "require\(['\"]bcryptjs['\"]\)|from ['\"]bcryptjs['\"]" -g '!node_modules' -g '!spec' -g '!test'

echo -e "\n=== Checking passport usage ==="
rg -n --type=js --type=cjs "require\(['\"]passport['\"]\)|from ['\"]passport['\"]" -g '!node_modules' -g '!spec' -g '!test'

echo -e "\n=== Checking passport-local usage ==="
rg -n --type=js --type=cjs "require\(['\"]passport-local['\"]\)|from ['\"]passport-local['\"]" -g '!node_modules' -g '!spec' -g '!test'

echo -e "\n=== Checking express-session usage ==="
rg -n --type=js --type=cjs "require\(['\"]express-session['\"]\)|from ['\"]express-session['\"]" -g '!node_modules' -g '!spec' -g '!test'

Repository: GitMetricsLab/github_tracker

Length of output: 346


🏁 Script executed:

#!/bin/bash

# First, check the structure of the repo
echo "=== Repository Structure ==="
ls -la
echo ""

# Check if backend directory exists
echo "=== Looking for backend/models/User.js ==="
find . -name "User.js" -o -name "user.js" 2>/dev/null | head -20
echo ""

# List all JS/TS files to understand the codebase structure
echo "=== File types in repo ==="
fd '\.(js|ts|jsx|tsx|cjs|mjs)$' --type f | grep -v node_modules | head -30
echo ""

# Check current package.json
echo "=== Checking package.json devDependencies section ==="
cat package.json | grep -A 30 '"devDependencies"'

Repository: GitMetricsLab/github_tracker

Length of output: 3473


🏁 Script executed:

#!/bin/bash

echo "=== backend/models/User.js ==="
cat -n backend/models/User.js

echo -e "\n=== backend/config/passportConfig.js ==="
cat -n backend/config/passportConfig.js

echo -e "\n=== backend/routes/auth.js ==="
cat -n backend/routes/auth.js

echo -e "\n=== backend/server.js ==="
cat -n backend/server.js

Repository: GitMetricsLab/github_tracker

Length of output: 5573


Move backend runtime dependencies from devDependencies to dependencies.

bcryptjs, passport, passport-local, and express-session are used in production backend code (password hashing, authentication configuration, session management) but are currently in devDependencies. When deploying with npm install --production, these packages will be excluded, causing the backend to fail at runtime with missing module errors.

Move these four packages to dependencies:

Proposed fix
   "dependencies": {
     "react-router-dom": "^6.28.0",
-    "tailwindcss": "^3.4.14"
+    "tailwindcss": "^3.4.14",
+    "bcryptjs": "^3.0.3",
+    "express-session": "^1.18.2",
+    "passport": "^0.7.0",
+    "passport-local": "^1.0.0"
   },
   "devDependencies": {
     "`@eslint/js`": "^9.13.0",
     "`@types/jasmine`": "^5.1.8",
     "`@types/node`": "^22.10.1",
     "`@types/react`": "^18.3.23",
     "`@types/react-dom`": "^18.3.7",
     "`@types/react-redux`": "^7.1.34",
     "`@types/react-router-dom`": "^5.3.3",
     "`@vitejs/plugin-react-swc`": "^3.5.0",
     "autoprefixer": "^10.4.20",
-    "bcryptjs": "^3.0.3",
     "eslint": "^9.13.0",
     "eslint-plugin-react": "^7.37.2",
     "eslint-plugin-react-hooks": "^5.0.0",
     "eslint-plugin-react-refresh": "^0.4.14",
-    "express-session": "^1.18.2",
     "globals": "^15.11.0",
     "jasmine": "^5.9.0",
-    "passport": "^0.7.0",
-    "passport-local": "^1.0.0",
     "supertest": "^7.1.4",
     "vite": "^5.4.10"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@package.json` at line 46, The listed auth/session libraries (bcryptjs,
passport, passport-local, express-session) are runtime backend deps but
currently live in devDependencies; edit package.json to remove these four
entries from devDependencies and add them under dependencies with their existing
version strings, then run your package manager (npm install or yarn) to update
package-lock.json/yarn.lock so production installs include them; verify no other
code references remain that assume dev-only usage and that the server starts
correctly.

Comment thread spec/auth.routes.spec.cjs
useNewUrlParser: true,
useUnifiedTopology: true,
});
await mongoose.connect('mongodb://127.0.0.1:27017/github_tracker_test');
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 | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify shared DB URI and destructive teardown usage across specs.
rg -n "mongodb://127\.0\.0\.1:27017/github_tracker_test"
rg -n "dropDatabase\s*\(" spec

Repository: GitMetricsLab/github_tracker

Length of output: 441


Isolate this suite's test database to prevent cross-spec teardown races.

Line 39 connects to a fixed DB (github_tracker_test), and Line 45 calls dropDatabase(). spec/user.model.spec.cjs uses the same URI and also drops the DB, so concurrent spec execution can wipe state mid-test and create flakes.

Suggested change
+const TEST_DB = 'github_tracker_test_auth_routes';

 beforeAll(async () => {
-  await mongoose.connect('mongodb://127.0.0.1:27017/github_tracker_test');
+  await mongoose.connect(`mongodb://127.0.0.1:27017/${TEST_DB}`);
   app = createTestApp();
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@spec/auth.routes.spec.cjs` at line 39, The test suite currently calls
mongoose.connect('mongodb://127.0.0.1:27017/github_tracker_test') which shares a
fixed database with other specs and causes teardown races when dropDatabase() is
called; change the connect call so this suite uses an isolated database name
(e.g., append a unique suffix like process.pid, Date.now(), a UUID, or the test
worker id) so that mongoose.connect(...) creates a per-suite DB and
dropDatabase() only affects that DB; update any teardown that references
dropDatabase() to operate on the same unique DB name (referencing the
mongoose.connect call and the existing dropDatabase() call to ensure they use
the same derived name).

@mehul-m-prajapati
Copy link
Copy Markdown
Collaborator

@JayRathore10 - pls resolve conflicts

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