Skip to content

Conversation

@yuvraj-kolkar17
Copy link

@yuvraj-kolkar17 yuvraj-kolkar17 commented Jan 7, 2026

What kind of change does this PR introduce?

Bug fix – Setup file execution issue

Issue Number

Fixes #6184

Snapshots/Videos

image ## If relevant, did you update the documentation? N/A

Summary

This PR implements conditional execution for the setup.ts module to prevent automatic execution during testing.

Changes Made:

  • Wrapped main() execution in a require.main === module check in setup.ts
  • Updated setup.spec.ts to include a test case verifying conditional execution
  • Added an explicit test: "should not auto-execute main() when imported for testing"

Impact:

  • Tests can now import setup functions without triggering full execution
  • Prevents unintended side effects during test imports
  • Makes testing more reliable and easier to write

Testing:

  • All existing tests pass
  • New test specifically validates conditional execution

Does this PR introduce a breaking change?

No

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

N/A

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • Bug Fixes

    • Safer setup execution with guarded startup and clearer error handling/exit behavior to avoid accidental runs and make failures more visible.
  • Tests

    • Expanded test coverage for setup flows: Docker paths, reCAPTCHA opt-in/out, logging opt-in/out, port/API updates, failure paths, messages, and edge cases.
  • New Features

    • Logging configuration controls surfaced to tooling for explicit opt-in/opt-out handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@keploy
Copy link

keploy bot commented Jan 7, 2026

No significant changes currently retry

@github-actions
Copy link

github-actions bot commented Jan 7, 2026

Our Pull Request Approval Process

This PR will be reviewed according to our:

  1. Palisadoes Contributing Guidelines

  2. AI Usage Policy

Your PR may be automatically closed if:

  1. Our PR template isn't filled in correctly

  2. You haven't correctly linked your PR to an issue

Thanks for contributing!

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 7, 2026

Walkthrough

Added a conditional guard so main() runs only when executed directly, exported askAndSetLogErrors to standardize the public API, and expanded unit tests to cover reCAPTCHA, logging, Docker flows, env backup/updates, error paths, and edge cases.

Changes

Cohort / File(s) Summary
Setup Module Core Changes
src/setup/setup.ts
Wraps top-level main() in if (require.main === module) { main().catch(...); } to avoid execution on import; logs errors and exits with code 1 on unhandled failures; askAndSetLogErrors changed from a private const to export const (no implementation change).
Setup Test Coverage Expansion
src/setup/setup.spec.ts
Tests reworked to import functions directly; added console spies, mocked backupEnvFile and validateRecaptcha; expanded scenarios for Docker=YES/NO, reCAPTCHA opt-in/out and validation handling, log-errors prompts, env backup and updates, multiple error-path tests asserting process.exit(1), welcome/success/error messages, and edge cases (empty/malformed env, Docker flag case sensitivity).

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: making setup.ts module execution conditional to prevent automatic execution during import.
Description check ✅ Passed The PR description is largely complete, addressing what kind of change it is (bug fix), issue number (#6184), summary of changes made, impact, testing status, and contributing guide acknowledgment. While test coverage verification is not fully marked, all other required sections are present.
Linked Issues check ✅ Passed The PR successfully fulfills all coding requirements from issue #6184: conditional execution via require.main === module check is implemented, askAndSetLogErrors is now exported consistently, tests import functions directly without triggering side effects, and error handling with process.exit(1) is in place.
Out of Scope Changes check ✅ Passed All changes in the PR are directly scoped to the linked issue #6184: setup.ts conditional execution, consistent exports of helper functions, and comprehensive test coverage for the new behavior and existing functionality.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9600bfd and d421e86.

📒 Files selected for processing (1)
  • src/setup/setup.spec.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{test,spec}.{ts,tsx}: Validate test files cover all use cases including edge cases, error scenarios, and success paths with 100% test code coverage for all modified/added functions, components, and branches
Test files must have valid, properly structured tests following Jest and React Testing Library best practices
Tests must include proper mocking of GraphQL queries/mutations, external dependencies, and API calls
Test files must follow naming conventions (*.test.tsx, *.test.ts, *.spec.tsx, *.spec.ts)
Tests must not include disabled tests (it.skip, describe.skip) unless explicitly documented
Mock data cleanup must be performed as required by pre-commit hooks

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx}: No use of any type without explicit justification in TypeScript files
Proper interface/type definitions must be provided for all props, state, and function parameters in TypeScript
No TypeScript errors or warnings in the codebase
Error handling must be implemented for all GraphQL operations
Adequate JSDoc comments must be provided on public functions and complex logic
No unused imports or dead code as checked by knip
TypeScript type checking must pass without errors
Proper input validation and sanitization must be implemented for all user inputs
No SQL injection or XSS vulnerabilities must be present in any data handling code
Foreign key relationships must be correctly enforced in database operations

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,json,env}

📄 CodeRabbit inference engine (Custom checks)

No sensitive information including API keys, tokens, or credentials must be exposed

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,json,js}

