router / src /test.ts
xinxiang.wang
../..
53cc475
import { expect, test, describe } from "bun:test";
import { fetch } from "bun";
// The port where our proxy server is running
const PROXY_PORT = process.env.PORT || 8000;
const PROXY_URL = `http://localhost:${PROXY_PORT}`;
// Test target URLs
const TEST_ENDPOINTS = [
"https://httpbin.org/get",
"https://httpbin.org/headers",
"https://httpbin.org/status/200",
"https://httpbin.org/anything"
];
describe("URL Proxy Server Tests", () => {
// Basic functionality test
test("should proxy a GET request correctly", async () => {
const targetUrl = "https://httpbin.org/get";
const response = await fetch(`${PROXY_URL}/${targetUrl}`);
expect(response.status).toBe(200);
const data = await response.json() as any;
expect(data.url).toBe(targetUrl);
});
// Test with query parameters
test("should handle query parameters correctly", async () => {
const targetUrl = "https://httpbin.org/get";
const queryParams = "?param1=value1&param2=value2";
const response = await fetch(`${PROXY_URL}/${targetUrl}${queryParams}`);
expect(response.status).toBe(200);
const data = await response.json() as any;
expect(data.args.param1).toBe("value1");
expect(data.args.param2).toBe("value2");
});
// Test POST request
test("should proxy a POST request with JSON body", async () => {
const targetUrl = "https://httpbin.org/post";
const testData = { test: "data", number: 123 };
const response = await fetch(`${PROXY_URL}/${targetUrl}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(testData)
});
expect(response.status).toBe(200);
const data = await response.json() as any;
expect(data.json).toEqual(testData);
});
// Test headers forwarding
test("should forward custom headers correctly", async () => {
const targetUrl = "https://httpbin.org/headers";
const customHeader = "X-Custom-Test-Header";
const headerValue = "test-value-123";
const response = await fetch(`${PROXY_URL}/${targetUrl}`, {
headers: {
[customHeader]: headerValue
}
});
expect(response.status).toBe(200);
const data = await response.json() as any;
// httpbin normalizes header names to lowercase with hyphens
const normalizedHeaderName = customHeader.toLowerCase();
expect(data.headers[normalizedHeaderName]).toBe(headerValue);
});
// Test error handling for invalid URLs
test("should return 400 for invalid target URLs", async () => {
const invalidUrl = "not-a-valid-url";
const response = await fetch(`${PROXY_URL}/${invalidUrl}`);
expect(response.status).toBe(400);
});
// Test concurrent requests
test("should handle multiple concurrent requests", async () => {
// Create 16 concurrent requests to different endpoints
const requests = [];
for (let i = 0; i < 16; i++) {
const targetUrl = TEST_ENDPOINTS[i % TEST_ENDPOINTS.length];
requests.push(fetch(`${PROXY_URL}/${targetUrl}`));
}
const responses = await Promise.all(requests);
// Check that all responses were successful
for (const response of responses) {
expect(response.status).toBe(200);
}
});
});