From 44e68b14c39ee9e25e990c90510d3bab92ac2217 Mon Sep 17 00:00:00 2001 From: Arthur Taylor Date: Tue, 12 Aug 2025 11:30:06 +0200 Subject: [PATCH] feat(client): add proxy object for `request.agent` for compatibility In node environments, the code in `node/agent.js` creates a proxy object around `Agent` so that it can be instantiated without using the `new` keyword. The equivalent code for the browser version (in `client.js`) defines `request.agent` as `() => new Agent()`. In supertest, the `TestAgent` attempts to subclass `Agent` with the call `Object.setPrototypeOf(TestAgent.prototype, Agent.prototype);`. This works in the node environment but not in the browser version, because in the browser version `() => new Agent()` is not an object and has an undefined prototype, leading to the error message `Object prototype may only be an Object or null: undefined`. Wrap `request.agent` in a proxy object for the client/browser case so that supertest can also use the library in browser contexts without error. --- src/client.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/client.js b/src/client.js index 319011ab..e85e59bd 100644 --- a/src/client.js +++ b/src/client.js @@ -872,7 +872,14 @@ Request.prototype._end = function () { xhr.send(typeof data === 'undefined' ? null : data); }; -request.agent = () => new Agent(); +// create a Proxy that can instantiate a new Agent without using `new` keyword +// (for backward compatibility and chaining) +const proxyAgent = new Proxy(Agent, { + apply(target, thisArg, argumentsList) { + return new target(...argumentsList); + } +}); +request.agent = proxyAgent; for (const method of ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE']) { Agent.prototype[method.toLowerCase()] = function (url, fn) {