|
| 1 | +import express from "express"; |
| 2 | +import getPort from "../get-port"; |
| 3 | +import ProxyServer, { createServer } from "../.."; |
| 4 | +import http from "node:http"; |
| 5 | + |
| 6 | +describe("test empty req.url", () => { |
| 7 | + let port: number, server: http.Server; |
| 8 | + |
| 9 | + it("create a simple http server", async () => { |
| 10 | + port = await getPort(); |
| 11 | + const app = express(); |
| 12 | + |
| 13 | + app.get("/test", (req, res, next) => { |
| 14 | + if (req.path !== "/test") return next(); |
| 15 | + res.send("Test Page!: " + JSON.stringify(req.query)); |
| 16 | + }); |
| 17 | + |
| 18 | + server = app.listen(port); |
| 19 | + }); |
| 20 | + |
| 21 | + let proxy: ProxyServer, httpServer: http.Server; |
| 22 | + let proxyPort: number; |
| 23 | + it("create a proxy server", async () => { |
| 24 | + proxy = createServer(); |
| 25 | + proxy.on("error", (err, _req, res) => { |
| 26 | + console.error("Proxy error:", err); |
| 27 | + res.end("Something went wrong."); |
| 28 | + }); |
| 29 | + httpServer = http.createServer((req, res) => { |
| 30 | + req.url = '' + new URL(`http://example.com${req.url}`).search; |
| 31 | + proxy.web(req, res, { target: `http://localhost:${port}/test` }); |
| 32 | + }); |
| 33 | + |
| 34 | + proxyPort = await getPort(); |
| 35 | + httpServer.listen(proxyPort); |
| 36 | + }); |
| 37 | + |
| 38 | + const getProxy = async (url: string) => { |
| 39 | + return await (await fetch(`http://localhost:${proxyPort}${url}`)).text(); |
| 40 | + }; |
| 41 | + |
| 42 | + it("get using the proxy", async () => { |
| 43 | + expect(await getProxy("")).toBe("Test Page!: {}"); |
| 44 | + expect(await getProxy("?foo")).toBe("Test Page!: {\"foo\":\"\"}"); |
| 45 | + expect(await getProxy("?foo=bar")).toBe("Test Page!: {\"foo\":\"bar\"}"); |
| 46 | + }); |
| 47 | + |
| 48 | + it("clean up", () => { |
| 49 | + server.close(); |
| 50 | + httpServer.close(); |
| 51 | + }); |
| 52 | +}); |
0 commit comments