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(ClientRequest): support ClientRequest constructor #692

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/interceptors/ClientRequest/index.ts
Original file line number Diff line number Diff line change
@@ -31,6 +31,24 @@ export class ClientRequestInterceptor extends Interceptor<HttpRequestEventMap> {
const onRequest = this.onRequest.bind(this)
const onResponse = this.onResponse.bind(this)

http.ClientRequest = new Proxy(http.ClientRequest, {
construct: (target, args: Parameters<typeof http.request>) => {
const [url, options, callback] = normalizeClientRequestArgs(
'http:',
args
)

const mockAgent = new MockAgent({
customAgent: options.agent,
onRequest,
onResponse,
})
options.agent = mockAgent

return Reflect.construct(target, [url, options, callback])
},
})

http.request = new Proxy(http.request, {
apply: (target, thisArg, args: Parameters<typeof http.request>) => {
const [url, options, callback] = normalizeClientRequestArgs(
67 changes: 67 additions & 0 deletions test/modules/http/intercept/client-request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { vi, it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import http from 'http'
import { HttpServer } from '@open-draft/test-server/http'
import { ClientRequestInterceptor } from '../../../../src/interceptors/ClientRequest'
import { REQUEST_ID_REGEXP, waitForClientRequest } from '../../../helpers'
import { RequestController } from '../../../../src/RequestController'
import { HttpRequestEventMap } from '../../../../src/glossary'

const httpServer = new HttpServer((app) => {
app.get('/user', (req, res) => {
res.status(200).send('user-body')
})
})

const interceptor = new ClientRequestInterceptor()

beforeAll(async () => {
await httpServer.listen()
interceptor.apply()
})

afterEach(() => {
vi.resetAllMocks()
interceptor.removeAllListeners()
})

afterAll(async () => {
interceptor.dispose()
await httpServer.close()
})

it('intercepts a ClientRequest request with options', async () => {
const url = new URL(httpServer.http.url('/user?id=123'))
const requestListener = vi.fn<HttpRequestEventMap['request']>()
interceptor.on('request', requestListener)

// send options object instead of (url, options) as in other tests
// because the @types/node is incorrect and does not have the correct signature
const req = new http.ClientRequest({
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
headers: {
'x-custom-header': 'yes',
},
})
req.end()
const { text } = await waitForClientRequest(req)

expect(requestListener).toHaveBeenCalledTimes(1)

const [{ request, requestId, controller }] = requestListener.mock.calls[0]

expect(request.method).toBe('GET')
expect(request.url).toBe(url.toString())
expect(Object.fromEntries(request.headers.entries())).toMatchObject({
'x-custom-header': 'yes',
})
expect(request.credentials).toBe('same-origin')
expect(request.body).toBe(null)
expect(controller).toBeInstanceOf(RequestController)

expect(requestId).toMatch(REQUEST_ID_REGEXP)

// Must receive the original response.
expect(await text()).toBe('user-body')
})

Unchanged files with check annotations Beta

.timeout(1000)
.catch((error) => {
console.error(error)
expect.fail('Request must not error')

Check failure on line 58 in test/modules/http/regressions/http-post-missing-first-bytes.test.ts

GitHub Actions / build (18)

modules/http/regressions/http-post-missing-first-bytes.test.ts > does not skip first request bytes on passthrough POST request

AssertionError: Request must not error ❯ modules/http/regressions/http-post-missing-first-bytes.test.ts:58:14 ❯ modules/http/regressions/http-post-missing-first-bytes.test.ts:45:20
})
expect(response.status).toBe(200)