Skip to content

fix(tests): guard jest globalSetup against non-test NODE_ENV (#3476)#3488

Merged
PierreBrisorgueil merged 2 commits intomasterfrom
fix/jest-globalsetup-guard-3476-v2
Apr 23, 2026
Merged

fix(tests): guard jest globalSetup against non-test NODE_ENV (#3476)#3488
PierreBrisorgueil merged 2 commits intomasterfrom
fix/jest-globalsetup-guard-3476-v2

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Apr 23, 2026

Summary

  • Hard-guard scripts/jest.globalSetup.js so dropDatabase() is never called when NODE_ENV !== 'test' or when the resolved DB name does not match /test/i.
  • Add 5 unit tests covering the two guards + the happy path + Mongo unreachable.
  • Extend jest.config.js testMatch to include scripts/tests/**/*.js.

Why

Downstream projects (ism_node, trawl_node, comes_node, montaine_node) export NODE_ENV=<project> in the developer shell so their config resolves to the project DB. Running jest directly (npx jest, IDE runner, editor extension) bypasses the cross-env NODE_ENV=test wrapper and the previous globalSetup happily dropped that project DB.

Real incident (2026-04-20, ism_node): NODE_ENV=ism npx jest modules/appointments --silent wiped 16 collections in 22 ms. No replica set / oplog / dump available, unrecoverable.

Behaviour

NODE_ENV DB name Outcome
test NodeTest drop (unchanged)
test Production refuse + warn (belt-and-suspenders)
ism any refuse + warn
undefined any refuse + warn

Test plan

  • NODE_ENV=test npm run test:unit — 44 suites / 513 tests passing
  • NODE_ENV=ism node -e "..." — logs refusal, no drop
  • npm run lint — clean
  • New unit test file scripts/tests/jest.globalSetup.unit.tests.js — 5 tests passing

Closes #3476

Summary by CodeRabbit

  • Tests

    • Expanded Jest configuration to include test files from additional directory paths.
    • Added comprehensive test coverage for database cleanup safety validation.
  • Bug Fixes

    • Implemented safety checks to prevent accidental database cleanup when running outside test environments or with non-test database names.

Downstream projects (ism_node, trawl_node, comes_node, montaine_node)
export `NODE_ENV=<project>` in their shell to pick up their config.
Running jest directly (`npx jest`, IDE runner) bypasses the
`cross-env NODE_ENV=test` wrapper used by the npm `test*` scripts, and
`scripts/jest.globalSetup.js` unconditionally called `dropDatabase()`
against `config.db.uri` resolved from that env.

Real incident (2026-04-20, ism_node): `NODE_ENV=ism npx jest ...` wiped
16 collections in 22ms with no confirmation.

Guards added in globalSetup (defense-in-depth):
1. Refuse to drop when `NODE_ENV !== 'test'`, log clear refusal.
2. Refuse to drop when the resolved DB name does not match `/test/i`,
   catching cases where `config.db.uri` is overridden to a non-test DB.

Both checks exit without connecting; tests run against existing state.

Tests: 5 new unit tests cover project-env leak, undefined NODE_ENV,
non-test DB name, happy path, and Mongo-unreachable fallback. Added
`scripts/tests/**` to `testMatch` so this path is picked up.

Fixes #3476
Copilot AI review requested due to automatic review settings April 23, 2026 07:23
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 41 minutes and 55 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 41 minutes and 55 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 08f06ae8-acb7-40fd-bd0e-f4e87d3ecd33

📥 Commits

Reviewing files that changed from the base of the PR and between 1779469 and be3883e.

📒 Files selected for processing (2)
  • scripts/jest.globalSetup.js
  • scripts/tests/jest.globalSetup.unit.tests.js

Walkthrough

Jest configuration updated to discover tests in scripts/tests/**. Safety guards added to jest.globalSetup.js to refuse database drops when NODE_ENV is not "test" or database name does not match /test/i. Comprehensive test suite validates these guards across multiple scenarios.

Changes

Cohort / File(s) Summary
Configuration
jest.config.js
Added scripts/tests/** to testMatch glob pattern for test discovery; reformatted to multi-line array.
Database Safety Guards
scripts/jest.globalSetup.js
Added pre-connection checks: refuses to drop database if NODE_ENV is not "test", or if database name (extracted from URI) does not match /test/i pattern; logs warnings and returns early in both cases.
Guard Validation Tests
scripts/tests/jest.globalSetup.unit.tests.js
New unit test suite with 5 test cases covering: wrong/undefined NODE_ENV, mismatched database name, correct setup, and MongoDB unreachable scenarios; mocks mongoose and stubs config to verify guard behavior and warning messages.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • pierreb-devkit/Node#3324: Ensures NODE_ENV=test is passed during Docker test builds, complementing the runtime guards that verify NODE_ENV === "test" before database operations.

Suggested labels

Fix

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly summarizes the main change: adding guards to jest globalSetup against non-test NODE_ENV, which is the primary objective of the PR.
Description check ✅ Passed Description provides summary, rationale (real incident), behaviour table, test plan with validation, and references linked issue #3476, covering most template sections appropriately.
Linked Issues check ✅ Passed PR fully implements issue #3476 objectives: hard guards prevent dropping when NODE_ENV !== 'test' or DB name doesn't match /test/i [#3476], unit tests cover guards plus happy path and Mongo fallback [#3476], testMatch extended for CI [#3476].
Out of Scope Changes check ✅ Passed All three file changes (jest.config.js, jest.globalSetup.js, new test file) directly support the stated objective of guarding globalSetup against non-test NODE_ENV with comprehensive testing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/jest-globalsetup-guard-3476-v2

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 23, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.85%. Comparing base (f4ba797) to head (be3883e).
⚠️ Report is 11 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #3488   +/-   ##
=======================================
  Coverage   85.85%   85.85%           
=======================================
  Files         115      115           
  Lines        2919     2919           
  Branches      809      809           
=======================================
  Hits         2506     2506           
  Misses        327      327           
  Partials       86       86           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds defense-in-depth to Jest’s globalSetup to prevent accidental database drops when Jest is run outside of the intended test environment, and adds unit coverage for the new safety checks.

Changes:

  • Add hard guards in scripts/jest.globalSetup.js to refuse dropDatabase() unless NODE_ENV === 'test' and the resolved DB name matches /test/i.
  • Add unit tests covering guard behavior and the happy path for jest.globalSetup.
  • Extend jest.config.js testMatch to include scripts/tests/**/*.js.

Reviewed changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 2 comments.

File Description
scripts/jest.globalSetup.js Adds environment + DB-name guards before connecting/dropping the database.
scripts/tests/jest.globalSetup.unit.tests.js Adds unit tests for the new globalSetup safety behavior.
jest.config.js Includes scripts/tests/** in Jest test discovery so the new tests run.

Comment thread scripts/tests/jest.globalSetup.unit.tests.js Outdated
Comment thread scripts/jest.globalSetup.js
Copy link
Copy Markdown

@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

Caution

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

⚠️ Outside diff range comments (1)
scripts/jest.globalSetup.js (1)

35-40: ⚠️ Potential issue | 🟠 Major

Disconnect even when dropDatabase() fails.

If mongoose.connect() succeeds but dropDatabase() rejects, the catch swallows the error and skips mongoose.disconnect(), which can leave an open Mongo handle during test startup.

Proposed cleanup fix
-    await mongoose.connect(config.db.uri);
-    await mongoose.connection.dropDatabase();
-    await mongoose.disconnect();
+    await mongoose.connect(config.db.uri);
+    try {
+      await mongoose.connection.dropDatabase();
+    } finally {
+      await mongoose.disconnect();
+    }
   } catch {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/jest.globalSetup.js` around lines 35 - 40, The current try/catch
swallows errors from mongoose.connection.dropDatabase() and skips
mongoose.disconnect(), leaving an open connection; modify the block so that
mongoose.disconnect() is always called (use a finally or separate try/catch)
after mongoose.connect() and dropDatabase(), and log or rethrow the dropDatabase
error as appropriate; reference mongoose.connect,
mongoose.connection.dropDatabase, and mongoose.disconnect so the disconnect call
is executed in all code paths even when dropDatabase() rejects.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@scripts/jest.globalSetup.js`:
- Line 19: Add a JSDoc header immediately above the exported async function
signature "export default async () => {" that provides a one-line description
and an `@returns` tag; since this is an async setup function with no params,
include a line like "@returns {Promise<void>} Description of what the setup
returns" (or similar) to satisfy the rule that async functions always document
`@returns` and ensure no `@param` is required.

In `@scripts/tests/jest.globalSetup.unit.tests.js`:
- Around line 34-38: The afterEach teardown currently restores NODE_ENV by
assigning process.env.NODE_ENV = originalNodeEnv which will set the string
"undefined" if originalNodeEnv was absent; change the logic in the afterEach
block (where warnSpy.mockRestore(), process.env.NODE_ENV = originalNodeEnv,
jest.resetModules() live) to conditionally delete process.env.NODE_ENV when
originalNodeEnv is undefined and only assign when it has a real value so the
environment is correctly restored.

---

Outside diff comments:
In `@scripts/jest.globalSetup.js`:
- Around line 35-40: The current try/catch swallows errors from
mongoose.connection.dropDatabase() and skips mongoose.disconnect(), leaving an
open connection; modify the block so that mongoose.disconnect() is always called
(use a finally or separate try/catch) after mongoose.connect() and
dropDatabase(), and log or rethrow the dropDatabase error as appropriate;
reference mongoose.connect, mongoose.connection.dropDatabase, and
mongoose.disconnect so the disconnect call is executed in all code paths even
when dropDatabase() rejects.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3b6e58f0-6d64-49f9-8fd6-f055aea04b68

📥 Commits

Reviewing files that changed from the base of the PR and between f8542e3 and 1779469.

📒 Files selected for processing (3)
  • jest.config.js
  • scripts/jest.globalSetup.js
  • scripts/tests/jest.globalSetup.unit.tests.js

Comment thread scripts/jest.globalSetup.js
Comment thread scripts/tests/jest.globalSetup.unit.tests.js
- scripts/jest.globalSetup.js: add JSDoc @returns on the default export;
  wrap dropDatabase in try/finally so mongoose.disconnect() runs even
  when the drop rejects (no dangling connection).
- scripts/tests/jest.globalSetup.unit.tests.js: afterEach now deletes
  NODE_ENV when the original was undefined (process.env coerces to the
  literal string "undefined" otherwise); add a 6th test covering the
  disconnect-on-drop-failure path.
@PierreBrisorgueil
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

✅ 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.

Copy link
Copy Markdown

@codacy-production codacy-production Bot left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

The PR currently contains no code changes or new tests, which directly contradicts the stated intent of implementing database guards and adding at least five unit tests. This is a critical blocker as the core safety logic for scripts/jest.globalSetup.js and the verification tests are missing from the submission. While Codacy indicates the PR is up to standards, this is likely an artifact of an empty diff rather than a successful implementation.

About this PR

  • The PR body describes several critical security guards and unit tests, but the submitted diff is empty. The implementation of environment guards (NODE_ENV === 'test'), database name pattern matching, and the required unit tests in scripts/tests/ must be included for review.

Test suggestions

  • Successful database drop when NODE_ENV is 'test' and DB name contains 'test'
  • Refusal to drop when NODE_ENV is 'test' but DB name is a production-like name
  • Refusal to drop when NODE_ENV is set to a project-specific value (e.g., 'ism')
  • Refusal to drop when NODE_ENV is undefined
  • Graceful handling of unreachable MongoDB during global setup
Prompt proposal for missing tests
Consider implementing these tests if applicable:
1. Successful database drop when NODE_ENV is 'test' and DB name contains 'test'
2. Refusal to drop when NODE_ENV is 'test' but DB name is a production-like name
3. Refusal to drop when NODE_ENV is set to a project-specific value (e.g., 'ism')
4. Refusal to drop when NODE_ENV is undefined
5. Graceful handling of unreachable MongoDB during global setup

🗒️ Improve review quality by adding custom instructions

@codacy-production
Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes. Give us feedback

@PierreBrisorgueil PierreBrisorgueil merged commit 93f23e0 into master Apr 23, 2026
6 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/jest-globalsetup-guard-3476-v2 branch April 23, 2026 11:41
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.

fix(tests): jest globalSetup drops whatever DB NODE_ENV resolves — needs hard guard against non-test envs

2 participants