|
| 1 | +import { describe, it, expect, vi, afterEach } from "vitest" |
| 2 | +import { getText, getJSON } from "@/utils/fetch" |
| 3 | +import { addHandlers } from "../msw.setup" |
| 4 | +import { http, HttpResponse } from "msw" |
| 5 | + |
| 6 | +describe("fetch facade", () => { |
| 7 | + afterEach(() => { |
| 8 | + vi.clearAllMocks() |
| 9 | + }) |
| 10 | + |
| 11 | + describe("getText", () => { |
| 12 | + it("should fetch URL and return text content", async () => { |
| 13 | + addHandlers( |
| 14 | + http.get("https://example.com/test", () => { |
| 15 | + return HttpResponse.text("Hello, World!") |
| 16 | + }) |
| 17 | + ) |
| 18 | + |
| 19 | + const result = await getText("https://example.com/test") |
| 20 | + expect(result).toBe("Hello, World!") |
| 21 | + }) |
| 22 | + |
| 23 | + it("should throw error when fetch response is not ok", async () => { |
| 24 | + addHandlers( |
| 25 | + http.get("https://example.com/missing", () => { |
| 26 | + return HttpResponse.text("Not Found", { status: 404 }) |
| 27 | + }) |
| 28 | + ) |
| 29 | + |
| 30 | + await expect(getText("https://example.com/missing")).rejects.toThrow( |
| 31 | + "Failed to fetch https://example.com/missing: 404 Not Found" |
| 32 | + ) |
| 33 | + }) |
| 34 | + }) |
| 35 | + |
| 36 | + describe("getJSON", () => { |
| 37 | + it("should fetch URL and return JSON object", async () => { |
| 38 | + const mockData = { message: "Hello", count: 42 } |
| 39 | + addHandlers( |
| 40 | + http.get("https://api.example.com/data", () => { |
| 41 | + return HttpResponse.json(mockData) |
| 42 | + }) |
| 43 | + ) |
| 44 | + |
| 45 | + const result = await getJSON("https://api.example.com/data") |
| 46 | + expect(result).toEqual(mockData) |
| 47 | + }) |
| 48 | + |
| 49 | + it("should throw error when fetch response is not ok", async () => { |
| 50 | + addHandlers( |
| 51 | + http.get("https://api.example.com/error", () => { |
| 52 | + return HttpResponse.json({ error: "Server Error" }, { status: 500 }) |
| 53 | + }) |
| 54 | + ) |
| 55 | + |
| 56 | + await expect(getJSON("https://api.example.com/error")).rejects.toThrow( |
| 57 | + "Failed to fetch https://api.example.com/error: 500 Internal Server Error" |
| 58 | + ) |
| 59 | + }) |
| 60 | + }) |
| 61 | +}) |
0 commit comments