Skip to content

Commit

Permalink
lib: refactor lazy loading of undici for fetch method
Browse files Browse the repository at this point in the history
Object.defineProperty is updated to lazily load the undici dependency
for the fetch method. This change allows for simpler and more reliable
mocking of the fetch method for testing purposes, resolving issues
encountered with premature method invocation during testing.

Fixes: #52015
  • Loading branch information
YCChenVictor committed Apr 7, 2024
1 parent 61e5de1 commit 3fdd4d3
Showing 1 changed file with 13 additions and 26 deletions.
39 changes: 13 additions & 26 deletions lib/internal/bootstrap/web/exposed-window-or-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,32 +57,19 @@ defineReplaceableLazyAttribute(globalThis, 'perf_hooks', ['performance']);
const { installObjectURLMethods } = require('internal/url');
installObjectURLMethods();

{
// https://fetch.spec.whatwg.org/#fetch-method
function set(value) {
ObjectDefineProperty(globalThis, 'fetch', {
__proto__: null,
writable: true,
value,
});
}
ObjectDefineProperty(globalThis, 'fetch', {
__proto__: null,
configurable: true,
enumerable: true,
set,
get() {
function fetch(input, init = undefined) {
// Loading undici alone lead to promises which breaks lots of tests so we
// have to load it really lazily for now.
const { fetch: impl } = require('internal/deps/undici/undici');
return impl(input, init);
}
set(fetch);
return fetch;
},
});
}
// https://fetch.spec.whatwg.org/#fetch-method
ObjectDefineProperty(globalThis, 'fetch', {
__proto__: null,
configurable: true,
enumerable: true,
writable: true,
value: function fetch(input, init = undefined) { // eslint-disable-line func-name-matching
// Loading undici alone lead to promises which breaks lots of tests so we
// have to load it really lazily for now.
const { fetch: impl } = require('internal/deps/undici/undici');
return impl(input, init);
},
});

// https://xhr.spec.whatwg.org/#interface-formdata
// https://fetch.spec.whatwg.org/#headers-class
Expand Down

0 comments on commit 3fdd4d3

Please sign in to comment.