Debian Codegraph @

web/src/app/Api.test.js

raw
1 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2 import userManager from "./UserManager";
3 import api from "./Api";
4
5 // Api.js talks to the server through the global fetch and looks up credentials via userManager.
6 // (vi.mock is hoisted above the imports by vitest, so the import above receives the mock.)
7 vi.mock("./UserManager", () => ({ default: { get: vi.fn() } }));
8
9 let fetchMock;
10
11 beforeEach(() => {
12 vi.clearAllMocks();
13 vi.spyOn(console, "log").mockImplementation(() => {});
14 fetchMock = vi.fn();
15 vi.stubGlobal("fetch", fetchMock);
16 userManager.get.mockResolvedValue(undefined); // anonymous by default
17 });
18
19 afterEach(() => {
20 vi.restoreAllMocks();
21 vi.unstubAllGlobals();
22 });
23
24 describe("Api.poll", () => {
25 it("parses newline-delimited JSON and skips lines without an id", async () => {
26 const body = [
27 JSON.stringify({ id: "1", message: "a" }),
28 JSON.stringify({ event: "keepalive" }), // no id -> skipped
29 JSON.stringify({ id: "2", message: "b" }),
30 ].join("\n");
31 fetchMock.mockResolvedValue(new Response(body));
32
33 const messages = await api.poll("https://ntfy.sh", "mytopic");
34
35 expect(messages.map((m) => m.id)).toEqual(["1", "2"]);
36 });
37
38 it("uses the plain poll URL without a since cursor", async () => {
39 fetchMock.mockResolvedValue(new Response(""));
40 await api.poll("https://ntfy.sh", "mytopic");
41 expect(fetchMock).toHaveBeenCalledWith("https://ntfy.sh/mytopic/json?poll=1", expect.anything());
42 });
43
44 it("uses the since URL when a cursor is given", async () => {
45 fetchMock.mockResolvedValue(new Response(""));
46 await api.poll("https://ntfy.sh", "mytopic", 12345);
47 expect(fetchMock).toHaveBeenCalledWith("https://ntfy.sh/mytopic/json?poll=1&since=12345", expect.anything());
48 });
49 });
50
51 describe("Api.publish", () => {
52 it("PUTs the message body to the base URL", async () => {
53 fetchMock.mockResolvedValue({ status: 200 });
54 await api.publish("https://ntfy.sh", "mytopic", "Hello", { priority: 5, tags: ["warning"] });
55 expect(fetchMock).toHaveBeenCalledWith(
56 "https://ntfy.sh",
57 expect.objectContaining({
58 method: "PUT",
59 body: JSON.stringify({ topic: "mytopic", message: "Hello", priority: 5, tags: ["warning"] }),
60 }),
61 );
62 });
63
64 it("attaches basic auth when the user has a password", async () => {
65 userManager.get.mockResolvedValue({ username: "phil", password: "secret" });
66 fetchMock.mockResolvedValue({ status: 200 });
67 await api.publish("https://ntfy.sh", "mytopic", "Hi");
68 const [, options] = fetchMock.mock.calls[0];
69 expect(options.headers.Authorization).toBe(`Basic ${btoa("phil:secret")}`);
70 });
71
72 it("attaches bearer auth when the user has a token", async () => {
73 userManager.get.mockResolvedValue({ token: "tk_abc" });
74 fetchMock.mockResolvedValue({ status: 200 });
75 await api.publish("https://ntfy.sh", "mytopic", "Hi");
76 const [, options] = fetchMock.mock.calls[0];
77 expect(options.headers.Authorization).toBe("Bearer tk_abc");
78 });
79 });
80
81 describe("Api.topicAuth", () => {
82 it("returns true for a 2xx response", async () => {
83 fetchMock.mockResolvedValue({ status: 200 });
84 expect(await api.topicAuth("https://ntfy.sh", "mytopic")).toBe(true);
85 });
86
87 it("returns false for 401/403", async () => {
88 fetchMock.mockResolvedValue({ status: 403 });
89 expect(await api.topicAuth("https://ntfy.sh", "mytopic")).toBe(false);
90 });
91
92 it("throws for any other status", async () => {
93 fetchMock.mockResolvedValue({ status: 500 });
94 await expect(api.topicAuth("https://ntfy.sh", "mytopic")).rejects.toThrow("Unexpected server response 500");
95 });
96 });
97
98 describe("Api web push", () => {
99 const pushSubscription = {
100 endpoint: "https://push.example/abc",
101 keys: { auth: "AUTH", p256dh: "P256" },
102 };
103
104 it("updateWebPush POSTs endpoint, keys and topics to the web push URL", async () => {
105 fetchMock.mockResolvedValue({ status: 200 });
106 await api.updateWebPush(pushSubscription, ["topicA", "topicB"]);
107 expect(fetchMock).toHaveBeenCalledWith(
108 "https://ntfy.sh/v1/webpush",
109 expect.objectContaining({
110 method: "POST",
111 body: JSON.stringify({ endpoint: "https://push.example/abc", auth: "AUTH", p256dh: "P256", topics: ["topicA", "topicB"] }),
112 }),
113 );
114 });
115
116 it("deleteWebPush DELETEs just the endpoint", async () => {
117 fetchMock.mockResolvedValue({ status: 200 });
118 await api.deleteWebPush(pushSubscription);
119 expect(fetchMock).toHaveBeenCalledWith(
120 "https://ntfy.sh/v1/webpush",
121 expect.objectContaining({
122 method: "DELETE",
123 body: JSON.stringify({ endpoint: "https://push.example/abc" }),
124 }),
125 );
126 });
127 });