Skip to content

Commit

Permalink
fix: support already aborted requests (#673)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Nov 6, 2024
1 parent 4da432f commit 20e9ce4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/utils/handleRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
20 changes: 20 additions & 0 deletions test/modules/fetch/compliance/abort-conrtoller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Error>(
() => expect.fail('must not return any response'),
(error) => error
)

expect(abortError.name).toBe('AbortError')
expect(abortError.message).toBe('This operation was aborted')
})

0 comments on commit 20e9ce4

Please sign in to comment.