diff --git a/src/FetchTool.js b/src/FetchTool.js index ccb5ae21..7ac5b075 100644 --- a/src/FetchTool.js +++ b/src/FetchTool.js @@ -20,7 +20,10 @@ class FetchTool { */ get ({url, ...options}) { return fetch(url, Object.assign({method: 'GET'}, options)) - .then(result => result.arrayBuffer()) + .then(result => { + if (result.ok) return result.arrayBuffer(); + return Promise.reject(result.status); + }) .then(body => new Uint8Array(body)); } diff --git a/test/unit/fetch-tool.js b/test/unit/fetch-tool.js index 2f23d025..a325cfdc 100644 --- a/test/unit/fetch-tool.js +++ b/test/unit/fetch-tool.js @@ -1,4 +1,6 @@ const test = require('tap').test; +const TextEncoder = require('util').TextEncoder; +const TextDecoder = require('util').TextDecoder; const FetchTool = require('../../src/FetchTool'); @@ -27,3 +29,34 @@ test('send failure returns response.status', t => { t.equal(reason, 500); }); }); + +test('get success returns Uint8Array.body(response.arrayBuffer())', t => { + const text = 'successful response'; + const encoding = 'utf-8'; + const encoded = new TextEncoder().encode(text); + const decoder = new TextDecoder(encoding); + + global.fetch = () => Promise.resolve({ + ok: true, + arrayBuffer: () => encoded.buffer + }); + + const tool = new FetchTool(); + + return tool.get({url: 'url'}).then(result => { + t.equal(decoder.decode(result), text); + }); +}); + +test('get failure returns response.status', t => { + global.fetch = () => Promise.resolve({ + ok: false, + status: 500 + }); + + const tool = new FetchTool(); + + return tool.get({url: 'url'}).catch(reason => { + t.equal(reason, 500); + }); +});