import { beforeEach, describe, expect, it } from 'vitest'; import { clearLobby, getLobby, patchLobbyGame, setLobby } from './lobbycache'; import type { AccountRef, GameView } from './model'; function gameView(id: string, status: GameView['status'] = 'active', toMove = 0): GameView { return { id, variant: 'scrabble_en', dictVersion: 'v1', status, players: 2, toMove, turnTimeoutSecs: 300, multipleWordsPerTurn: true, moveCount: 0, endReason: '', lastActivityUnix: 0, seats: [], }; } beforeEach(() => clearLobby()); describe('patchLobbyGame', () => { it('replaces the matching game by id and leaves the others untouched', () => { setLobby({ games: [gameView('a', 'active', 0), gameView('b', 'active', 0)], invitations: [], incoming: [] }); // The player's own move flipped game "a" to the opponent's turn. patchLobbyGame(gameView('a', 'active', 1)); const snap = getLobby(); expect(snap?.games.map((g) => g.id)).toEqual(['a', 'b']); expect(snap?.games.find((g) => g.id === 'a')?.toMove).toBe(1); expect(snap?.games.find((g) => g.id === 'b')?.toMove).toBe(0); }); it('preserves invitations and incoming when patching a game', () => { const incoming: AccountRef[] = [{ accountId: 'u9', displayName: 'Nine' }]; setLobby({ games: [gameView('a')], invitations: [], incoming }); patchLobbyGame(gameView('a', 'finished')); expect(getLobby()?.incoming).toEqual(incoming); expect(getLobby()?.games[0].status).toBe('finished'); }); it('adds the game when it is not yet in the cached lobby (a game started elsewhere)', () => { setLobby({ games: [gameView('a')], invitations: [], incoming: [] }); patchLobbyGame(gameView('z', 'active')); // Order is irrelevant — the lobby re-groups and re-sorts on render — so assert membership. expect(getLobby()?.games.map((g) => g.id).sort()).toEqual(['a', 'z']); }); it('is a no-op when there is no cached lobby yet', () => { patchLobbyGame(gameView('a')); expect(getLobby()).toBeNull(); }); it('does not mutate the previous snapshot array', () => { const games = [gameView('a', 'active', 0)]; setLobby({ games, invitations: [], incoming: [] }); patchLobbyGame(gameView('a', 'active', 1)); expect(games[0].toMove).toBe(0); // the original array/object is left intact }); });