Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch native fetch on Safari to fix #584 #585

Merged
merged 1 commit into from
Aug 1, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 45 additions & 1 deletion src/lib/fetch-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,50 @@ class AbortError extends Error {
}
}

// Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari.
// See also https://github.com/wheresrhys/fetch-mock/issues/584
// See also https://stackoverflow.com/a/50952018/1273406
const patchNativeFetchForSafari = (nativeFetch) => {
// Try to patch fetch only on Safari
if (
!navigator ||
!navigator.vendor ||
navigator.vendor !== 'Apple Computer, Inc.'
) {
return nativeFetch;
}
// It seems the code is working on Safari thus patch native fetch to avoid the error.
return async (request) => {
const { method } = request;
if (!['POST', 'PUT', 'PATCH'].includes(method)) {
// No patch is required in this case
return nativeFetch(request);
}
const body = await request.clone().text();
const {
cache,
credentials,
headers,
integrity,
mode,
redirect,
referrer,
} = request;
const init = {
body,
cache,
credentials,
headers,
integrity,
mode,
redirect,
referrer,
method,
};
return nativeFetch(request.url, init);
};
};

const resolve = async (
{ response, responseIsFetch = false },
url,
Expand Down Expand Up @@ -252,7 +296,7 @@ FetchMock.getNativeFetch = function () {
'fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'
);
}
return func;
return patchNativeFetchForSafari(func);
};

FetchMock.recordCall = function (obj) {
Expand Down