diff --git a/src/utils/handleRequest.ts b/src/utils/handleRequest.ts index 84316e0e..546f62ab 100644 --- a/src/utils/handleRequest.ts +++ b/src/utils/handleRequest.ts @@ -98,13 +98,17 @@ export async function handleRequest( * @note `signal` is not always defined in React Native. */ if (options.request.signal) { - options.request.signal.addEventListener( - 'abort', - () => { - requestAbortPromise.reject(options.request.signal.reason) - }, - { once: true } - ) + if (options.request.signal.aborted) { + requestAbortPromise.reject(options.request.signal.reason) + } else { + options.request.signal.addEventListener( + 'abort', + () => { + requestAbortPromise.reject(options.request.signal.reason) + }, + { once: true } + ) + } } const result = await until(async () => { diff --git a/test/modules/fetch/compliance/abort-conrtoller.test.ts b/test/modules/fetch/compliance/abort-conrtoller.test.ts index ebf9b87d..54fa0c21 100644 --- a/test/modules/fetch/compliance/abort-conrtoller.test.ts +++ b/test/modules/fetch/compliance/abort-conrtoller.test.ts @@ -124,3 +124,23 @@ it('forwards custom abort reason to the request if pending', async () => { expect(abortError.name).toBe('Error') expect(abortError.message).toEqual('Custom abort reason') }) + +it('respects requests aborted before they are dispatched', async () => { + interceptor.on('request', ({ controller }) => { + controller.respondWith(new Response('hello world')) + }) + + const controller = new AbortController() + const request = new Request(httpServer.http.url('/'), { + signal: controller.signal, + }) + controller.abort() + + const abortError = await fetch(request).then( + () => expect.fail('must not return any response'), + (error) => error + ) + + expect(abortError.name).toBe('AbortError') + expect(abortError.message).toBe('This operation was aborted') +})