import { expect, test, describe, beforeEach, afterEach, mock } from 'bun:test'; import { GameStateManager, GameStateType } from './GameStateManager'; describe('GameStateManager', () => { let gameStateManager: GameStateManager; beforeEach(() => { // Initialize a fresh GameStateManager before each test gameStateManager = new GameStateManager(); }); test('should initialize with a default empty game state', () => { const initialState = gameStateManager.getGameState(); expect(initialState).toEqual({ id: '', board: Array(15).fill(Array(15).fill(null)), currentPlayer: 'black', status: 'waiting', winner: null, players: {}, }); }); test('should update game state from server updates', () => { const serverState = { id: 'game123', board: Array.from({ length: 15 }, () => Array(15).fill(null)), currentPlayer: 'white' as 'black' | 'white', status: 'playing' as 'waiting' | 'playing' | 'finished', winner: null, players: { black: 'playerA', white: 'playerB' }, }; gameStateManager.updateGameState(serverState); expect(gameStateManager.getGameState()).toEqual(serverState); }); test('should handle optimistic updates for making a move', () => { const initialBoard = Array.from({ length: 15 }, () => Array(15).fill(null)); initialBoard[7][7] = 'black'; // Simulate an optimistic move const optimisticState = { id: 'game123', board: initialBoard, currentPlayer: 'white' as 'black' | 'white', // Turn changes optimistically status: 'playing' as 'waiting' | 'playing' | 'finished', winner: null, players: { black: 'playerA', white: 'playerB' }, }; gameStateManager.updateGameState(optimisticState); expect(gameStateManager.getGameState().board[7][7]).toEqual('black'); expect(gameStateManager.getGameState().currentPlayer).toEqual('white'); }); test('should rollback optimistic updates if server rejects move', () => { const initialServerState = { id: 'game123', board: Array.from({ length: 15 }, () => Array(15).fill(null)), currentPlayer: 'black' as 'black' | 'white', status: 'playing' as 'waiting' | 'playing' | 'finished', winner: null, players: { black: 'playerA', white: 'playerB' }, }; gameStateManager.updateGameState(initialServerState); // Optimistic update const optimisticBoard = Array.from({ length: 15 }, () => Array(15).fill(null), ); optimisticBoard[7][7] = 'black'; const optimisticState = { id: 'game123', board: optimisticBoard, currentPlayer: 'white' as 'black' | 'white', status: 'playing' as 'waiting' | 'playing' | 'finished', winner: null, players: { black: 'playerA', white: 'playerB' }, }; gameStateManager.updateGameState(optimisticState); // Server rejection - rollback to initial state gameStateManager.rollbackGameState(); // This method will be implemented expect(gameStateManager.getGameState()).toEqual(initialServerState); }); // Add more tests for: // - Win conditions // - Draw conditions // - Invalid moves (already occupied, out of bounds - though this might be server-side validation primarily) // - Player disconnection/reconnection behavior });