📄 CodeRabbit inference engine (Custom checks)

Pre-commit hook requirements must be met including code formatting with Prettier

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx,js}: ESLint linting requirements must be satisfied in all code files
No security vulnerabilities must be introduced

Files:

  • src/setup/setup.spec.ts
🧠 Learnings (4)
📚 Learning: 2025-12-21T08:59:37.942Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5287
File: src/shared-components/Recurrence/CustomRecurrenceModal.spec.tsx:78-84
Timestamp: 2025-12-21T08:59:37.942Z
Learning: In talawa-admin test files, ensure each spec file uses an explicit vi.clearAllMocks() in an afterEach block to guarantee test isolation. This should be present even if a global cleanup exists in vitest.setup.ts, as the linter enforces per-file hygiene. Apply this guideline to all spec files (e.g., src/**/*.spec.tsx) to satisfy ESLint/Vitest requirements and prevent bleed-over between tests.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2025-12-27T11:22:41.191Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5782
File: src/screens/Leaderboard/Leaderboard.spec.tsx:342-370
Timestamp: 2025-12-27T11:22:41.191Z
Learning: In test files that render screens with shared components (e.g., src/screens/Leaderboard/Leaderboard.spec.tsx), verify integration behavior by asserting the screen renders correctly in different scenarios (e.g., search results) without asserting the internal ARIA attributes, text, or icons of the shared component. Rely on the shared component's own tests to cover accessibility and presentation details. This keeps tests focused on higher-level behavior and interactions.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-06T21:27:50.880Z
Learnt from: Jashan32
Repo: PalisadoesFoundation/talawa-admin PR: 6222
File: src/utils/userUpdateUtils.ts:22-22
Timestamp: 2026-01-06T21:27:50.880Z
Learning: In the Talawa Admin codebase, the i18n extraction tool can misclassify TypeScript generic syntax (e.g., (obj: T): Partial) as translatable content. Suppress these false positives by adding a // i18n-ignore-next-line comment directly above the line with the type declaration or generic function signature. Apply this only to TS code where misclassification is confirmed; avoid blanket suppression.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-07T14:21:19.711Z
Learnt from: cotishq
Repo: PalisadoesFoundation/talawa-admin PR: 6198
File: src/setup/setup.ts:123-124
Timestamp: 2026-01-07T14:21:19.711Z
Learning: Use TSDoc (eslint-plugin-tsdoc) instead of JSDoc. Do not wrap type names in curly braces in throws and returns. Write as "throws Error" and "returns Promise<void>" (no braces). Curly-brace usage causes tsdoc-malformed-inline-tag and tsdoc-escape-right-brace lint errors. Apply this rule to all TypeScript source files (e.g., src/**/*.ts) to ensure consistency.

Applied to files:

  • src/setup/setup.spec.ts
🧬 Code graph analysis (1)
src/setup/setup.spec.ts (1)
src/setup/setup.ts (3)
  • main (65-98)
  • askAndSetRecaptcha (13-49)
  • askAndSetLogErrors (52-62)
🔇 Additional comments (7)
src/setup/setup.spec.ts (7)

15-22: Excellent type safety improvement!

The PromptQuestion interface properly replaces the previous as any casts and provides strong typing for inquirer prompt interactions. The interface is well-structured with appropriate optional fields and a properly typed validate function.


42-75: Well-structured test setup and teardown.

The test harness properly:

  • Creates spies for console.log and console.error to verify messaging
  • Mocks process.exit to throw, enabling clean async error testing
  • Uses vi.clearAllMocks() in afterEach for proper test isolation (per repository conventions)
  • Restores all spies to prevent test interference

The setup provides a solid foundation for comprehensive testing.


77-294: Exceptional test coverage of the main setup flow.

These tests thoroughly validate:

  • ✅ Success paths with default options and full configurations
  • ✅ Conditional logic (Docker=YES skips port setup, Docker=NO includes it)
  • ✅ Error handling for each setup step with proper process.exit(1) behavior
  • ✅ Early return when environment check fails
  • ✅ User-facing messages (welcome, success, error support)
  • ✅ Integration between setup steps

The tests properly assert that errors halt execution and prevent subsequent steps from running (e.g., line 245), which validates the error-handling flow.


296-461: Comprehensive reCAPTCHA setup testing.

The test suite thoroughly covers:

  • ✅ User opt-in with valid key validation
  • ✅ User opt-out (verifies site key prompt is skipped at line 334)
  • ✅ Validation function behavior for both valid and invalid inputs
  • ✅ Error propagation with helpful messages
  • ✅ Error handling at each prompt stage

The validation tests properly assert validateFn is defined (lines 395, 417) before invoking it, preventing silent test passes if the validation function is missing.


526-540: Critical test validates conditional execution requirement.

This test directly addresses the PR objective to prevent automatic execution on import:

  • Clears all mocks to reset state
  • Asserts setup functions have not been called before explicit invocation
  • Verifies all exports are available for testing

