Skip to content

Comments

fix(fetch): use current global fetch instead of cached one when env f…#2

Open
MitchLewis930 wants to merge 1 commit intopr_022_beforefrom
pr_022_after
Open

fix(fetch): use current global fetch instead of cached one when env f…#2
MitchLewis930 wants to merge 1 commit intopr_022_beforefrom
pr_022_after

Conversation

@MitchLewis930
Copy link

@MitchLewis930 MitchLewis930 commented Jan 29, 2026

PR_022

Summary by CodeRabbit

  • Refactor

    • Improved fetch adapter initialization and environment configuration handling with enhanced fallback mechanisms to ensure compatibility across different scenarios
  • Tests

    • Added comprehensive test coverage validating fetch adapter correctly falls back to the global fetch implementation when custom configuration is not provided

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

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2026

📝 Walkthrough

Walkthrough

The fetch adapter is refactored to implement environment-based fetch resolution with fallback support. Environment configuration now prefers an explicit envFetch while defaulting to an empty object when no env is provided. The adapter uses a merged environment to select the appropriate fetch implementation, supporting cases where fetch is unavailable or overridden.

Changes

Cohort / File(s) Summary
Fetch Adapter Implementation
lib/adapters/fetch.js
Introduces environment merging for fetch globals; replaces direct fetch invocations with a computed _fetch reference that prioritizes envFetch; adds fallback to global fetch; changes env initialization to default to empty object instead of merged global API.
Fetch Adapter Test
test/unit/adapters/fetch.js
Adds test case verifying fallback behavior when env.fetch is undefined; confirms adapter uses global fetch implementation as expected fallback.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A fetch so clever, both local and wide,
With envFetch first, the globals will hide,
When env runs empty, a fallback so grand,
Global fetch steps in to lend a helpful hand! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: using the current global fetch instead of a cached one when env fetch is not specified, which aligns with the PR's primary objective of maintaining MSW support.
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 docstrings

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

@MitchLewis930
Copy link
Author

@CodeRabbit full review

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2026

✅ Actions performed

Full review triggered.

Copy link

@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

🤖 Fix all issues with AI agents
In `@lib/adapters/fetch.js`:
- Around line 265-266: The destructuring of {fetch, Request, Response} assumes
env is an object but env can be undefined when config.env is missing; update the
assignment that creates env (used by the fetch adapter) to default to an empty
object (e.g., env = (config && config.env) || {}) so the subsequent destructure
in lib/adapters/fetch.js cannot throw; change the code referencing env (the
variables fetch, Request, Response) used by getFetch to always read from a
guaranteed object.

In `@test/unit/adapters/fetch.js`:
- Around line 493-517: The test currently reassigns the global fetch variable
(using variable globalFetch and direct fetch = ...) which triggers
noGlobalAssign; change to capture and restore globalThis.fetch instead: store
the original as const originalFetch = globalThis.fetch, replace with
globalThis.fetch = async () => {...} before calling startHTTPServer and
fetchAxios.get, and in the finally block restore globalThis.fetch =
originalFetch; keep the rest of the test logic (env: { fetch: undefined },
assertions, and use of startHTTPServer and fetchAxios.get) unchanged.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c26d00f and cf78825.

📒 Files selected for processing (2)
  • lib/adapters/fetch.js
  • test/unit/adapters/fetch.js
🧰 Additional context used
🧬 Code graph analysis (2)
lib/adapters/fetch.js (1)
lib/utils.js (1)
  • isFunction (95-95)
test/unit/adapters/fetch.js (1)
test/helpers/server.js (2)
  • startHTTPServer (14-53)
  • startHTTPServer (14-53)
🪛 Biome (2.3.13)
test/unit/adapters/fetch.js

[error] 496-496: A global variable should not be reassigned.

Assigning to a global variable can override essential functionality.

(lint/suspicious/noGlobalAssign)


[error] 516-516: A global variable should not be reassigned.

Assigning to a global variable can override essential functionality.

(lint/suspicious/noGlobalAssign)

🔇 Additional comments (2)
lib/adapters/fetch.js (2)

15-38: LGTM.
The adapter setup and env merge flow look coherent.


141-142: LGTM — consistent resolved transport usage.

Also applies to: 202-202

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines +265 to 266
let env = config ? config.env : {};
const {fetch, Request, Response} = env;
Copy link

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:

git ls-files lib/adapters/fetch.js

Repository: Signal65/axios-CodeRabbit

Length of output: 90


🏁 Script executed:

head -n 300 lib/adapters/fetch.js | tail -n 50

Repository: Signal65/axios-CodeRabbit

Length of output: 1138


🏁 Script executed:

rg -n -C2 '\bgetFetch\s*\('

Repository: Signal65/axios-CodeRabbit

Length of output: 255


🏁 Script executed:

rg -n 'getFetch' --type js

Repository: Signal65/axios-CodeRabbit

Length of output: 246


🏁 Script executed:

rg -n 'getFetch\s*\(' --type js -A 5

Repository: Signal65/axios-CodeRabbit

Length of output: 199


🏁 Script executed:

cat lib/adapters/adapters.js

Repository: Signal65/axios-CodeRabbit

Length of output: 2142


Guard against config.env being undefined.

When getFetch is called with a config object (line 60-61 in lib/adapters/adapters.js), the current code at line 265 can set env to undefined if config.env is missing or falsy. This causes line 266 destructuring to throw a TypeError. The suggested fix ensures env always defaults to an object:

