1 import { describe, expect, it, vi } from "vitest"
2 import { CatalogError, fetchCatalog } from "./catalog"
3
4 const options = { backendUrl: "http://localhost:9000", publishableKey: "pk_test_example" }
5 const regions = { regions: [
6 { id: "reg_ir", countries: [{ iso_2: "ir" }] },
7 { id: "reg_ae", countries: [{ iso_2: "ae" }] },
8 { id: "reg_om", countries: [{ iso_2: "om" }] },
9 { id: "reg_iq", countries: [{ iso_2: "iq" }] },
10 { id: "reg_qa", countries: [{ iso_2: "qa" }] },
11 ] }
12
13 function mockApi(productsResponse: Response, regionsResponse = new Response(JSON.stringify(regions))) {
14 return vi.fn(async (url: string) => url.includes("/store/regions") ? regionsResponse.clone() : productsResponse.clone())
15 }
16
17 describe("Medusa Store API catalog", () => {
18 it.each([["IR", "reg_ir"], ["AE", "reg_ae"], ["OM", "reg_om"], ["IQ", "reg_iq"], ["QA", "reg_qa"]] as const)(
19 "resolves country %s to region %s",
20 async (market, region) => {
21 const fetcher = mockApi(new Response(JSON.stringify({ products: [
22 { id: "prod_1", title: "Sample", handle: "sample", thumbnail: "https://example.com/a.jpg" },
23 ] })))
24 const products = await fetchCatalog(market, { ...options, fetcher: fetcher as typeof fetch })
25 expect(products).toHaveLength(1)
26 expect(fetcher.mock.calls[1][0]).toContain("region_id=" + region)
27 },
28 )
29 it("requires a publishable key", async () => {
30 await expect(fetchCatalog("AE", { ...options, publishableKey: "" })).rejects.toThrow("publishable key")
31 })
32 it("rejects markets not enabled in backend", async () => {
33 const fetcher = mockApi(new Response(JSON.stringify({ products: [] })), new Response(JSON.stringify({ regions: [] })))
34 await expect(fetchCatalog("QA", { ...options, fetcher: fetcher as typeof fetch })).rejects.toThrow("not configured")
35 })
36 it("surfaces HTTP errors", async () => {
37 const fetcher = mockApi(new Response("Unauthorized", { status: 401 }))
38 await expect(fetchCatalog("QA", { ...options, fetcher: fetcher as typeof fetch })).rejects.toMatchObject({ status: 401 })
39 })
40 it("rejects malformed product response", async () => {
41 const fetcher = mockApi(new Response(JSON.stringify({ items: [] })))
42 await expect(fetchCatalog("OM", { ...options, fetcher: fetcher as typeof fetch })).rejects.toBeInstanceOf(CatalogError)
43 })
44 })