|
| 1 | +import { describe, it, expect, vi } from "vitest"; |
| 2 | +import { ZodNamespace } from "../../src/v3/zodNamespace.js"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { Server } from "socket.io"; |
| 5 | +import { createServer } from "node:http"; |
| 6 | + |
| 7 | +describe("ZodNamespace", () => { |
| 8 | + it("should allow sending messages with the ZodSocketMessageCatalogSchema structure", async () => { |
| 9 | + const io = new Server(createServer()); |
| 10 | + |
| 11 | + const clientMessages = { |
| 12 | + CLIENT_MSG: { |
| 13 | + message: z.object({ foo: z.string() }) |
| 14 | + } |
| 15 | + }; |
| 16 | + |
| 17 | + const serverMessages = { |
| 18 | + SERVER_MSG: { |
| 19 | + message: z.object({ bar: z.number() }) |
| 20 | + } |
| 21 | + }; |
| 22 | + |
| 23 | + const ns = new ZodNamespace({ |
| 24 | + io, |
| 25 | + name: "test", |
| 26 | + clientMessages, |
| 27 | + serverMessages, |
| 28 | + }); |
| 29 | + |
| 30 | + const emitSpy = vi.spyOn(ns.namespace, "emit"); |
| 31 | + |
| 32 | + // This should not throw and should emit the correct payload |
| 33 | + // Currently this might throw or require passing { message: { bar: 1 } } |
| 34 | + await ns.sender.send("SERVER_MSG", { bar: 1 } as any); |
| 35 | + |
| 36 | + expect(emitSpy).toHaveBeenCalledWith("SERVER_MSG", { |
| 37 | + payload: { bar: 1 }, |
| 38 | + version: "v1" |
| 39 | + }); |
| 40 | + }); |
| 41 | + |
| 42 | + it("should support schemas with callbacks if updated", async () => { |
| 43 | + // This test represents the desired state |
| 44 | + const io = new Server(createServer()); |
| 45 | + |
| 46 | + const clientMessages = { |
| 47 | + CLIENT_MSG: { |
| 48 | + message: z.object({ foo: z.string() }), |
| 49 | + callback: z.object({ ok: z.boolean() }) |
| 50 | + } |
| 51 | + }; |
| 52 | + |
| 53 | + const serverMessages = { |
| 54 | + SERVER_MSG: { |
| 55 | + message: z.object({ bar: z.number() }), |
| 56 | + callback: z.object({ success: z.boolean() }) |
| 57 | + } |
| 58 | + } as any; // Cast for now until we update the types |
| 59 | + |
| 60 | + const ns = new ZodNamespace({ |
| 61 | + io, |
| 62 | + name: "test-cb", |
| 63 | + clientMessages, |
| 64 | + serverMessages, |
| 65 | + }); |
| 66 | + |
| 67 | + expect(ns).toBeDefined(); |
| 68 | + }); |
| 69 | +}); |
0 commit comments