jameslnewell / xhr-mock

Utility for mocking XMLHttpRequest.
196 stars 48 forks source link

Responsetype "arraybuffer" not implemented correctly #104

Open gflohr opened 4 years ago

gflohr commented 4 years ago

In my (jest) test I mock XHR like this:

mock.get('/assets/locale/de/LC_MESSAGES/http.json', {
    status: 200,
    body: 'some string',
});

I use XMLHTTPRequest in my code in like this:

loadFile(url: string): Promise<ArrayBuffer> {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'arraybuffer';
        xhr.open('GET', url, true);
        xhr.onload = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                resolve(xhr.response);
            } else {
                reject(new Error('get failed with status ' + xhr.status));
            }
        };
        xhr.onerror = (err) => reject(err);
        xhr.send();
    });
}

In the browser, the response data is in xhr.response (not xhr.responseType!)) as an ArrayBuffer, and accessing xhr.responseText throws an exception. In the mock, the data is a string in xhr.responseText but xhr.response is null.

This looks like a bug to me, see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Handling_binary_data. Any chance to fix this?