Skip to content

Commit

Permalink
Add support for stringifiable objects (including URLs)
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew Simpson committed Mar 19, 2021
1 parent 908db5f commit 937b80d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ const normalizeRequest = (input, reqInit) => {
abort()
}
return new Request(input, reqInit)
} else if (typeof input.toString === 'function') {
if (reqInit && reqInit.signal && reqInit.signal.aborted) {
abort()
}
return new Request(input.toString(), reqInit)
} else {
throw new TypeError('Unable to parse input as string or Request')
}
Expand Down
7 changes: 7 additions & 0 deletions tests/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ async function APIRequest(who) {
return Promise.all([call1, call2])
} else if (who === 'twitter') {
return fetch('https://twitter.com').then((res) => res.json())
} else if (who === 'instagram') {
return fetch(new URL('https://instagram.com')).then((res) => res.json())
} else if (who === 'bing') {
const stringifier = {
toString: () => 'https://bing.com'
}
return fetch(stringifier).then((res) => res.json())
} else {
return fetch('https://google.com').then((res) => res.json())
}
Expand Down
24 changes: 24 additions & 0 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,30 @@ describe('testing mockResponse and alias once', () => {
)
expect(fetch.mock.calls[1][0]).toEqual('https://facebook.com')
})

it('supports URLs', async () => {
fetch.mockResponseOnce(
JSON.stringify({ secret_data: 'abcde' }, { status: 200 })
)

const response = await APIRequest('instagram')

expect(response).toEqual({ secret_data: 'abcde' })
expect(fetch.mock.calls.length).toEqual(1)
expect(fetch.mock.calls[0][0]).toEqual(new URL('https://instagram.com'))
});

it('supports an object with a stringifier', async () => {
fetch.mockResponseOnce(
JSON.stringify({ secret_data: 'abcde' }, { status: 200 })
)

const response = await APIRequest('instagram')

expect(response).toEqual({ secret_data: 'abcde' })
expect(fetch.mock.calls.length).toEqual(1)
expect(fetch.mock.calls[0][0]).toEqual(new URL('https://instagram.com'))
});
})

describe('testing mockResponses', () => {
Expand Down

0 comments on commit 937b80d

Please sign in to comment.