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

423 lines
14 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from "node:assert/strict";
import { test } from "node:test";
import {
ApiClient,
ApiClientContractError,
ApiClientError,
assertResponseContract,
type FetchResponse,
} from "../src/index.js";
import { adminTrustContentListSchema } from "../src/schemas/admin-collections.js";
import { z } from "zod";
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(url.includes("/admin/bookings?") ? [] : { 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("客户端登出会调用当前会话接口", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
token: "admin-token",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method, body: init?.body });
return response({ loggedOut: true });
},
});
await client.logoutAdmin();
await client.logoutCustomer();
assert.deepEqual(calls, [
{ url: "http://api.test/admin/session/logout", method: "POST", body: "{}" },
{ url: "http://api.test/customer/session/logout", method: "POST", body: "{}" },
]);
});
test("Admin 会话客户端读取当前会话且登录不返回 token", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method, body: init?.body });
return url.endsWith("/session/current")
? response({
authenticated: true,
displayName: "测试管理员",
mustChangePassword: false,
role: "owner",
platformTemplateRole: "none",
})
: response({
displayName: "测试管理员",
mustChangePassword: false,
role: "owner",
platformTemplateRole: "none",
});
},
});
const current = await client.getAdminSession();
const login = await client.loginAdmin("admin", "password-123");
assert.equal(current.authenticated, true);
assert.equal("token" in login, false);
assert.deepEqual(calls, [
{ url: "http://api.test/admin/session/current", method: "GET", body: undefined },
{
url: "http://api.test/admin/session/login",
method: "POST",
body: JSON.stringify({ username: "admin", password: "password-123" }),
},
]);
});
test("品牌切换客户端不再接收 token", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method, body: init?.body });
return response({ role: "owner", brand: { id: "brand-1", name: "品牌一" } });
},
});
const switched = await client.switchAdminBrand("brand-1");
assert.equal("token" in switched, false);
assert.deepEqual(calls, [
{
url: "http://api.test/admin/brands/brand-1/switch",
method: "POST",
body: undefined,
},
]);
});
test("创建品牌与品牌内页面方案选项使用各自授权接口", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
token: "owner-token",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method, body: init?.body });
return response({});
},
});
await client.getAdminBrandCreationOptions();
await client.createAdminBrand({
name: "林境门窗",
slug: "linjing-windows",
businessType: "doors",
templatePackageVersionId: "version-1",
});
await client.getAdminPageSchemeOptions();
assert.deepEqual(calls, [
{ url: "http://api.test/admin/brands/creation-options", method: "GET", body: undefined },
{
url: "http://api.test/admin/brands",
method: "POST",
body: JSON.stringify({
name: "林境门窗",
slug: "linjing-windows",
businessType: "doors",
templatePackageVersionId: "version-1",
}),
},
{ url: "http://api.test/admin/workspace/template/options", method: "GET", body: undefined },
]);
});
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: "首次发布" }),
},
]);
});
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({ appId: "wx123", apiBaseUrl: "https://wechat.example.com/api" });
},
});
await client.updateAdminMiniAppSettings({
appId: "wx123",
apiBaseUrl: "https://wechat.example.com/api",
});
assert.deepEqual(calls, [
{
url: "http://api.test/admin/miniapp-releases/settings",
method: "PATCH",
body: JSON.stringify({
appId: "wx123",
apiBaseUrl: "https://wechat.example.com/api",
}),
},
]);
});
test("模板目录客户端发送分页并支持版本发布和审计", async () => {
const calls: Array<{ url: string; method?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
token: "template-admin-token",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method });
return response(
url.includes("/audit")
? []
: url.endsWith("/publish")
? { changed: true, version: { id: "version-1", status: "published" } }
: { items: [], page: 2, pageSize: 10, total: 0 },
);
},
});
await client.listAdminTemplatePackages({ page: 2, pageSize: 10 });
await client.publishAdminTemplatePackage("version/1");
await client.listAdminTemplatePackageAudit("version/1");
await client.previewAdminTemplatePackage("version/1", "personal & design");
await client.previewAdminTemplatePackage("version/1", "personal & design", "1".repeat(64));
assert.deepEqual(calls, [
{ url: "http://api.test/admin/templates?page=2&pageSize=10", method: "GET" },
{ url: "http://api.test/admin/templates/version%2F1/publish", method: "POST" },
{ url: "http://api.test/admin/templates/version%2F1/audit", method: "GET" },
{
url: "http://api.test/admin/templates/version%2F1/preview?industry=personal%20%26%20design",
method: "GET",
},
{
url: "http://api.test/admin/templates/version%2F1/preview?industry=personal%20%26%20design&session=1111111111111111111111111111111111111111111111111111111111111111",
method: "GET",
},
]);
});
test("模板升级和回滚提交预览版本、checksum 与全部保留确认", 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({ installation: { templateVersion: "2.0.0" } });
},
});
await client.upgradeAdminTemplate({
templatePackageVersionId: "target-version",
expectedContentChecksum: "target-checksum",
expectedCurrentVersion: "1.0.0",
expectedCurrentPackageVersionId: "source-version",
confirm: true,
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
});
await client.rollbackAdminTemplate({ expectedCurrentVersion: "2.0.0", confirm: true });
assert.deepEqual(calls, [
{
url: "http://api.test/admin/workspace/template/upgrade",
method: "POST",
body: JSON.stringify({
templatePackageVersionId: "target-version",
expectedContentChecksum: "target-checksum",
expectedCurrentVersion: "1.0.0",
expectedCurrentPackageVersionId: "source-version",
confirm: true,
preservedBindings: [
{ key: "founder", binding: "brand.config.founder", action: "preserve" },
],
}),
},
{
url: "http://api.test/admin/workspace/template/rollback",
method: "POST",
body: JSON.stringify({ expectedCurrentVersion: "2.0.0", confirm: true }),
},
]);
});
test("模板运营失败指标客户端发送查询窗口", async () => {
const calls: Array<{ url: string; method?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
token: "template-admin-token",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method });
return response({
since: "2026-10-01",
until: "2026-10-17",
days: 14,
backfilled: false,
failures: [],
});
},
});
await client.getAdminTemplateOperationFailures({ days: 14 });
assert.deepEqual(calls, [
{ url: "http://api.test/admin/template-operations/failures?days=14", method: "GET" },
]);
});
test("响应契约通过时保留原始数据,包含 schema 未声明的字段", async () => {
const body = [
{
id: "trust-1",
type: "credential",
title: "从业十年",
content: "长期服务本地客户",
sortOrder: 0,
isPublished: true,
summary: null,
coverUrl: null,
config: { sections: [] },
futureField: "保留",
},
];
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async () => response(body),
});
const result = await client.listAdminTrustContent();
assert.deepEqual(result, body);
});
test("响应契约不匹配时抛出带接口路径的 ApiClientContractError", async () => {
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async () => response([null]),
});
await assert.rejects(
() => client.listAdminTrustContent(),
(error: unknown) => {
assert.ok(error instanceof ApiClientContractError);
assert.equal(error.path, "/admin/config/trust-content");
assert.match(error.message, /\/admin\/config\/trust-content/);
assert.ok(error.issues.length > 0);
return true;
},
);
});
test("契约校验只接受对象数组且拒绝缺少关键字段的记录", () => {
assert.throws(
() =>
assertResponseContract(
z.array(z.object({ id: z.string() })),
[{ id: "ok" }, { id: 1 }],
"/admin/example",
),
(error: unknown) => {
assert.ok(error instanceof ApiClientContractError);
assert.match(error.issues[0] ?? "", /^1\.id:/);
return true;
},
);
assert.doesNotThrow(() =>
assertResponseContract(adminTrustContentListSchema, [], "/admin/config/trust-content"),
);
});
test("错误响应仍抛 ApiClientError,而不是契约错误", async () => {
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async () =>
response(
{ data: null, error: { code: "HTTP_500", message: "服务异常" }, requestId: "req-2" },
500,
),
});
await assert.rejects(
() => client.listAdminTrustContent(),
(error: unknown) => {
assert.ok(error instanceof ApiClientError);
assert.equal(error instanceof ApiClientContractError, false);
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({ received: true, duplicate: false });
},
});
const receipt = await client.reportAdminClientError({
errorId: "admin-abc-123",
message: "boom",
route: "/admin/trust?tab=1",
componentStack: "at TrustContentPage",
});
assert.deepEqual(receipt, { received: true, duplicate: false });
assert.deepEqual(calls, [
{
url: "http://api.test/admin/client-errors",
method: "POST",
body: JSON.stringify({
errorId: "admin-abc-123",
message: "boom",
route: "/admin/trust?tab=1",
componentStack: "at TrustContentPage",
}),
},
]);
});