Skip to content

Commit a143911

Browse files
author
Michael Solomon
authored
fix(fetch): add support for aborting requests using AbortSignal (#2809)
1 parent 451e69c commit a143911

3 files changed

Lines changed: 17 additions & 2 deletions

File tree

lib/create_response.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ const responseStatusCodesWithoutBody = [204, 205, 304]
1616

1717
/**
1818
* @param {import('http').IncomingMessage} message
19+
* @param {AbortSignal} signal
1920
*/
20-
function createResponse(message) {
21+
function createResponse(message, signal) {
2122
const responseBodyOrNull = responseStatusCodesWithoutBody.includes(
2223
message.statusCode || 200,
2324
)
@@ -27,6 +28,7 @@ function createResponse(message) {
2728
message.on('data', chunk => controller.enqueue(chunk))
2829
message.on('end', () => controller.close())
2930
message.on('error', error => controller.error(error))
31+
signal.addEventListener('abort', () => message.destroy(signal.reason))
3032
},
3133
cancel() {
3234
message.destroy()

lib/intercept.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ function activate() {
399399
globalEmitter.emit('no match', nockRequest)
400400
} else {
401401
nockRequest.on('response', nockResponse => {
402-
const response = createResponse(nockResponse)
402+
const response = createResponse(nockResponse, mswRequest.signal)
403403
controller.respondWith(response)
404404
})
405405

tests/test_fetch.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@ describe('Native Fetch', () => {
119119
scope.done()
120120
})
121121

122+
it('should abort a request with a timeout signal', async () => {
123+
const scope = nock('http://test.com').get('/').delayBody(100).reply(200)
124+
125+
const response = await fetch('http://test.com', {
126+
signal: AbortSignal.timeout(50),
127+
})
128+
await assertRejects(
129+
response.text(),
130+
'TimeoutError: The operation was aborted due to timeout',
131+
)
132+
scope.done()
133+
})
134+
122135
// https://github.com/nock/nock/issues/2768
123136
it('should not mess the Headers object', async () => {
124137
nock('https://api.test.com', {

0 commit comments

Comments
 (0)