⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
test: add unit tests for websocket broadcast and event system
tiran133c542ae7e1968
diff --git a/tests/api/events/publish-event.test.ts b/tests/api/events/publish-event.test.tsnew file mode 100644index 000000000..b3fcc6898--- /dev/null+++ b/tests/api/events/publish-event.test.ts@@ -0,0 +1,99 @@+import { afterEach, describe, expect, it } from "vitest";+import {+ eventContext,+ publishEvent,+ shutdownEventBus,+ subscribeToEvent,+} from "../../../apps/api/src/events/index";++describe("publishEvent / subscribeToEvent", () => {+ afterEach(async () => {+ await shutdownEventBus();+ });++ it("delivers event data to a subscriber", async () => {+ const received: unknown[] = [];++ await subscribeToEvent("test.event", async (data) => {+ received.push(data);+ });++ await publishEvent("test.event", { foo: "bar" });++ // EventEmitter is synchronous so handler runs inline+ expect(received).toHaveLength(1);+ expect(received[0]).toMatchObject({ foo: "bar" });+ });++ it("attaches initiatorId from eventContext store", async () => {+ const received: Array<{ initiatorId?: string }> = [];++ await subscribeToEvent<{ initiatorId?: string }>(+ "test.initiator",+ async (data) => {+ received.push(data);+ },+ );++ await eventContext.run({ initiatorId: "user-abc" }, async () => {+ await publishEvent("test.initiator", { taskId: "t1" });+ });++ expect(received).toHaveLength(1);+ expect(received[0]?.initiatorId).toBe("user-abc");+ });++ it("sets initiatorId to undefined when no eventContext store exists", async () => {+ const received: Array<{ initiatorId?: string }> = [];++ await subscribeToEvent<{ initiatorId?: string }>(+ "test.no-context",+ async (data) => {+ received.push(data);+ },+ );++ await publishEvent("test.no-context", { taskId: "t2" });++ expect(received).toHaveLength(1);+ expect(received[0]?.initiatorId).toBeUndefined();+ });++ it("does not deliver events to unrelated subscribers", async () => {+ const received: unknown[] = [];++ await subscribeToEvent("other.event", async (data) => {+ received.push(data);+ });++ await publishEvent("test.unrelated", { value: 1 });++ expect(received).toHaveLength(0);+ });++ it("handles non-object data without attaching initiatorId", async () => {+ const received: unknown[] = [];++ await subscribeToEvent("test.primitive", async (data) => {+ received.push(data);+ });++ await publishEvent("test.primitive", "just a string");++ expect(received).toHaveLength(1);+ expect(received[0]).toBe("just a string");+ });++ it("shutdownEventBus removes all listeners", async () => {+ const received: unknown[] = [];++ await subscribeToEvent("test.shutdown", async (data) => {+ received.push(data);+ });++ await shutdownEventBus();+ await publishEvent("test.shutdown", { after: true });++ expect(received).toHaveLength(0);+ });+});diff --git a/tests/api/ws/broadcast.test.ts b/tests/api/ws/broadcast.test.tsnew file mode 100644index 000000000..a0787126f--- /dev/null+++ b/tests/api/ws/broadcast.test.ts@@ -0,0 +1,168 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// Mock events to prevent side effects from ws/index.ts top-level subscriptions+vi.mock("../../../apps/api/src/events", () => ({+ subscribeToEvent: vi.fn(),+ publishEvent: vi.fn(),+}));++import {+ addConnection,+ broadcastToProject,+ initializeWebSocketAdapter,+ removeConnection,+ shutdownWebSocketAdapter,+} from "../../../apps/api/src/ws/index";++function makeFakeWs() {+ return {+ send: vi.fn(),+ close: vi.fn(),+ readyState: 1,+ raw: undefined,+ url: null,+ protocol: null,+ } as never;+}++describe("broadcastToProject", () => {+ beforeEach(async () => {+ // Ensure no REDIS_URL so InMemoryBroadcastAdapter is used+ delete process.env.REDIS_URL;+ await initializeWebSocketAdapter();+ });++ afterEach(async () => {+ await shutdownWebSocketAdapter();+ });++ it("delivers messages to connected clients after batch timeout", async () => {+ const ws = makeFakeWs();+ const conn = addConnection("proj-1", ws, "user-1", "init-1");++ broadcastToProject("proj-1", {+ type: "TASK_CREATED",+ projectId: "proj-1",+ taskId: "t1",+ });++ // Messages are batched with 100ms timeout+ expect(+ (ws as { send: ReturnType<typeof vi.fn> }).send,+ ).not.toHaveBeenCalled();++ // Wait for batch flush+ await vi.waitFor(+ () => {+ expect(+ (ws as { send: ReturnType<typeof vi.fn> }).send,+ ).toHaveBeenCalled();+ },+ { timeout: 300 },+ );++ const sent = JSON.parse(+ (ws as { send: ReturnType<typeof vi.fn> }).send.mock.calls[0][0],+ );+ expect(sent.type).toBe("TASK_CREATED");+ expect(sent.taskId).toBe("t1");++ removeConnection("proj-1", conn);+ });++ it("excludes connections matching excludeInitiatorId", async () => {+ const ws1 = makeFakeWs();+ const ws2 = makeFakeWs();+ const conn1 = addConnection("proj-1", ws1, "user-1", "init-excluded");+ const conn2 = addConnection("proj-1", ws2, "user-2", "init-other");++ broadcastToProject(+ "proj-1",+ { type: "TASK_UPDATED", projectId: "proj-1" },+ "init-excluded",+ );++ await vi.waitFor(+ () => {+ expect(+ (ws2 as { send: ReturnType<typeof vi.fn> }).send,+ ).toHaveBeenCalled();+ },+ { timeout: 300 },+ );++ expect(+ (ws1 as { send: ReturnType<typeof vi.fn> }).send,+ ).not.toHaveBeenCalled();++ removeConnection("proj-1", conn1);+ removeConnection("proj-1", conn2);+ });++ it("deduplicates messages with the same key in a batch window", async () => {+ const ws = makeFakeWs();+ const conn = addConnection("proj-1", ws, "user-1", "init-1");++ // Send two messages with the same type+taskId — should be deduplicated+ broadcastToProject("proj-1", {+ type: "TASK_UPDATED",+ projectId: "proj-1",+ taskId: "t1",+ });+ broadcastToProject("proj-1", {+ type: "TASK_UPDATED",+ projectId: "proj-1",+ taskId: "t1",+ });++ await vi.waitFor(+ () => {+ expect(+ (ws as { send: ReturnType<typeof vi.fn> }).send,+ ).toHaveBeenCalled();+ },+ { timeout: 300 },+ );++ // Only one message should be delivered (deduplication by message key)+ expect(+ (ws as { send: ReturnType<typeof vi.fn> }).send,+ ).toHaveBeenCalledTimes(1);++ removeConnection("proj-1", conn);+ });++ it("does not deliver to connections on a different project", async () => {+ const ws = makeFakeWs();+ const conn = addConnection("proj-2", ws, "user-1", "init-1");++ broadcastToProject("proj-1", {+ type: "TASK_CREATED",+ projectId: "proj-1",+ });++ // Wait past the batch timeout+ await new Promise((r) => setTimeout(r, 200));++ expect(+ (ws as { send: ReturnType<typeof vi.fn> }).send,+ ).not.toHaveBeenCalled();++ removeConnection("proj-2", conn);+ });++ it("warns when called before adapter initialization", async () => {+ await shutdownWebSocketAdapter();+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});++ broadcastToProject("proj-1", {+ type: "TASK_CREATED",+ projectId: "proj-1",+ });++ expect(warnSpy).toHaveBeenCalledWith(+ "broadcastToProject called before adapter initialization",+ );+ warnSpy.mockRestore();+ });+});diff --git a/tests/api/ws/connections.test.ts b/tests/api/ws/connections.test.tsnew file mode 100644index 000000000..fb24a8cb8--- /dev/null+++ b/tests/api/ws/connections.test.ts@@ -0,0 +1,91 @@+import { afterEach, describe, expect, it, vi } from "vitest";++// We need to mock the events module to prevent side effects from the+// top-level subscribeToEvent calls in ws/index.ts+vi.mock("../../../apps/api/src/events", () => ({+ subscribeToEvent: vi.fn(),+ publishEvent: vi.fn(),+}));++import {+ addConnection,+ removeConnection,+} from "../../../apps/api/src/ws/index";++function makeFakeWs() {+ return {+ send: vi.fn(),+ close: vi.fn(),+ readyState: 1,+ raw: undefined,+ url: null,+ protocol: null,+ } as never;+}++// We access projectConnections indirectly through the exported functions.+// After each test we clean up by removing all connections we added.+const tracked: Array<{+ projectId: string;+ conn: ReturnType<typeof addConnection>;+}> = [];++afterEach(() => {+ for (const { projectId, conn } of tracked) {+ removeConnection(projectId, conn);+ }+ tracked.length = 0;+});++function trackAdd(projectId: string, userId: string, initiatorId: string) {+ const conn = addConnection(projectId, makeFakeWs(), userId, initiatorId);+ tracked.push({ projectId, conn });+ return conn;+}++describe("addConnection / removeConnection", () => {+ it("returns a ProjectConnection object with the provided values", () => {+ const ws = makeFakeWs();+ const conn = addConnection("proj-1", ws, "user-1", "init-1");+ tracked.push({ projectId: "proj-1", conn });++ expect(conn).toEqual({+ ws,+ userId: "user-1",+ initiatorId: "init-1",+ });+ });++ it("allows multiple connections for the same project", () => {+ const c1 = trackAdd("proj-1", "user-1", "init-1");+ const c2 = trackAdd("proj-1", "user-2", "init-2");++ expect(c1).not.toBe(c2);+ // Both should be removable without error+ removeConnection("proj-1", c1);+ removeConnection("proj-1", c2);+ // Remove from tracked since we manually cleaned up+ tracked.length = 0;+ });++ it("allows connections to different projects", () => {+ const c1 = trackAdd("proj-1", "user-1", "init-1");+ const c2 = trackAdd("proj-2", "user-1", "init-1");++ expect(c1).not.toBe(c2);+ });++ it("removeConnection does not throw for unknown project", () => {+ const conn = trackAdd("proj-1", "user-1", "init-1");+ // Remove from a project that doesn't match — should not throw+ expect(() => removeConnection("nonexistent", conn)).not.toThrow();+ });++ it("removeConnection does not throw for already-removed connection", () => {+ const conn = trackAdd("proj-1", "user-1", "init-1");+ removeConnection("proj-1", conn);+ tracked.length = 0;+ // Second removal should be a no-op+ expect(() => removeConnection("proj-1", conn)).not.toThrow();+ });+});diff --git a/tests/api/ws/in-memory-broadcast-adapter.test.ts b/tests/api/ws/in-memory-broadcast-adapter.test.tsnew file mode 100644index 000000000..b00b3a172--- /dev/null+++ b/tests/api/ws/in-memory-broadcast-adapter.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from "vitest";+import type { BroadcastMessage } from "../../../apps/api/src/ws/broadcast-adapter";+import { InMemoryBroadcastAdapter } from "../../../apps/api/src/ws/in-memory-broadcast-adapter";++describe("InMemoryBroadcastAdapter", () => {+ it("delivers published messages to the subscribed handler", async () => {+ const adapter = new InMemoryBroadcastAdapter();+ const received: BroadcastMessage[] = [];++ await adapter.subscribe((msg) => {+ received.push(msg);+ });++ const message: BroadcastMessage = {+ projectId: "project-1",+ message: { type: "TASK_CREATED", projectId: "project-1", taskId: "t1" },+ };++ await adapter.publish(message);++ expect(received).toHaveLength(1);+ expect(received[0]).toEqual(message);+ });++ it("does not throw when publishing without a subscriber", async () => {+ const adapter = new InMemoryBroadcastAdapter();++ await expect(+ adapter.publish({+ projectId: "project-1",+ message: { type: "TASK_CREATED", projectId: "project-1" },+ }),+ ).resolves.toBeUndefined();+ });++ it("passes excludeInitiatorId through to the handler", async () => {+ const adapter = new InMemoryBroadcastAdapter();+ const received: BroadcastMessage[] = [];++ await adapter.subscribe((msg) => {+ received.push(msg);+ });++ await adapter.publish({+ projectId: "p1",+ message: { type: "TASK_UPDATED", projectId: "p1" },+ excludeInitiatorId: "user-abc",+ });++ expect(received[0]?.excludeInitiatorId).toBe("user-abc");+ });++ it("stops delivering messages after shutdown", async () => {+ const adapter = new InMemoryBroadcastAdapter();+ const received: BroadcastMessage[] = [];++ await adapter.subscribe((msg) => {+ received.push(msg);+ });++ await adapter.shutdown();++ await adapter.publish({+ projectId: "p1",+ message: { type: "TASK_DELETED", projectId: "p1" },+ });++ expect(received).toHaveLength(0);+ });++ it("replaces the handler when subscribe is called again", async () => {+ const adapter = new InMemoryBroadcastAdapter();+ const first: BroadcastMessage[] = [];+ const second: BroadcastMessage[] = [];++ await adapter.subscribe((msg) => first.push(msg));+ await adapter.subscribe((msg) => second.push(msg));++ await adapter.publish({+ projectId: "p1",+ message: { type: "TASK_UPDATED", projectId: "p1" },+ });++ expect(first).toHaveLength(0);+ expect(second).toHaveLength(1);+ });+});