Files
persionalBrand/packages/api-client/test/client.test.ts

72 lines
2.4 KiB
TypeScript

import assert from "node:assert/strict";
import { test } from "node:test";
import { ApiClient, ApiClientError, type FetchResponse } from "../src/index.js";
function response(body: unknown, status = 200): FetchResponse {
return { status, ok: status >= 200 && status < 300, json: async () => body };
}
test("客户端发送认证头、查询参数和 JSON 请求体", async () => {
const calls: Array<{ url: string; init?: { headers?: Record<string, string>; body?: string } }> =
[];
const client = new ApiClient({
baseUrl: "http://api.test/",
token: "token-1",
fetcher: async (url, init) => {
calls.push({ url, init });
return response({ count: 2 });
},
});
await client.listAdminBookings({ status: "received", unreadOnly: true, tagId: "tag/1" });
await client.createAdminTag("重点");
assert.equal(
calls[0]?.url,
"http://api.test/admin/bookings?status=received&unreadOnly=true&tagId=tag%2F1",
);
assert.equal(calls[0]?.init?.headers?.authorization, "Bearer token-1");
assert.equal(calls[1]?.init?.body, JSON.stringify({ name: "重点" }));
});
test("客户端将统一错误响应转换为 ApiClientError", async () => {
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async () =>
response(
{ data: null, error: { code: "HTTP_401", message: "无权限" }, requestId: "req-1" },
401,
),
});
await assert.rejects(
() => client.getAdminUnreadCount(),
(error: unknown) => {
assert.ok(error instanceof ApiClientError);
assert.equal(error.status, 401);
assert.equal(error.code, "HTTP_401");
assert.equal(error.requestId, "req-1");
return true;
},
);
});
test("发布检查与发布操作使用当前品牌的管理接口", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
token: "brand-token",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method, body: init?.body });
return response({ ready: true, checks: [] });
},
});
await client.getAdminReleaseReadiness();
await client.publishAdminRelease("首次发布");
assert.deepEqual(calls, [
{ url: "http://api.test/admin/releases/readiness", method: "GET", body: undefined },
{
url: "http://api.test/admin/releases/publish",
method: "POST",
body: JSON.stringify({ note: "首次发布" }),
},
]);
});