ember-cli-mirage
ember-cli-mirage copied to clipboard
Mirage-overridden fetch cannot download an image binary blob
Mirage has a bug when using the fetch
API to download an image Blob
.
Here is a repo that reproduces the problem: https://github.com/skarger/mirage-blob-fetch.
It's a simple Ember app that can be run with yarn start
.
The Mirage-overridden fetch
function seems to return a text version of the image's bytes, instead of the desired Blob
. Same problem if trying to access the image as an ArrayBuffer
.
The fetched data is corrupt, and also larger. I believe it's larger because the text representation of the image's bytes is UTF-8 encoded, and therefore each of its "characters" may expand in width from 1 byte to up to 4 bytes.
There are a few players in the mix:
-
Pretender
, which Mirage uses to mock thefetch
function. -
whatwg-fetch
, a polyfill forwindow.fetch
, which Pretender uses to overwrite the browser's nativefetch
function. -
I believe the bug only happens when using Mirage.
-
I've confirmed it does not happen when only using
whatwg-fetch
.
The example app's index route provides a demo that reproduces the problem.
Clicking the buttons will show the returned blob type and byte sizes when using
the native fetch
function and when using the Mirage-overridden fetch
.
You can see they are different. Clicking these buttons prompts console logging as well.
Demo app screenshot:
In order to make this demo, I used an Ember application initializer to capture
the native fetch
function as window.nativeFetch
. Otherwise I would have no way to access
native fetch
because Mirage / Pretender overrides it.
You know I think these issues might be related...
- https://github.com/miragejs/miragejs/issues/339
- https://github.com/miragejs/miragejs/issues/343
Haven't had time to dig yet but it's possible they all have the same root cause. Would be great to get to the bottom of it.
I tried to debug this problem a little bit because we are facing the following issue: https://github.com/miragejs/miragejs/issues/339
I think our issue involves even more "problems" but for the binary data problem I found out, that when I do the following in the fetch implementation of https://github.com/pretenderjs/pretender everything works fine 🙂
// inside fetch(input, init)
if (xhr.url.indexOf('.wasm') !== -1) {
xhr.responseType = 'arraybuffer';
}
The main problem I face is, that I do not know how to set the correct responseType
because in the fetch implementation I have no information about what responseType
to use 🤔 If I would know where to get this information from, I probably could create a PR
@skarger I found a workaround that works for us 🙂we use MirageJS without Ember-CLI but maybe it helps you to find a workaround for you as well. The details are here: https://github.com/miragejs/miragejs/issues/339#issuecomment-613334649
I think this is related to this bug in pretender
: https://github.com/pretenderjs/pretender/issues/305