proxy-forwarder-status-text.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Readable } from "node:stream";
  2. import { describe, expect, it, vi } from "vitest";
  3. const undiciMocks = vi.hoisted(() => {
  4. return {
  5. Agent: vi.fn(),
  6. ProxyAgent: vi.fn(),
  7. setGlobalDispatcher: vi.fn(),
  8. request: vi.fn(),
  9. fetch: vi.fn(),
  10. };
  11. });
  12. vi.mock("undici", () => undiciMocks);
  13. describe("ProxyForwarder - statusText", () => {
  14. it("标准状态码应写入对应的 statusText(例如 200 -> OK)", async () => {
  15. vi.resetModules();
  16. undiciMocks.request.mockResolvedValue({
  17. statusCode: 200,
  18. headers: { "content-type": "text/plain" },
  19. body: Readable.from(["ok"]),
  20. });
  21. const { ProxyForwarder } = await import("@/app/v1/_lib/proxy/forwarder");
  22. const fetchWithoutAutoDecode = (ProxyForwarder as any).fetchWithoutAutoDecode as (
  23. url: string,
  24. init: RequestInit,
  25. providerId: number,
  26. providerName: string
  27. ) => Promise<Response>;
  28. const response = await fetchWithoutAutoDecode(
  29. "https://example.com/test",
  30. { method: "GET" },
  31. 1,
  32. "test-provider"
  33. );
  34. expect(response.status).toBe(200);
  35. expect(response.statusText).toBe("OK");
  36. });
  37. it("未知/非标准状态码不应兜底为 OK(避免误导)", async () => {
  38. vi.resetModules();
  39. undiciMocks.request.mockResolvedValue({
  40. statusCode: 499,
  41. headers: { "content-type": "text/plain" },
  42. body: Readable.from(["unknown"]),
  43. });
  44. const { ProxyForwarder } = await import("@/app/v1/_lib/proxy/forwarder");
  45. const fetchWithoutAutoDecode = (ProxyForwarder as any).fetchWithoutAutoDecode as (
  46. url: string,
  47. init: RequestInit,
  48. providerId: number,
  49. providerName: string
  50. ) => Promise<Response>;
  51. const response = await fetchWithoutAutoDecode(
  52. "https://example.com/test",
  53. { method: "GET" },
  54. 1,
  55. "test-provider"
  56. );
  57. expect(response.status).toBe(499);
  58. expect(response.statusText).toBe("");
  59. });
  60. });