Skip to content

Commit

Permalink
fix: jest bug when using MockScope.delay (nodejs#1340)
Browse files Browse the repository at this point in the history
  • Loading branch information
KhafraDev authored and crysmags committed Feb 27, 2024
1 parent 21d12b1 commit 3e94194
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
18 changes: 10 additions & 8 deletions lib/api/api-request.js
Expand Up @@ -88,14 +88,16 @@ class RequestHandler extends AsyncResource {
this.res = body
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)

this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
trailers: this.trailers,
opaque,
body,
context
})
if (callback !== null) {
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
trailers: this.trailers,
opaque,
body,
context
})
}
}

onData (chunk) {
Expand Down
32 changes: 32 additions & 0 deletions test/jest/mock-scope.test.js
@@ -0,0 +1,32 @@
const { MockAgent, setGlobalDispatcher, request } = require('../../index')

/* global afterAll, expect, it, AbortController */

const runIf = (condition) => condition ? it : it.skip

const nodeMajor = Number(process.versions.node.split('.', 1)[0])
const mockAgent = new MockAgent()

afterAll(async () => {
await mockAgent.close()
})

runIf(nodeMajor >= 16)('Jest works with MockScope.delay - issue #1327', async () => {
mockAgent.disableNetConnect()
setGlobalDispatcher(mockAgent)

const mockPool = mockAgent.get('http://localhost:3333')

mockPool.intercept({
path: '/jest-bugs',
method: 'GET'
}).reply(200, 'Hello').delay(100)

const ac = new AbortController()
setTimeout(() => ac.abort(), 5)
const promise = request('http://localhost:3333/jest-bugs', {
signal: ac.signal
})

await expect(promise).rejects.toThrowError('Request aborted')
}, 1000)

0 comments on commit 3e94194

Please sign in to comment.