diff --git a/src/index.js b/src/index.js index e554bba..4ac478d 100644 --- a/src/index.js +++ b/src/index.js @@ -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') } diff --git a/tests/api.js b/tests/api.js index c285309..93f9365 100644 --- a/tests/api.js +++ b/tests/api.js @@ -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()) } diff --git a/tests/test.js b/tests/test.js index efc24ac..5f0cea0 100644 --- a/tests/test.js +++ b/tests/test.js @@ -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', () => {