This ensures the require.main === module guard in the source file works correctly and modules can safely import setup functions without triggering side effects.


543-586: Excellent edge case coverage for robust error handling.

These tests validate the setup handles real-world scenarios gracefully:

  • ✅ Empty environment configuration (defaults to Docker=NO path)
  • ✅ Malformed environment files
  • ✅ Case-sensitive Docker flag handling (correctly treats lowercase "yes" as false per line 583)

The edge cases ensure the setup script is resilient to various environment states and configuration formats.


1-587: Outstanding test coverage and quality! 🎉

This test file demonstrates exemplary testing practices:

Strengths:

  • Complete coverage: Main flow, reCAPTCHA, logging, error paths, and edge cases all thoroughly tested
  • Type safety: Proper PromptQuestion interface eliminates unsafe any usage
  • Test isolation: Proper use of vi.clearAllMocks() in afterEach per repository conventions
  • Error handling: Comprehensive validation of error paths with proper process.exit(1) testing
  • PR objectives: Directly validates conditional execution (lines 526-540) and standardized exports
  • Edge cases: Tests empty configs, malformed content, and case-sensitive flags
  • Best practices: No disabled tests, proper mocking patterns, descriptive test names

Alignment with acceptance criteria:

  • Validates main() is not auto-executed on import ✅
  • Tests all exported helper functions ✅
  • Confirms proper exit-code error handling ✅
  • Verifies all flows pass ✅

The test suite provides excellent confidence in the setup module's reliability and correctly validates the bug fix for issue #6184.


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
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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/setup/setup.ts (1)

52-62: Consider adding error handling for consistency with askAndSetRecaptcha.

The askAndSetRecaptcha function wraps errors with try-catch and provides a contextual error message (lines 45-48), but askAndSetLogErrors lacks this pattern. While errors will propagate to main(), adding consistent error handling would improve debuggability.

♻️ Suggested refactor for consistent error handling
 export const askAndSetLogErrors = async (): Promise<void> => {
+  try {
     const { shouldLogErrors } = await inquirer.prompt({
       type: 'confirm',
       name: 'shouldLogErrors',
       message:
         'Would you like to log Compiletime and Runtime errors in the console?',
       default: true,
     });
 
     updateEnvFile('ALLOW_LOGS', shouldLogErrors ? 'YES' : 'NO');
+  } catch (error) {
+    console.error('Error setting up log configuration:', error);
+    throw new Error(`Failed to set up log configuration: ${(error as Error).message}`);
+  }
 };
🤖 Fix all issues with AI agents
In @src/setup/setup.spec.ts:
- Around line 169-173: The test swallows errors with an empty catch block;
replace the try/catch pattern around main() with a Jest rejects assertion for
consistency with other error tests—e.g., change the try/catch to await
expect(main()).rejects.toThrow() (or .rejects.toBeInstanceOf(Error) /
.rejects.toMatchInlineSnapshot() as appropriate) so the test explicitly asserts
that main() rejects.
- Around line 586-599: The test title "should not auto-execute main() when
imported for testing" is misleading because the assertions only check exports;
rename the test to accurately reflect its checks (e.g., "should export required
functions" or "should not auto-execute main on import — verify exports") or
replace the title and add an explicit side-effect assertion by confirming the
mocked function (e.g., checkEnvFile) was not called before invoking main; update
the test that references main, askAndSetRecaptcha, askAndSetLogErrors (and
optionally checkEnvFile mock) to match the new intent.

In @src/setup/setup.ts:
- Around line 100-105: The file uses CommonJS execution guard require.main ===
module which is incompatible with ES modules; replace that guard with an
import.meta.url check (if (import.meta.url === `file://${process.argv[1]}`) {
... }) and invoke main() inside it; because main() already handles errors and
calls process.exit(1) internally, remove the outer .catch(...) block so you
don't double-handle errors—locate the invocation of main() and the surrounding
guard and update them to use import.meta.url and no outer catch.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c6638b2 and b3f4714.

📒 Files selected for processing (2)
  • src/setup/setup.spec.ts
  • src/setup/setup.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{test,spec}.{ts,tsx}: Validate test files cover all use cases including edge cases, error scenarios, and success paths with 100% test code coverage for all modified/added functions, components, and branches
Test files must have valid, properly structured tests following Jest and React Testing Library best practices
Tests must include proper mocking of GraphQL queries/mutations, external dependencies, and API calls
Test files must follow naming conventions (*.test.tsx, *.test.ts, *.spec.tsx, *.spec.ts)
Tests must not include disabled tests (it.skip, describe.skip) unless explicitly documented
Mock data cleanup must be performed as required by pre-commit hooks

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx}: No use of any type without explicit justification in TypeScript files
Proper interface/type definitions must be provided for all props, state, and function parameters in TypeScript
No TypeScript errors or warnings in the codebase
Error handling must be implemented for all GraphQL operations
Adequate JSDoc comments must be provided on public functions and complex logic
No unused imports or dead code as checked by knip
TypeScript type checking must pass without errors
Proper input validation and sanitization must be implemented for all user inputs
No SQL injection or XSS vulnerabilities must be present in any data handling code
Foreign key relationships must be correctly enforced in database operations

