Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment here? I personally didn't know what 204 means and had to look it up.

} 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',
},
})
})
})
})