Skip to content

Commit

Permalink
fix: Don't throw for 204 responses (#153)
Browse files Browse the repository at this point in the history
* fix: Don't throw for 204 responses

* chore: Add comment for 204 status
  • Loading branch information
usame-algan authored Feb 28, 2024
1 parent c08eb2e commit 66c90c0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ async function parseResponse<T>(resp: Response): Promise<T> {
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}`)
Expand Down
21 changes: 21 additions & 0 deletions tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
})
})
})
})

0 comments on commit 66c90c0

Please sign in to comment.