import { http, HttpResponse } from "msw"; import { afterEach, describe, expect, test, vi } from "vitest"; import { ApiError } from "../api-error"; import { server } from "../../test/server"; import { apiBaseUrl, createTestClient, valueSchema } from "./client-test-helpers"; afterEach(() => { vi.unstubAllEnvs(); }); describe("API client", () => { test("accepts a successful envelope without errorProperty", async () => { // Given vi.stubEnv("VITE_API_BASE_URL", apiBaseUrl); const { client } = createTestClient(); server.use( http.get(`${apiBaseUrl}/public`, () => HttpResponse.json({ success: true, message: null, data: { value: "ok" } }), ), ); // When const response = await client.request({ path: "/public", responseSchema: valueSchema, authentication: "none", }); // Then expect(response).toEqual({ value: "ok" }); }); test("accepts a successful envelope with null errorProperty", async () => { // Given vi.stubEnv("VITE_API_BASE_URL", apiBaseUrl); const { client } = createTestClient(); server.use( http.get(`${apiBaseUrl}/public`, () => HttpResponse.json({ success: true, message: null, data: { value: "ok" }, errorProperty: null, }), ), ); // When const response = await client.request({ path: "/public", responseSchema: valueSchema, authentication: "none", }); // Then expect(response).toEqual({ value: "ok" }); }); test.each([400, 404, 405, 415, 500])( "preserves a Korean server error envelope for status %i", async (status) => { // Given vi.stubEnv("VITE_API_BASE_URL", apiBaseUrl); const { client } = createTestClient(); const message = `서버 오류 ${status}`; const errorProperty = "request"; server.use( http.get(`${apiBaseUrl}/error`, () => HttpResponse.json( { success: false, message, data: null, errorProperty }, { status }, ), ), ); // When const request = client.request({ path: "/error", responseSchema: valueSchema, authentication: "none", }); // Then await expect(request).rejects.toMatchObject({ status, message, errorProperty }); }, ); test("exposes server errors as ApiError", async () => { // Given vi.stubEnv("VITE_API_BASE_URL", apiBaseUrl); const { client } = createTestClient(); server.use( http.get(`${apiBaseUrl}/error`, () => HttpResponse.json( { success: false, message: "잘못된 요청입니다.", data: null, errorProperty: null, }, { status: 400 }, ), ), ); // When const request = client.request({ path: "/error", responseSchema: valueSchema, authentication: "none", }); // Then await expect(request).rejects.toBeInstanceOf(ApiError); }); });