Files:

  • src/setup/setup.spec.ts
  • src/setup/setup.ts
**/*.{ts,tsx,json,env}

📄 CodeRabbit inference engine (Custom checks)

No sensitive information including API keys, tokens, or credentials must be exposed

Files:

  • src/setup/setup.spec.ts
  • src/setup/setup.ts
**/*.{ts,tsx,json,js}

📄 CodeRabbit inference engine (Custom checks)

Pre-commit hook requirements must be met including code formatting with Prettier

Files:

  • src/setup/setup.spec.ts
  • src/setup/setup.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx,js}: ESLint linting requirements must be satisfied in all code files
No security vulnerabilities must be introduced

Files:

  • src/setup/setup.spec.ts
  • src/setup/setup.ts
🧠 Learnings (4)
📚 Learning: 2025-12-21T08:59:37.942Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5287
File: src/shared-components/Recurrence/CustomRecurrenceModal.spec.tsx:78-84
Timestamp: 2025-12-21T08:59:37.942Z
Learning: In talawa-admin test files, ensure each spec file uses an explicit vi.clearAllMocks() in an afterEach block to guarantee test isolation. This should be present even if a global cleanup exists in vitest.setup.ts, as the linter enforces per-file hygiene. Apply this guideline to all spec files (e.g., src/**/*.spec.tsx) to satisfy ESLint/Vitest requirements and prevent bleed-over between tests.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2025-12-27T11:22:41.191Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5782
File: src/screens/Leaderboard/Leaderboard.spec.tsx:342-370
Timestamp: 2025-12-27T11:22:41.191Z
Learning: In test files that render screens with shared components (e.g., src/screens/Leaderboard/Leaderboard.spec.tsx), verify integration behavior by asserting the screen renders correctly in different scenarios (e.g., search results) without asserting the internal ARIA attributes, text, or icons of the shared component. Rely on the shared component's own tests to cover accessibility and presentation details. This keeps tests focused on higher-level behavior and interactions.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-06T21:27:50.880Z
Learnt from: Jashan32
Repo: PalisadoesFoundation/talawa-admin PR: 6222
File: src/utils/userUpdateUtils.ts:22-22
Timestamp: 2026-01-06T21:27:50.880Z
Learning: In the Talawa Admin codebase, the i18n extraction tool can misclassify TypeScript generic syntax (e.g., (obj: T): Partial) as translatable content. Suppress these false positives by adding a // i18n-ignore-next-line comment directly above the line with the type declaration or generic function signature. Apply this only to TS code where misclassification is confirmed; avoid blanket suppression.

Applied to files:

  • src/setup/setup.spec.ts
  • src/setup/setup.ts
📚 Learning: 2026-01-07T14:21:19.711Z
Learnt from: cotishq
Repo: PalisadoesFoundation/talawa-admin PR: 6198
File: src/setup/setup.ts:123-124
Timestamp: 2026-01-07T14:21:19.711Z
Learning: Use TSDoc (eslint-plugin-tsdoc) instead of JSDoc. Do not wrap type names in curly braces in throws and returns. Write as "throws Error" and "returns Promise<void>" (no braces). Curly-brace usage causes tsdoc-malformed-inline-tag and tsdoc-escape-right-brace lint errors. Apply this rule to all TypeScript source files (e.g., src/**/*.ts) to ensure consistency.

Applied to files:

  • src/setup/setup.spec.ts
  • src/setup/setup.ts
🧬 Code graph analysis (1)
src/setup/setup.spec.ts (1)
src/setup/setup.ts (3)
  • main (65-98)
  • askAndSetRecaptcha (13-49)
  • askAndSetLogErrors (52-62)
🔇 Additional comments (5)
src/setup/setup.spec.ts (5)

1-27: LGTM: Imports and mock setup are properly configured.

All new dependencies (validateRecaptcha, backupEnvFile, askAndSetLogErrors) are correctly imported and mocked to support the expanded test coverage.


28-65: LGTM: Test setup and teardown are properly configured.

The beforeEach correctly clears mocks and sets up default mock implementations. The afterEach properly restores spies and resets mocks to ensure test isolation. Based on learnings, the mock cleanup approach is appropriate.


354-528: LGTM: Comprehensive test coverage for askAndSetRecaptcha.

Tests thoroughly cover:

  • User opt-in/opt-out paths
  • Validation function behavior (valid/invalid keys)
  • Error propagation with contextual messages
  • Error handling during prompt and updateEnvFile operations

530-584: LGTM: Good test coverage for askAndSetLogErrors.

Tests cover opt-in/opt-out scenarios, error propagation, and validate the prompt configuration matches expected values.


601-666: LGTM: Comprehensive edge case coverage.

