diff --git a/src/utils.ts b/src/utils.ts index 111029e2..6c4696b6 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -41,7 +41,8 @@ async function parseResponse(resp: Response): Promise { let json try { - json = await resp.json() + // An HTTP 204 - No Content response doesn't contain a body so trying to call .json() on it would throw + json = resp.status === 204 ? {} : await resp.json() } catch { if (resp.headers && resp.headers.get('content-length') !== '0') { throw new Error(`Invalid response content: ${resp.statusText}`) diff --git a/tests/utils.test.ts b/tests/utils.test.ts index 81488689..9984db35 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -197,5 +197,26 @@ describe('utils', () => { }, }) }) + + it('should not throw for a 204 response', async () => { + const jsonMock = jest.fn() + fetchMock.mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 204, + json: jsonMock, + }) + }) + + await expect(fetchData('/test/safe', 'DELETE')).resolves.toEqual({}) + expect(jsonMock).not.toHaveBeenCalled() + + expect(fetch).toHaveBeenCalledWith('/test/safe', { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + }, + }) + }) }) })