import { expect, test } from "bun:test"; import ky from "ky"; import { createBillFlow, deleteBillFlow, submitBillFlow } from "./api.js"; import { AuthenticationError, EkbApiError, PermissionError } from "../../core/errors.js"; function fixture(response: unknown, status = 200) { let requests = 0; const client = ky.create({ prefix: "https://tenant.invalid", retry: 0, fetch: async () => { requests++; return Response.json(response, { status }); } }); return { client, count: () => requests }; } test("创建兼容 flow/value/裸对象包装,保留正常业务单号", async () => { const flow = { id: "created", code: "B26000001", form: { code: "B26000001" } }; for (const response of [{ flow }, { value: flow }, flow]) { expect(await createBillFlow(fixture(response).client, "corp", { title: "草稿" })).toEqual(flow); } }); test("所有单据写动作检查 HTTP 200 中的业务拒绝与鉴权错误", async () => { for (const action of [ (client: ReturnType) => createBillFlow(client, "corp", {}), (client: ReturnType) => submitBillFlow(client, "corp", "f", {}, "expense", []), (client: ReturnType) => deleteBillFlow(client, "corp", "f"), ]) { for (const [errorCode, ErrorClass] of [["REJECTED", EkbApiError], [401, AuthenticationError], [403, PermissionError]] as const) { const { client, count } = fixture({ errorCode, errorMessage: "拒绝操作" }); await expect(action(client)).rejects.toBeInstanceOf(ErrorClass); expect(count()).toBe(1); } } }); test("HTTP 失败不被吞掉;无效或空流程 ID 不被强转为成功", async () => { const { client, count } = fixture({ error: "unavailable" }, 503); await expect(createBillFlow(client, "corp", {})).rejects.toThrow(); expect(count()).toBe(1); for (const response of [{ flow: {} }, { flow: { id: 1 } }, { value: { id: " " } }, { id: "f", form: [] }]) { await expect(createBillFlow(fixture(response).client, "corp", {})).rejects.toBeInstanceOf(EkbApiError); } });