Tests properly cover:

  • Empty env config handling (defaults to non-Docker path)
  • Malformed env file content (graceful degradation)
  • Case-sensitive USE_DOCKER flag validation (lowercase "yes" ≠ "YES")
  • Error propagation across setup steps

The case-sensitivity test (lines 630-643) is particularly valuable as it validates the strict equality check envConfig.USE_DOCKER === 'YES' in the source.

Comment on lines +100 to +105
if (require.main === module) {
main().catch((error) => {
console.error('Setup failed:', error);
process.exit(1);
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, check if the file exists and view the relevant lines
if [ -f "src/setup/setup.ts" ]; then
  echo "=== Lines 93-105 of src/setup/setup.ts ==="
  sed -n '93,105p' src/setup/setup.ts
else
  echo "File not found, searching for setup.ts"
  find . -name "setup.ts" -type f
fi

Repository: PalisadoesFoundation/talawa-admin

Length of output: 426


🏁 Script executed:

# Check tsconfig.json for module configuration
echo "=== Checking tsconfig.json ==="
if [ -f "tsconfig.json" ]; then
  cat tsconfig.json | jq '.compilerOptions.module // "not set"' 2>/dev/null || cat tsconfig.json | grep -A2 -B2 '"module"'
else
  echo "No tsconfig.json found"
fi

# Check package.json for type field
echo ""
echo "=== Checking package.json type field ==="
if [ -f "package.json" ]; then
  cat package.json | jq '.type // "not set"' 2>/dev/null || grep '"type"' package.json
else
  echo "No package.json found"
fi

Repository: PalisadoesFoundation/talawa-admin

Length of output: 167


Replace require.main === module with ES module compatible pattern; current approach is incompatible with project configuration.

The project is configured for ES modules ("type": "module" in package.json and "module": "esnext" in tsconfig.json), but the code uses require.main === module, which is CommonJS-specific and will not work correctly. Use import.meta.url comparison instead:

if (import.meta.url === `file://${process.argv[1]}`) {
  // execution guard
}

Additionally, the outer .catch() block (lines 102-105) is redundant given the inner try-catch already handles errors with process.exit(1). Simplify by removing one layer.

🤖 Prompt for AI Agents
In @src/setup/setup.ts around lines 100 - 105, The file uses CommonJS execution
guard require.main === module which is incompatible with ES modules; replace
that guard with an import.meta.url check (if (import.meta.url ===
`file://${process.argv[1]}`) { ... }) and invoke main() inside it; because
main() already handles errors and calls process.exit(1) internally, remove the
outer .catch(...) block so you don't double-handle errors—locate the invocation
of main() and the surrounding guard and update them to use import.meta.url and
no outer catch.

Signed-off-by: Yuvraj Kolkar <[email protected]>
Copy link
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: 5

🤖 Fix all issues with AI agents
In @src/setup/setup.spec.ts:
- Around line 382-384: Replace the unsafe `as any` cast by defining and using a
proper typed interface for inquirer prompts (e.g., PromptQuestion with fields
type,name,message,default,validate) and apply it when extracting the mocked
call: cast vi.mocked(inquirer.prompt).mock.calls[1][0] to PromptQuestion |
PromptQuestion[] (or use a type guard) so `promptCall`, `questions`, and
`validateFn` are strongly typed; update the top of the test file to declare the
PromptQuestion interface and then remove the `as any` usage around
promptCall/validateFn.
- Around line 574-586: The test name claims multiple consecutive errors but only
throws once from modifyEnvFile; either rename the test to reflect a single
synchronous modifyEnvFile failure or update the test to simulate multiple steps
by mocking subsequent setup functions (e.g., askAndSetDockerOption) to throw or
to be asserted as not called; ensure you keep the call to main(), the
expect(main()).rejects check, and the consoleErrorSpy assertion for the original
error, and if testing multiple errors also assert that subsequent step mocks
(askAndSetDockerOption) were not invoked.
- Around line 60-65: Add an explicit call to vi.clearAllMocks() inside the
existing afterEach block to follow repository conventions and ensure test
isolation; specifically, update the afterEach that currently calls
vi.resetAllMocks(), processExitSpy.mockRestore(), consoleErrorSpy.mockRestore(),
and consoleLogSpy.mockRestore() by inserting vi.clearAllMocks() (in addition to
vi.resetAllMocks()) so both clearAllMocks() and resetAllMocks() are invoked
before restoring the spies in afterEach.
- Around line 515-528: The test named "should not auto-execute main() when
imported for testing" is misleading because it only asserts exports (main,
askAndSetRecaptcha, askAndSetLogErrors) which is already covered by the later
test; either remove this redundant first test or rename it to reflect that it
only checks exports, and if you want to truly assert no side effects on import,
replace its body to clear mocks (vi.clearAllMocks()) and assert that side-effect
functions like checkEnvFile and backupEnvFile were not called before any
explicit invocation of main(); update assertions to reference the actual
exported identifiers (main, askAndSetRecaptcha, askAndSetLogErrors,
checkEnvFile, backupEnvFile) accordingly.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b3f4714 and f28085e.

📒 Files selected for processing (1)
  • src/setup/setup.spec.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{test,spec}.{ts,tsx}: Validate test files cover all use cases including edge cases, error scenarios, and success paths with 100% test code coverage for all modified/added functions, components, and branches
Test files must have valid, properly structured tests following Jest and React Testing Library best practices
Tests must include proper mocking of GraphQL queries/mutations, external dependencies, and API calls
Test files must follow naming conventions (*.test.tsx, *.test.ts, *.spec.tsx, *.spec.ts)
Tests must not include disabled tests (it.skip, describe.skip) unless explicitly documented
Mock data cleanup must be performed as required by pre-commit hooks

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx}: No use of any type without explicit justification in TypeScript files
Proper interface/type definitions must be provided for all props, state, and function parameters in TypeScript
No TypeScript errors or warnings in the codebase
Error handling must be implemented for all GraphQL operations
Adequate JSDoc comments must be provided on public functions and complex logic
No unused imports or dead code as checked by knip
TypeScript type checking must pass without errors
Proper input validation and sanitization must be implemented for all user inputs
No SQL injection or XSS vulnerabilities must be present in any data handling code
Foreign key relationships must be correctly enforced in database operations

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,json,env}

