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
Show file tree
Hide file tree
Changes from 1 commit
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
Expand Up @@ -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(
Expand Down
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 resolver = vi.fn<HttpRequestEventMap['request']>()

const interceptor = new ClientRequestInterceptor()
interceptor.on('request', resolver)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually grew to dislike this pattern. Sorry it's still present in the test suite. It leads to a shared state in a shape of the resolver function, and that's really bad.

May I please ask you to add the request listener within the test instead? It will yield a much simpler setup. Thanks!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! like this?
image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think so!

And please add interceptor.removeAllListeners() to the afterEach() hook.


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

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

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'))

// 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(resolver).toHaveBeenCalledTimes(1)

const [{ request, requestId, controller }] = resolver.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')
})