Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: jest bug when using MockScope.delay #1340

Merged
merged 3 commits into from Apr 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)