📄 CodeRabbit inference engine (Custom checks)

No sensitive information including API keys, tokens, or credentials must be exposed

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,json,js}

📄 CodeRabbit inference engine (Custom checks)

Pre-commit hook requirements must be met including code formatting with Prettier

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx,js}: ESLint linting requirements must be satisfied in all code files
No security vulnerabilities must be introduced

Files:

  • src/setup/setup.spec.ts
🧠 Learnings (4)
📚 Learning: 2025-12-21T08:59:37.942Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5287
File: src/shared-components/Recurrence/CustomRecurrenceModal.spec.tsx:78-84
Timestamp: 2025-12-21T08:59:37.942Z
Learning: In talawa-admin test files, ensure each spec file uses an explicit vi.clearAllMocks() in an afterEach block to guarantee test isolation. This should be present even if a global cleanup exists in vitest.setup.ts, as the linter enforces per-file hygiene. Apply this guideline to all spec files (e.g., src/**/*.spec.tsx) to satisfy ESLint/Vitest requirements and prevent bleed-over between tests.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2025-12-27T11:22:41.191Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5782
File: src/screens/Leaderboard/Leaderboard.spec.tsx:342-370
Timestamp: 2025-12-27T11:22:41.191Z
Learning: In test files that render screens with shared components (e.g., src/screens/Leaderboard/Leaderboard.spec.tsx), verify integration behavior by asserting the screen renders correctly in different scenarios (e.g., search results) without asserting the internal ARIA attributes, text, or icons of the shared component. Rely on the shared component's own tests to cover accessibility and presentation details. This keeps tests focused on higher-level behavior and interactions.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-06T21:27:50.880Z
Learnt from: Jashan32
Repo: PalisadoesFoundation/talawa-admin PR: 6222
File: src/utils/userUpdateUtils.ts:22-22
Timestamp: 2026-01-06T21:27:50.880Z
Learning: In the Talawa Admin codebase, the i18n extraction tool can misclassify TypeScript generic syntax (e.g., (obj: T): Partial) as translatable content. Suppress these false positives by adding a // i18n-ignore-next-line comment directly above the line with the type declaration or generic function signature. Apply this only to TS code where misclassification is confirmed; avoid blanket suppression.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-07T14:21:19.711Z
Learnt from: cotishq
Repo: PalisadoesFoundation/talawa-admin PR: 6198
File: src/setup/setup.ts:123-124
Timestamp: 2026-01-07T14:21:19.711Z
Learning: Use TSDoc (eslint-plugin-tsdoc) instead of JSDoc. Do not wrap type names in curly braces in throws and returns. Write as "throws Error" and "returns Promise<void>" (no braces). Curly-brace usage causes tsdoc-malformed-inline-tag and tsdoc-escape-right-brace lint errors. Apply this rule to all TypeScript source files (e.g., src/**/*.ts) to ensure consistency.

Applied to files:

  • src/setup/setup.spec.ts
🧬 Code graph analysis (1)
src/setup/setup.spec.ts (1)
src/setup/setup.ts (3)
  • main (65-98)
  • askAndSetRecaptcha (13-49)
  • askAndSetLogErrors (52-62)
🔇 Additional comments (4)
src/setup/setup.spec.ts (4)

1-26: LGTM!

Imports are well-organized and all mocked dependencies are properly set up for test isolation. The addition of askAndSetLogErrors, validateRecaptcha, and backupEnvFile aligns with the expanded test coverage.


67-281: Comprehensive main() test coverage.

