@eggjs/supertest
Version:
SuperAgent driven library for testing HTTP servers
74 lines (72 loc) • 1.8 kB
JavaScript
import { Test } from "./test.js";
import http from "node:http";
import http2 from "node:http2";
import { agent } from "superagent";
//#region src/agent.ts
/**
* Initialize a new `TestAgent`.
*
* @param {Function|Server} app
* @param {Object} options
*/
var TestAgent = class extends agent {
app;
_host;
#http2 = false;
constructor(appOrListener, options = {}) {
super(options);
if (typeof appOrListener === "function") if (options.http2) {
this.#http2 = true;
this.app = http2.createServer(appOrListener);
} else this.app = http.createServer(appOrListener);
else this.app = appOrListener;
}
host(host) {
this._host = host;
return this;
}
_testRequest(method, url) {
const req = new Test(this.app, method.toUpperCase(), url);
if (this.#http2) req.http2();
if (this._host) req.set("host", this._host);
const that = this;
req.on("response", that._saveCookies.bind(this));
req.on("redirect", that._saveCookies.bind(this));
req.on("redirect", that._attachCookies.bind(this, req));
that._setDefaults(req);
that._attachCookies(req);
return req;
}
delete(url) {
return this._testRequest("delete", url);
}
del(url) {
return this._testRequest("delete", url);
}
get(url) {
return this._testRequest("get", url);
}
head(url) {
return this._testRequest("head", url);
}
put(url) {
return this._testRequest("put", url);
}
post(url) {
return this._testRequest("post", url);
}
patch(url) {
return this._testRequest("patch", url);
}
options(url) {
return this._testRequest("options", url);
}
trace(url) {
return this._testRequest("trace", url);
}
};
const proxyAgent = new Proxy(TestAgent, { apply(target, _, argumentsList) {
return new target(argumentsList[0], argumentsList[1]);
} });
//#endregion
export { TestAgent, proxyAgent };