jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
886 stars 117 forks source link

Add blob() support. Use node-fetch directly instead of isomorphic-fetch #79

Closed drewler closed 5 years ago

drewler commented 6 years ago

As mentioned on #45 by @coremessage, using isomorphic-fetch implies using an old version of node-fetch which lacks blob().

As jest-fetch-mock is node-only, I think it's better to use node-fetch directly.

GrahamTheCoder commented 6 years ago

I do really need a fix for blob, but when I use node-fetch instead I have the problem that it doesn't support relative URLs (and doesn't make sense for it to do so): https://github.com/bitinn/node-fetch/issues/481 Not sure this is the right solution in the case of emulating a browser

jefflau commented 6 years ago

@GrahamTheCoder Do you have any suggestions for a better way to fix this?

GrahamTheCoder commented 6 years ago

Sadly, no. I don't know enough about the plethora of fetch-related packages to understand what the right solution is. In my case I don't actually need to assert against the blob, so I'm just polyfilling it in my global setup file like this:

const originalFetch = window.fetch;
window.fetch = (url, init) => {
    return originalFetch(url, init).then(result => {
        result.blob = () => Promise.resolve(new Blob());
        return result;
    });
};

If there's a good implementation of blob somewhere around it'd be easy enough to patch that in to what's here, or potentially switch totally to using the library that provides it.

EDIT: I have now slightly educated myself about said packages. It seems whatwg-fetch is the implementation that all the proxies (e.g. isomorphic-fetch, cross-fetch) basically delegate to for browser-stuff. Putting this in my setup file seems to fix this issue, so maybe that's the fix we should do here:

require("whatwg-fetch");

However, it may be that @drewler did effectively fix the issue for node-environments. In which case what we'd probably want is a proxy package like isomorphic-fetch. Worth doing a bit of googling but cross-fetch seems a plausible candidate.

GrahamTheCoder commented 6 years ago

OK I've opened PR https://github.com/jefflau/jest-fetch-mock/pull/80 for the same thing but using cross-fetch, which does work for my use case, and hopefully still will for @drewler

jefflau commented 5 years ago

I've merged @GrahamTheCoder's PR in so I'm closing this as we are using cross-fetch, not node-fetch