The test suite thoroughly covers:

  • Default options flow with Docker=NO
  • Docker=YES path (skipping port setup)
  • Error handling with proper process.exit(1) verification
  • Early return when env file check fails
  • Welcome and success message display
  • Individual error paths for each setup step (backupEnvFile, modifyEnvFile, askAndUpdatePort, askAndUpdateTalawaApiUrl, askAndSetRecaptcha, askAndSetLogErrors)

459-513: LGTM!

Good coverage of askAndSetLogErrors including opt-in/opt-out scenarios, error handling for both inquirer.prompt and updateEnvFile failures, and prompt configuration validation.


530-572: Good edge case coverage.

The edge case tests effectively document behavior for:

  • Empty env configuration (defaults to non-Docker flow)
  • Malformed env file content handling
  • Case-sensitive Docker flag comparison ('yes''YES')

This documents important implementation details about strict equality checking.

Signed-off-by: Yuvraj Kolkar <[email protected]>
Copy link
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: 3

🤖 Fix all issues with AI agents
In @src/setup/setup.spec.ts:
- Around line 396-402: The tests currently guard execution with "if
(validateFn)" which allows silent passes; update both invalid-key and valid-key
tests to explicitly assert validateFn is defined before calling it (e.g.,
expect(validateFn).toBeDefined() or throw/assert), then call
validateFn('invalid-key') and expect the error message, and likewise for the
valid key case (ensure vi.mocked(validateRecaptcha) mockReturnValue and then
assert validateFn is defined before invoking it and checking the success
message); reference the validateFn variable and the mocked validateRecaptcha to
locate the fixes.
- Around line 597-611: Two tests duplicate mocking modifyEnvFile throwing and
asserting main() rejects; remove the later test block that begins with "should
handle synchronous error from modifyEnvFile" and instead add the extra assertion
from it (that askAndSetDockerOption was not called) into the earlier test that
already mocks modifyEnvFile and checks consoleErrorSpy; specifically update the
existing test that mocks modifyEnvFile to include
expect(askAndSetDockerOption).not.toHaveBeenCalled(), keeping the same mocked
behavior and the consoleErrorSpy assertions so there is one consolidated test
for synchronous modifyEnvFile errors.
- Around line 338-351: The test creates redundant local spies for console.error;
remove the local spy creation (e.g., remove vi.spyOn(console,
'error').mockImplementation(...) and its mockRestore()) and replace references
to the local spy with the shared consoleErrorSpy created in beforeEach; update
assertions that call toHaveBeenCalledWith(...) to use consoleErrorSpy, and
ensure you do the same replacement in the other two test blocks that cover
askAndSetRecaptcha() (the blocks currently at the other ranges 432-445 and
457-470) so no local console.error spies are stacked or restored locally.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f28085e and 9600bfd.

📒 Files selected for processing (1)
  • src/setup/setup.spec.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{test,spec}.{ts,tsx}: Validate test files cover all use cases including edge cases, error scenarios, and success paths with 100% test code coverage for all modified/added functions, components, and branches
Test files must have valid, properly structured tests following Jest and React Testing Library best practices
Tests must include proper mocking of GraphQL queries/mutations, external dependencies, and API calls
Test files must follow naming conventions (*.test.tsx, *.test.ts, *.spec.tsx, *.spec.ts)
Tests must not include disabled tests (it.skip, describe.skip) unless explicitly documented
Mock data cleanup must be performed as required by pre-commit hooks

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx}: No use of any type without explicit justification in TypeScript files
Proper interface/type definitions must be provided for all props, state, and function parameters in TypeScript
No TypeScript errors or warnings in the codebase
Error handling must be implemented for all GraphQL operations
Adequate JSDoc comments must be provided on public functions and complex logic
No unused imports or dead code as checked by knip
TypeScript type checking must pass without errors
Proper input validation and sanitization must be implemented for all user inputs
No SQL injection or XSS vulnerabilities must be present in any data handling code
Foreign key relationships must be correctly enforced in database operations

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,json,env}

📄 CodeRabbit inference engine (Custom checks)

No sensitive information including API keys, tokens, or credentials must be exposed

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,json,js}

📄 CodeRabbit inference engine (Custom checks)

Pre-commit hook requirements must be met including code formatting with Prettier

Files:

  • src/setup/setup.spec.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (Custom checks)

