Files
khb_microservices/packages/accounting_automation/src/qbo-client.test.ts

58 lines
3.9 KiB
TypeScript
Raw 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 { describe, expect, it } from "vitest";
import { makeQboClient, QboFileTooLarge, MAX_ATTACH_BYTES } from "./qbo-client.js";
function fakeFetch(calls: { url: string; init?: RequestInit }[], respond: (url: string, init?: RequestInit) => Response): typeof fetch {
return (async (url: string | URL, init?: RequestInit) => {
calls.push({ url: String(url), init });
if (String(url).endsWith("/token") || String(url).includes("/token?")) {
return new Response(JSON.stringify({ accessToken: "AT", realmId: "R1", apiBase: "https://qbo.test", expiresAt: new Date(Date.now() + 3600_000).toISOString() }), { status: 200 });
}
return respond(String(url), init);
}) as unknown as typeof fetch;
}
describe("qbo-client", () => {
it("query: токен берётся у qbo_auth, запрос уходит с Bearer", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
const c = makeQboClient({ authUrl: "http://auth", authToken: "T", fetchFn: fakeFetch(calls, () => new Response(JSON.stringify({ QueryResponse: { Purchase: [{ Id: "1" }] } }), { status: 200 })) });
const r = await c.query("select * from Purchase");
expect(r.Purchase).toEqual([{ Id: "1" }]);
expect(calls[0]!.url).toBe("http://auth/token");
expect((calls[0]!.init!.headers as Record<string, string>).authorization).toBe("Bearer T");
expect(calls[1]!.url).toContain("https://qbo.test/v3/company/R1/query?query=select%20*%20from%20Purchase");
});
it("401: токен обновляется принудительно и запрос повторяется один раз", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
let n = 0;
const c = makeQboClient({ authUrl: "http://auth", authToken: "T", fetchFn: fakeFetch(calls, () => (n++ === 0 ? new Response("expired", { status: 401 }) : new Response(JSON.stringify({ QueryResponse: {} }), { status: 200 }))) });
await c.query("select 1");
expect(calls.some((x) => x.url.includes("/token?force=true"))).toBe(true);
});
it("uploadAttachment: multipart с привязкой к записи; слишком большой файл - QboFileTooLarge", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
const c = makeQboClient({ authUrl: "http://auth", authToken: "T", fetchFn: fakeFetch(calls, () => new Response(JSON.stringify({ AttachableResponse: [{ Attachable: { Id: "77" } }] }), { status: 200 })) });
const r = await c.uploadAttachment({ fileName: "a.pdf", mime: "application/pdf", bytes: Buffer.from("PDF"), attachTo: { type: "Purchase", id: "4174" } });
expect(r.id).toBe("77");
const up = calls.find((x) => x.url.includes("/upload"))!;
const body = Buffer.from(up.init!.body as Buffer).toString("latin1");
expect(body).toContain('"value":"4174"');
expect(body).toContain('"type":"Purchase"');
expect(body).toContain("PDF");
await expect(c.uploadAttachment({ fileName: "b.pdf", mime: "application/pdf", bytes: Buffer.alloc(MAX_ATTACH_BYTES + 1), attachTo: { type: "Purchase", id: "1" } })).rejects.toBeInstanceOf(QboFileTooLarge);
});
it("appendNote: дописывает Memo (sparse update) и не дублирует", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
const c = makeQboClient({
authUrl: "http://auth",
authToken: "T",
fetchFn: fakeFetch(calls, (url, init) => (init?.method === "POST" ? new Response("{}", { status: 200 }) : new Response(JSON.stringify({ Purchase: { Id: "5", SyncToken: "2", PrivateNote: "старое" } }), { status: 200 }))),
});
await c.appendNote("purchase", "5", "Документ: https://x");
const post = calls.find((x) => x.init?.method === "POST" && !x.url.includes("/token"))!;
expect(JSON.parse(post.init!.body as string)).toMatchObject({ Id: "5", SyncToken: "2", sparse: true, PrivateNote: "старое\nДокумент: https://x" });
});
});