✅ Safer defaulting
-  let env = config ? config.env : {};
+  let env = (config && config.env) || {};
🤖 Prompt for AI Agents
In `@lib/adapters/fetch.js` around lines 265 - 266, The destructuring of {fetch,
Request, Response} assumes env is an object but env can be undefined when
config.env is missing; update the assignment that creates env (used by the fetch
adapter) to default to an empty object (e.g., env = (config && config.env) ||
{}) so the subsequent destructure in lib/adapters/fetch.js cannot throw; change
the code referencing env (the variables fetch, Request, Response) used by
getFetch to always read from a guaranteed object.

Comment on lines +493 to +517
it('should use current global fetch when env fetch is not specified', async() => {
const globalFetch = fetch;

fetch = async () => {
return {
headers: {
foo: '1'
},
text: async () => 'global'
}
};

try {
server = await startHTTPServer((req, res) => res.end('OK'));

const {data} = await fetchAxios.get('/', {
env: {
fetch: undefined
}
});

assert.strictEqual(data, 'global');
} finally {
fetch = globalFetch;
}
Copy link

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:

# First, let's examine the exact file and lines in question
wc -l test/unit/adapters/fetch.js

Repository: Signal65/axios-CodeRabbit

Length of output: 100


🏁 Script executed:

# Read the specific lines mentioned in the review (493-517)
sed -n '493,517p' test/unit/adapters/fetch.js

Repository: Signal65/axios-CodeRabbit

Length of output: 649


🏁 Script executed:

# Search for other global fetch stubs that might need the same treatment
rg -n -C2 '\bfetch\s*=' test/unit --max-count 20

Repository: Signal65/axios-CodeRabbit

Length of output: 598


🏁 Script executed:

# Check if there's a eslint/biome configuration file to confirm the noGlobalAssign rule
fd -e .biomerc -e biome.json -e .eslintrc -e .eslintignore 2>/dev/null | head -5

Repository: Signal65/axios-CodeRabbit

Length of output: 51


🏁 Script executed:

# Check for biome or eslint config in the root directory
ls -la | grep -E '(biome|eslint)'

Repository: Signal65/axios-CodeRabbit

Length of output: 199


🏁 Script executed:

# Check if biome is configured in package.json
cat package.json | grep -A10 -B2 'biome'

Repository: Signal65/axios-CodeRabbit

Length of output: 51


🏁 Script executed:

# Search the entire codebase for other uses of globalThis.fetch
rg 'globalThis\.fetch' --max-count 10

Repository: Signal65/axios-CodeRabbit

Length of output: 51


🏁 Script executed:

# Check if there are any other test files using globalThis for stubbing
rg 'globalThis\s*\.' test/ --max-count 15

Repository: Signal65/axios-CodeRabbit

Length of output: 51


🏁 Script executed:

# Read the biome.json file to check noGlobalAssign configuration
cat biome.json

Repository: Signal65/axios-CodeRabbit

Length of output: 1844


🏁 Script executed:

# Also check the .eslintrc.cjs file
cat .eslintrc.cjs

Repository: Signal65/axios-CodeRabbit

Length of output: 317


🏁 Script executed:

# Final verification: check if there are any other fetch reassignments in the entire test directory
rg 'fetch\s*=' test/ --type js -B2 -A2

Repository: Signal65/axios-CodeRabbit

Length of output: 558


Use globalThis.fetch instead of direct global assignment to avoid noGlobalAssign lint violation.
Biome and ESLint both flag direct fetch reassignment as noGlobalAssign. Using globalThis.fetch at lines 496 and 516 resolves the lint error and keeps the global override explicit and testable.

🛠️ Suggested fix
-      const globalFetch = fetch;
-
-      fetch = async () => {
+      const globalFetch = globalThis.fetch;
+
+      globalThis.fetch = async () => {
         return {
           headers: {
             foo: '1'
           },
           text: async () => 'global'
         }
       };
@@
-        fetch = globalFetch;
+        globalThis.fetch = globalFetch;
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('should use current global fetch when env fetch is not specified', async() => {
const globalFetch = fetch;
fetch = async () => {
return {
headers: {
foo: '1'
},
text: async () => 'global'
}
};
try {
server = await startHTTPServer((req, res) => res.end('OK'));
const {data} = await fetchAxios.get('/', {
env: {
fetch: undefined
}
});
assert.strictEqual(data, 'global');
} finally {
fetch = globalFetch;
}
it('should use current global fetch when env fetch is not specified', async() => {
const globalFetch = globalThis.fetch;
globalThis.fetch = async () => {
return {
headers: {
foo: '1'
},
text: async () => 'global'
}
};
try {
server = await startHTTPServer((req, res) => res.end('OK'));
const {data} = await fetchAxios.get('/', {
env: {
fetch: undefined
}
});
assert.strictEqual(data, 'global');
} finally {
globalThis.fetch = globalFetch;
}
🧰 Tools
🪛 Biome (2.3.13)

[error] 496-496: A global variable should not be reassigned.

Assigning to a global variable can override essential functionality.

(lint/suspicious/noGlobalAssign)


[error] 516-516: A global variable should not be reassigned.

Assigning to a global variable can override essential functionality.

(lint/suspicious/noGlobalAssign)

🤖 Prompt for AI Agents
In `@test/unit/adapters/fetch.js` around lines 493 - 517, The test currently
reassigns the global fetch variable (using variable globalFetch and direct fetch
= ...) which triggers noGlobalAssign; change to capture and restore
globalThis.fetch instead: store the original as const originalFetch =
globalThis.fetch, replace with globalThis.fetch = async () => {...} before
calling startHTTPServer and fetchAxios.get, and in the finally block restore
globalThis.fetch = originalFetch; keep the rest of the test logic (env: { fetch:
undefined }, assertions, and use of startHTTPServer and fetchAxios.get)
unchanged.

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