diff --git a/src/index.mjs b/src/index.mjs index d4beeec..e6f953d 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -11,8 +11,10 @@ export default function(url, options) { request.withCredentials = options.credentials=='include'; - request.onload = () => { - resolve(response()); + request.onreadystatechange = function() { + if(this.readyState === 4 && this.status !== 0) { + resolve(response()); + } }; request.onerror = reject; diff --git a/test/index.js b/test/index.js index 3a9e598..92f85b3 100644 --- a/test/index.js +++ b/test/index.js @@ -20,6 +20,7 @@ describe('unfetch', () => { getAllResponseHeaders: jest.fn().mockReturnValue('X-Foo: bar\nX-Foo:baz'), open: jest.fn(), send: jest.fn(), + readyState: 4, status: 200, statusText: 'OK', responseText: '{"a":"b"}', @@ -60,10 +61,10 @@ describe('unfetch', () => { expect(xhr.send).toHaveBeenCalledWith(null); }); - expect(xhr.onload).toEqual(expect.any(Function)); + expect(xhr.onreadystatechange).toEqual(expect.any(Function)); expect(xhr.onerror).toEqual(expect.any(Function)); - xhr.onload(); + xhr.onreadystatechange(); return p; }); @@ -76,7 +77,7 @@ describe('unfetch', () => { expect(r.headers.get('X-foo')).toEqual('baz'); }); - xhr.onload(); + xhr.onreadystatechange(); return p; });