apiJson.test.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { describe, expect, it, vi } from "vitest";
  2. import { ApiError, type ApiClient } from "@zcode/shared";
  3. import { readApiJson } from "../src/providers/api/apiJson.js";
  4. function createMockClient(responseFactory: ReturnType<typeof vi.fn>): ApiClient {
  5. return {
  6. request: responseFactory,
  7. };
  8. }
  9. describe("apiJson", () => {
  10. it("非 2xx 响应会抛出带状态码的 ApiError", async () => {
  11. const request = vi.fn(async () => {
  12. return new Response(JSON.stringify({ error: "invalid token" }), {
  13. status: 401,
  14. headers: { "Content-Type": "application/json" },
  15. });
  16. });
  17. await expect(
  18. readApiJson(createMockClient(request), "https://example.com/oauth/userinfo"),
  19. ).rejects.toEqual(
  20. expect.objectContaining<ApiError>({
  21. name: "ApiError",
  22. method: "GET",
  23. status: 401,
  24. url: "https://example.com/oauth/userinfo",
  25. }),
  26. );
  27. });
  28. it("响应不是合法 JSON 时会抛出统一的 ApiError", async () => {
  29. const request = vi.fn(async () => {
  30. return new Response("not-json", {
  31. status: 200,
  32. headers: { "Content-Type": "application/json" },
  33. });
  34. });
  35. await expect(
  36. readApiJson(createMockClient(request), "https://example.com/client/configs"),
  37. ).rejects.toEqual(
  38. expect.objectContaining<ApiError>({
  39. name: "ApiError",
  40. method: "GET",
  41. status: 200,
  42. url: "https://example.com/client/configs",
  43. }),
  44. );
  45. });
  46. });