59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
import { describe, expect, test } from "bun:test";
|
|
import * as Y from "yjs";
|
|
import { getOrCreateSession, Session } from "./session";
|
|
|
|
describe("Session", () => {
|
|
test("creates yjs doc on init", () => {
|
|
const session = new Session("test-room");
|
|
expect(session.doc).toBeInstanceOf(Y.Doc);
|
|
expect(session.name).toBe("test-room");
|
|
});
|
|
|
|
test("tracks clients", () => {
|
|
const session = new Session("test-room");
|
|
const mockWs = {
|
|
send: () => {},
|
|
data: { room: null as string | null },
|
|
} as unknown as import("bun").ServerWebSocket<{ room: string | null }>;
|
|
const client = { ws: mockWs };
|
|
|
|
expect(session.clients.size).toBe(0);
|
|
session.join(client);
|
|
expect(session.clients.size).toBe(1);
|
|
session.leave(client);
|
|
expect(session.clients.size).toBe(0);
|
|
});
|
|
|
|
test("applies yjs updates", () => {
|
|
const session = new Session("test-room");
|
|
const text = session.doc.getText("content");
|
|
|
|
// simulate a remote update
|
|
const remoteDoc = new Y.Doc();
|
|
const remoteText = remoteDoc.getText("content");
|
|
remoteText.insert(0, "hello");
|
|
const update = Y.encodeStateAsUpdate(remoteDoc);
|
|
|
|
const mockWs = {
|
|
send: () => {},
|
|
data: { room: null as string | null },
|
|
} as unknown as import("bun").ServerWebSocket<{ room: string | null }>;
|
|
session.applyUpdate(update, { ws: mockWs });
|
|
|
|
expect(text.toString()).toBe("hello");
|
|
});
|
|
});
|
|
|
|
describe("getOrCreateSession", () => {
|
|
test("returns same session for same room", () => {
|
|
const s1 = getOrCreateSession("room-a");
|
|
const s2 = getOrCreateSession("room-a");
|
|
expect(s1).toBe(s2);
|
|
});
|
|
|
|
test("returns different sessions for different rooms", () => {
|
|
const s1 = getOrCreateSession("room-x");
|
|
const s2 = getOrCreateSession("room-y");
|
|
expect(s1).not.toBe(s2);
|
|
});
|
|
});
|