**/*.{ts,tsx,js}: ESLint linting requirements must be satisfied in all code files
No security vulnerabilities must be introduced

Files:

  • src/setup/setup.spec.ts
🧠 Learnings (4)
📚 Learning: 2025-12-21T08:59:37.942Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5287
File: src/shared-components/Recurrence/CustomRecurrenceModal.spec.tsx:78-84
Timestamp: 2025-12-21T08:59:37.942Z
Learning: In talawa-admin test files, ensure each spec file uses an explicit vi.clearAllMocks() in an afterEach block to guarantee test isolation. This should be present even if a global cleanup exists in vitest.setup.ts, as the linter enforces per-file hygiene. Apply this guideline to all spec files (e.g., src/**/*.spec.tsx) to satisfy ESLint/Vitest requirements and prevent bleed-over between tests.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2025-12-27T11:22:41.191Z
Learnt from: rawadhossain
Repo: PalisadoesFoundation/talawa-admin PR: 5782
File: src/screens/Leaderboard/Leaderboard.spec.tsx:342-370
Timestamp: 2025-12-27T11:22:41.191Z
Learning: In test files that render screens with shared components (e.g., src/screens/Leaderboard/Leaderboard.spec.tsx), verify integration behavior by asserting the screen renders correctly in different scenarios (e.g., search results) without asserting the internal ARIA attributes, text, or icons of the shared component. Rely on the shared component's own tests to cover accessibility and presentation details. This keeps tests focused on higher-level behavior and interactions.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-06T21:27:50.880Z
Learnt from: Jashan32
Repo: PalisadoesFoundation/talawa-admin PR: 6222
File: src/utils/userUpdateUtils.ts:22-22
Timestamp: 2026-01-06T21:27:50.880Z
Learning: In the Talawa Admin codebase, the i18n extraction tool can misclassify TypeScript generic syntax (e.g., (obj: T): Partial) as translatable content. Suppress these false positives by adding a // i18n-ignore-next-line comment directly above the line with the type declaration or generic function signature. Apply this only to TS code where misclassification is confirmed; avoid blanket suppression.

Applied to files:

  • src/setup/setup.spec.ts
📚 Learning: 2026-01-07T14:21:19.711Z
Learnt from: cotishq
Repo: PalisadoesFoundation/talawa-admin PR: 6198
File: src/setup/setup.ts:123-124
Timestamp: 2026-01-07T14:21:19.711Z
Learning: Use TSDoc (eslint-plugin-tsdoc) instead of JSDoc. Do not wrap type names in curly braces in throws and returns. Write as "throws Error" and "returns Promise<void>" (no braces). Curly-brace usage causes tsdoc-malformed-inline-tag and tsdoc-escape-right-brace lint errors. Apply this rule to all TypeScript source files (e.g., src/**/*.ts) to ensure consistency.

Applied to files:

  • src/setup/setup.spec.ts
🧬 Code graph analysis (1)
src/setup/setup.spec.ts (1)
src/setup/setup.ts (3)
  • main (65-98)
  • askAndSetRecaptcha (13-49)
  • askAndSetLogErrors (52-62)
🔇 Additional comments (6)
src/setup/setup.spec.ts (6)

15-22: Well-defined interface for prompt typing.

Good addition of the PromptQuestion interface to properly type the inquirer prompt configuration, eliminating the need for as any assertions.


56-58: Improved test harness with proper isolation.

The process.exit mock now throws an error enabling cleaner rejects.toThrow() assertions. The afterEach block correctly includes both vi.clearAllMocks() and vi.resetAllMocks() per repository conventions for test isolation. Based on learnings, this satisfies the ESLint/Vitest requirements for per-file hygiene.

Also applies to: 69-75


77-291: Comprehensive main() function test coverage.

Excellent coverage including:

  • Success paths with both Docker=YES and Docker=NO configurations
  • Error handling for each setup step (backupEnvFile, modifyEnvFile, askAndUpdatePort, askAndUpdateTalawaApiUrl, askAndSetRecaptcha, askAndSetLogErrors)
  • Welcome and error message verification
  • Early return when env file check fails

This satisfies the PR objectives for proper exit-code error handling.


473-527: Good test coverage for askAndSetLogErrors.

Comprehensive tests covering:

  • Opt-in and opt-out behavior
  • Error propagation from inquirer
  • updateEnvFile error handling
  • Prompt configuration verification

This properly validates the newly exported askAndSetLogErrors function per PR objectives.


536-550: Improved side-effect verification test.

This test now properly verifies that the module doesn't auto-execute main() on import by:

  1. Clearing mock call history
  2. Asserting that setup functions (checkEnvFile, backupEnvFile, modifyEnvFile, askAndSetDockerOption) were not called
  3. Confirming exports are still available

This directly addresses the PR objective: "main() is only called when the script is executed directly, not on import."


582-595: Valuable edge case: case-sensitive Docker flag.

This test documents important behavior - the Docker flag comparison is case-sensitive ("YES" vs "yes"). The comment at line 592 clarifies the expected behavior. This is good defensive testing.

Signed-off-by: Yuvraj Kolkar <[email protected]>
@palisadoes
Copy link
Contributor

Please ensure:

  1. CodeRabbit approves your changes
  2. All tests pass and are valid
  3. All conflicting files are resolved

@yuvraj-kolkar17
Copy link
Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 8, 2026

@yuvraj-kolkar17: I'll review the changes in this PR for you.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@palisadoes
Copy link
Contributor

Please submit your PRs against our develop branch. The default is main, so you will have to modify this before submitting your PR for review. PRs made against main will be closed.

Also if applicable, make sure your branch name is different from develop when resubmitting.

Closing.

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.

SetupFix - Improve Testing Infrastructure & Module Structure

2 participants