src\pages\lobbyScreen\useLobbyData.test.tsx [code]…
- User
src\pages\lobbyScreen\useLobbyData.test.tsx
typescript - Assistant
import { renderHook, act, waitFor } from '@testing-library/react';
import { vi } from 'vitest';
import useLobbyData from './useLobbyData';
import { doc, updateDoc } from 'firebase/firestore';
import { httpsCallable } from 'firebase/functions';
import usePlayerStore from '../../store/usePlayerStore';
import { BrowserRouter, useNavigate } from 'react-router-dom';
import { useGame } from '../../contexts/GameContext';
vi.mock('../../store/usePlayerStore', () => ({
__esModule: true,
default: vi.fn(),
}));
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: vi.fn(),
};
});
vi.mock('../../contexts/GameContext', () => ({
useGame: vi.fn(),
}));
describe('useLobbyData Hook', () => {
const mockGameId = 'testGameId';
const mockPlayerStore = usePlayerStore as unknown as vi.Mock;
const mockUseGame = useGame as jest.Mock;
beforeEach(() => {
vi.resetAllMocks();
mockPlayerStore.mockImplementation((selector: (state: { name: string }) => string) => {
return selector({ name: 'TestPlayer' });
});
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: null,
});
});
it('should initialize correctly with game data', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
numberOfTeams: 2,
playersPerTeam: 2,
numberOfRounds: 3,
jokerUsage: true,
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.players).toEqual(mockGameData.teams.flatMap(team => team.players));
expect(result.current.isHost).toBe(true);
expect(result.current.error).toBeNull();
});
});
it('should update player status successfully', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
(doc as vi.Mock).mockReturnValue('docRef');
(updateDoc as vi.Mock).mockResolvedValue(null);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('TestPlayer', true);
});
expect(updateDoc).toHaveBeenCalledWith('docRef', {
'teams.0.players.0.isReady': true,
});
expect(result.current.error).toBeNull();
});
it('should handle updatePlayerStatus error correctly', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
(doc as vi.Mock).mockReturnValue('docRef');
(updateDoc as vi.Mock).mockRejectedValue(new Error('Update failed'));
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('TestPlayer', true);
});
expect(updateDoc).toHaveBeenCalledWith('docRef', {
'teams.0.players.0.isReady': true,
});
expect(result.current.error).toBe('Failed to update player status.');
});
it('should handle invalid player name in updatePlayerStatus', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('NonExistentPlayer', true);
});
expect(updateDoc).not.toHaveBeenCalled();
expect(result.current.error).toBe('Player not found.');
});
it('should handle invalid gameId gracefully', async () => {
mockUseGame.mockReturnValue({
gameId: '',
gameData: null,
error: 'Invalid game ID.',
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.error).toBe('Invalid game ID.');
expect(result.current.players).toEqual([]);
});
});
it('should leave the game successfully', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockLeaveGameFunction = vi.fn().mockResolvedValue({ data: { message: 'Successfully left the game.' } });
(httpsCallable as vi.Mock).mockReturnValue(mockLeaveGameFunction);
const mockNavigate = vi.fn();
(useNavigate as vi.Mock).mockReturnValue(mockNavigate);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.leaveGame();
});
expect(httpsCallable).toHaveBeenCalledWith(expect.anything(), 'leaveGame');
expect(mockLeaveGameFunction).toHaveBeenCalledWith({ gameId: mockGameId, playerName: 'TestPlayer' });
expect(mockNavigate).toHaveBeenCalledWith('/');
expect(result.current.error).toBeNull();
});
it('should start the game successfully', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockStartGameFunction = vi.fn().mockResolvedValue({ data: { message: 'Game started successfully.' } });
(httpsCallable as vi.Mock).mockReturnValue(mockStartGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.startGame();
});
expect(httpsCallable).toHaveBeenCalledWith(expect.anything(), 'startGame');
expect(mockStartGameFunction).toHaveBeenCalledWith({ gameId: mockGameId });
expect(result.current.error).toBeNull();
expect(result.current.isStartingGame).toBe(false);
});
it('should handle startGame error correctly', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockStartGameFunction = vi.fn().mockRejectedValue(new Error('Start game failed'));
(httpsCallable as vi.Mock).mockReturnValue(mockStartGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.startGame();
});
expect(httpsCallable).toHaveBeenCalledWith(expect.anything(), 'startGame');
expect(mockStartGameFunction).toHaveBeenCalledWith({ gameId: mockGameId });
expect(result.current.error).toBe('Failed to start the game.');
expect(result.current.isStartingGame).toBe(false);
});
it('should handle game not found', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: 'Game not found.',
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.error).toBe('Game not found.');
expect(result.current.players).toEqual([]);
});
});
it('should handle error in fetching game data', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: 'Failed to fetch game data.',
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.error).toBe('Failed to fetch game data.');
expect(result.current.players).toEqual([]);
});
});
it('should navigate to game screen when game status changes to in-progress', async () => {
const mockNavigate = vi.fn();
(useNavigate as vi.Mock).mockReturnValue(mockNavigate);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
act(() => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: {
id: mockGameId,
status: 'in-progress',
teams: [],
createdBy: 'SomeoneElse',
},
error: null,
});
});
expect(mockNavigate).toHaveBeenCalledWith(`/game/${mockGameId}`);
});
it('should not allow non-host to start the game', async () => {
const mockGameData = {
id: mockGameId,
teams: [{ teamName: 'Team 1', players: [{ name: 'TestPlayer', isReady: false }] }],
createdBy: 'SomeoneElse',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockStartGameFunction = vi.fn();
(httpsCallable as vi.Mock).mockReturnValue(mockStartGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.isHost).toBe(false);
});
await act(async () => {
await result.current.startGame();
});
expect(mockStartGameFunction).not.toHaveBeenCalled();
});
it('should handle error when leaving game', async () => {
const mockGameData = {
id: mockGameId,
teams: [{ teamName: 'Team 1', players: [{ name: 'TestPlayer', isReady: false }] }],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockLeaveGameFunction = vi.fn().mockRejectedValue(new Error('Leave game failed'));
(httpsCallable as vi.Mock).mockReturnValue(mockLeaveGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.leaveGame();
});
expect(result.current.error).toBe('Failed to leave the game.');
});
it('should handle game data not available when updating player status', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('TestPlayer', true);
});
expect(result.current.error).toBe('Game data is not available.');
});
});
import { useState, useEffect } from 'react';
import { updateDoc } from 'firebase/firestore';
import { db } from '../../firebase/config';
import { Player } from '../../types';
import usePlayerStore from '../../store/usePlayerStore';
import { httpsCallable } from 'firebase/functions';
import { functions } from '../../firebase/config';
import { useGame } from '../../contexts/GameContext';
const useLobbyData = () => {
const { gameId, gameData } = useGame();
const [players, setPlayers] = useState<Player[]>([]);
const [isHost, setIsHost] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isStartingGame, setIsStartingGame] = useState(false);
const currentPlayer = usePlayerStore((state) => state.name);
useEffect(() => {
if (gameData) {
setPlayers(gameData.teams?.flatMap((team) => team.players) || []);
setIsHost(gameData.createdBy === currentPlayer);
} else {
setPlayers([]);
setIsHost(false);
}
}, [gameData, currentPlayer]);
const updatePlayerStatus = async (playerName: string, isReady: boolean) => {
if (!gameData) {
setError('Game data is not available.');
return;
}
const teamIndex = getPlayerTeamIndex(playerName);
const playerIndex = getPlayerIndex(playerName);
if (teamIndex === -1 || playerIndex === -1) {
setError('Player not found.');
return;
}
const updatePath = `teams.${teamIndex}.players.${playerIndex}.isReady`;
try {
await updateDoc(doc(db, 'games', gameId!), {
[updatePath]: isReady,
});
} catch (err) {
console.error('Error updating player status:', err);
setError('Failed to update player status.');
}
};
const startGame = async () => {
if (!isHost) return;
setIsStartingGame(true);
try {
const startGameFunction = httpsCallable(functions, 'startGame');
await startGameFunction({ gameId });
} catch (err) {
console.error('Error starting game:', err);
setError('Failed to start the game.');
} finally {
setIsStartingGame(false);
}
};
// Helper functions to find player's team and index
const getPlayerTeamIndex = (playerName: string): number => {
return gameData?.teams.findIndex((team) =>
team.players.some((player) => player.name === playerName)
) ?? -1;
};
const getPlayerIndex = (playerName: string): number => {
const teamIndex = getPlayerTeamIndex(playerName);
return gameData?.teams[teamIndex]?.players.findIndex((player) => player.name === playerName) ?? -1;
};
return { players, isHost, error, isStartingGame, updatePlayerStatus, startGame };
};
export default useLobbyData;
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 8 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should update player status successfully AssertionError: expected "spy" to be called with arguments: [ 'docRef', { …(1) } ]
Received:
Number of calls: 0
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:108:27 106| }); 107| 108| expect(updateDoc).toHaveBeenCalledWith('docRef', { | ^ 109| 'teams.0.players.0.isReady': true, 110| });
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should handle updatePlayerStatus error correctly AssertionError: expected "spy" to be called with arguments: [ 'docRef', { …(1) } ]
Received:
Number of calls: 0
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:145:27 143| }); 144| 145| expect(updateDoc).toHaveBeenCalledWith('docRef', { | ^ 146| 'teams.0.players.0.isReady': true, 147| });
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should handle invalid gameId gracefully AssertionError: expected null to be 'Invalid game ID.' // Object.is equality
Ignored nodes: comments, script, style
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:195:42 193| 194| await waitFor(() => { 195| expect(result.current.error).toBe('Invalid game ID.'); | ^ 196| expect(result.current.players).toEqual([]); 197| }); ❯ runWithExpensiveErrorDiagnosticsDisabled node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/config.js:47:12 ❯ checkCallback node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:127:77 ❯ Timeout.checkRealTimersCallback node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:121:16
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should leave the game successfully
TypeError: result.current.leaveGame is not a function
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:230:34
228|
229| await act(async () => {
230| await result.current.leaveGame();
| ^
231| });
232|
❯ node_modules/@testing-library/react/dist/act-compat.js:64:24
❯ act node_modules/react/cjs/react.development.js:2512:16
❯ actWithWarning node_modules/react-dom/cjs/react-dom-test-utils.development.js:1740:10
❯ Proxy. node_modules/@testing-library/react/dist/act-compat.js:63:25
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:229:15
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should handle game not found AssertionError: expected null to be 'Game not found.' // Object.is equality
Ignored nodes: comments, script, style
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:323:42 321| 322| await waitFor(() => { 323| expect(result.current.error).toBe('Game not found.'); | ^ 324| expect(result.current.players).toEqual([]); 325| }); ❯ runWithExpensiveErrorDiagnosticsDisabled node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/config.js:47:12 ❯ checkCallback node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:127:77 ❯ Timeout.checkRealTimersCallback node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:121:16
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[5/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should handle error in fetching game data AssertionError: expected null to be 'Failed to fetch game data.' // Object.is equality
Ignored nodes: comments, script, style
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:340:42 338| 339| await waitFor(() => { 340| expect(result.current.error).toBe('Failed to fetch game data.'); | ^ 341| expect(result.current.players).toEqual([]); 342| }); ❯ runWithExpensiveErrorDiagnosticsDisabled node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/config.js:47:12 ❯ checkCallback node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:127:77 ❯ Timeout.checkRealTimersCallback node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:121:16
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[6/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should navigate to game screen when game status changes to in-progress AssertionError: expected "spy" to be called with arguments: [ '/game/testGameId' ]
Received:
Number of calls: 0
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:366:30
364| });
365|
366| expect(mockNavigate).toHaveBeenCalledWith(/game/${mockGameId});
| ^
367| });
368|
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[7/8]⎯
FAIL src/pages/lobbyScreen/useLobbyData.test.tsx > useLobbyData Hook > should handle error when leaving game
TypeError: result.current.leaveGame is not a function
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:423:34
421|
422| await act(async () => {
423| await result.current.leaveGame();
| ^
424| });
425|
❯ node_modules/@testing-library/react/dist/act-compat.js:64:24
❯ act node_modules/react/cjs/react.development.js:2512:16
❯ actWithWarning node_modules/react-dom/cjs/react-dom-test-utils.development.js:1740:10
❯ Proxy. node_modules/@testing-library/react/dist/act-compat.js:63:25
❯ src/pages/lobbyScreen/useLobbyData.test.tsx:422:15
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[8/8]⎯ fix these tests
The failing tests in your useLobbyData.test.tsx file primarily stem from two main issues:
Missing leaveGame Function in the Hook:
leaveGame function from the useLobbyData hook, but the current implementation of the hook does not include this function. This absence leads to errors like TypeError: result.current.leaveGame is not a function.Incomplete Mocking of Firebase Functions:
doc and updateDoc from firebase/firestore, are not properly mocked. This causes tests that rely on these functions to fail because they aren't being tracked or behaving as expected in the testing environment.To resolve these issues, follow the steps below:
leaveGame Function in useLobbyData HookYour tests expect leaveGame to be part of the hook's return value. To align the hook with the tests, you need to implement and return the leaveGame function. Here's how you can modify the useLobbyData hook:
useLobbyData.tsximport { useState, useEffect } from 'react';
import { updateDoc, doc } from 'firebase/firestore';
import { db, functions } from '../../firebase/config';
import { Player } from '../../types';
import usePlayerStore from '../../store/usePlayerStore';
import { httpsCallable } from 'firebase/functions';
import { useNavigate } from 'react-router-dom'; // Import useNavigate
import { useGame } from '../../contexts/GameContext';
const useLobbyData = () => {
const { gameId, gameData, error: gameError } = useGame();
const [players, setPlayers] = useState<Player[]>([]);
const [isHost, setIsHost] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isStartingGame, setIsStartingGame] = useState(false);
const currentPlayer = usePlayerStore((state) => state.name);
const navigate = useNavigate(); // Initialize navigate
useEffect(() => {
if (gameData) {
setPlayers(gameData.teams?.flatMap((team) => team.players) || []);
setIsHost(gameData.createdBy === currentPlayer);
setError(gameError); // Set error from useGame
} else {
setPlayers([]);
setIsHost(false);
setError(gameError); // Set error from useGame
}
}, [gameData, currentPlayer, gameError]);
const updatePlayerStatus = async (playerName: string, isReady: boolean) => {
if (!gameData) {
setError('Game data is not available.');
return;
}
const teamIndex = getPlayerTeamIndex(playerName);
const playerIndex = getPlayerIndex(playerName);
if (teamIndex === -1 || playerIndex === -1) {
setError('Player not found.');
return;
}
const updatePath = `teams.${teamIndex}.players.${playerIndex}.isReady`;
try {
await updateDoc(doc(db, 'games', gameId!), {
[updatePath]: isReady,
});
} catch (err) {
console.error('Error updating player status:', err);
setError('Failed to update player status.');
}
};
const startGame = async () => {
if (!isHost) return;
setIsStartingGame(true);
try {
const startGameFunction = httpsCallable(functions, 'startGame');
await startGameFunction({ gameId });
} catch (err) {
console.error('Error starting game:', err);
setError('Failed to start the game.');
} finally {
setIsStartingGame(false);
}
};
const leaveGame = async () => {
try {
const leaveGameFunction = httpsCallable(functions, 'leaveGame');
await leaveGameFunction({ gameId, playerName: currentPlayer });
navigate('/'); // Navigate to home or appropriate route after leaving
} catch (err) {
console.error('Error leaving game:', err);
setError('Failed to leave the game.');
}
};
// Helper functions to find player's team and index
const getPlayerTeamIndex = (playerName: string): number => {
return gameData?.teams.findIndex((team) =>
team.players.some((player) => player.name === playerName)
) ?? -1;
};
const getPlayerIndex = (playerName: string): number => {
const teamIndex = getPlayerTeamIndex(playerName);
return gameData?.teams[teamIndex]?.players.findIndex((player) => player.name === playerName) ?? -1;
};
// Navigate to game screen when game status changes to 'in-progress'
useEffect(() => {
if (gameData?.status === 'in-progress') {
navigate(`/game/${gameId}`);
}
}, [gameData, gameId, navigate]);
return { players, isHost, error, isStartingGame, updatePlayerStatus, startGame, leaveGame };
};
export default useLobbyData;
Key Changes:
leaveGame: This function uses httpsCallable to call the leaveGame Firebase function, and upon success, navigates the user to the home screen.leaveGame in the Return Object: Ensures that the tests can access and call leaveGame.useEffect to navigate to the game screen when the game status changes to 'in-progress'.useGame: Ensures that any errors from useGame are reflected in the hook's error state.To ensure that Firebase functions like doc, updateDoc, and httpsCallable are properly mocked and their calls are tracked, you need to mock them at the beginning of your test file.
useLobbyData.test.tsxKey Changes:
Properly Mocked Firebase Firestore and Functions:
doc and updateDoc):
vi.mock('firebase/firestore', () => ({
doc: vi.fn(),
updateDoc: vi.fn(),
}));
httpsCallable):
vi.mock('firebase/functions', () => ({
httpsCallable: vi.fn(),
}));
Mocked useNavigate Correctly:
const mockNavigate = vi.fn();
beforeEach(() => {
vi.resetAllMocks();
// ... other mocks
// Mock useNavigate to return the mockNavigate function
const { useNavigate } = require('react-router-dom');
useNavigate.mockReturnValue(mockNavigate);
});
Adjusted Test Cases to Align with Hook Implementation:
doc and updateDoc are called with the correct arguments.leaveGame:
httpsCallable to simulate both success and failure scenarios.mockNavigate is called appropriately after leaving the game.useGame are correctly propagated and tested.Used act and waitFor Correctly:
act to ensure state updates are handled properly.waitFor to wait for asynchronous state changes before making assertions.Consistent Mocking: Ensure that all external dependencies are consistently mocked. This includes any modules or functions that your hook relies on, such as Firebase services, navigation, and state management stores.
Spy on Console Errors (Optional): To avoid cluttering test outputs with console errors, you can spy on console.error and mute them during tests. This is optional but can be useful for cleaner test outputs.
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
(console.error as jest.Mock).mockRestore();
});
Ensure Accurate Mock Implementations: Double-check that your mock implementations accurately reflect the behavior of the actual functions, especially in terms of return values and side effects.
Review Hook Dependencies: Ensure that all dependencies used within the useLobbyData hook are correctly mocked and provided during testing.
By implementing the leaveGame function in your hook and properly mocking all external dependencies, your tests should pass as expected. Ensure that the hook's implementation aligns with what your tests are asserting, and always keep your tests updated to reflect any changes in the hook's behavior or returned values.
Not yet included in a published release.
import { renderHook, act, waitFor } from '@testing-library/react';
import { vi } from 'vitest';
import useLobbyData from './useLobbyData';
import { doc, updateDoc } from 'firebase/firestore';
import { httpsCallable } from 'firebase/functions';
import usePlayerStore from '../../store/usePlayerStore';
import { BrowserRouter } from 'react-router-dom';
import { useGame } from '../../contexts/GameContext';
import { functions } from '../../firebase/config';
// Mock Firebase Firestore
vi.mock('firebase/firestore', () => ({
doc: vi.fn(),
updateDoc: vi.fn(),
}));
// Mock Firebase Functions
vi.mock('firebase/functions', () => ({
httpsCallable: vi.fn(),
}));
// Mock react-router-dom's useNavigate
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: vi.fn(),
};
});
// Mock usePlayerStore
vi.mock('../../store/usePlayerStore', () => ({
__esModule: true,
default: vi.fn(),
}));
// Mock useGame
vi.mock('../../contexts/GameContext', () => ({
useGame: vi.fn(),
}));
describe('useLobbyData Hook', () => {
const mockGameId = 'testGameId';
const mockPlayerStore = usePlayerStore as unknown as vi.Mock;
const mockUseGame = useGame as unknown as vi.Mock;
const mockNavigate = vi.fn();
beforeEach(() => {
vi.resetAllMocks();
// Mock usePlayerStore to return the current player's name
mockPlayerStore.mockImplementation((selector: (state: { name: string }) => string) => {
return selector({ name: 'TestPlayer' });
});
// Mock useNavigate to return the mockNavigate function
const { useNavigate } = require('react-router-dom');
useNavigate.mockReturnValue(mockNavigate);
// Default mock for useGame
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: null,
});
});
it('should initialize correctly with game data', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
numberOfTeams: 2,
playersPerTeam: 2,
numberOfRounds: 3,
jokerUsage: true,
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.players).toEqual(mockGameData.teams.flatMap(team => team.players));
expect(result.current.isHost).toBe(true);
expect(result.current.error).toBeNull();
});
});
it('should update player status successfully', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
(doc as vi.Mock).mockReturnValue('docRef');
(updateDoc as vi.Mock).mockResolvedValue(null);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('TestPlayer', true);
});
expect(doc).toHaveBeenCalledWith(db, 'games', mockGameId);
expect(updateDoc).toHaveBeenCalledWith('docRef', {
'teams.0.players.0.isReady': true,
});
expect(result.current.error).toBeNull();
});
it('should handle updatePlayerStatus error correctly', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
(doc as vi.Mock).mockReturnValue('docRef');
(updateDoc as vi.Mock).mockRejectedValue(new Error('Update failed'));
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('TestPlayer', true);
});
expect(doc).toHaveBeenCalledWith(db, 'games', mockGameId);
expect(updateDoc).toHaveBeenCalledWith('docRef', {
'teams.0.players.0.isReady': true,
});
expect(result.current.error).toBe('Failed to update player status.');
});
it('should handle invalid player name in updatePlayerStatus', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('NonExistentPlayer', true);
});
expect(updateDoc).not.toHaveBeenCalled();
expect(result.current.error).toBe('Player not found.');
});
it('should handle invalid gameId gracefully', async () => {
mockUseGame.mockReturnValue({
gameId: '',
gameData: null,
error: 'Invalid game ID.',
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.error).toBe('Invalid game ID.');
expect(result.current.players).toEqual([]);
});
});
it('should leave the game successfully', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockLeaveGameFunction = vi.fn().mockResolvedValue({ data: { message: 'Successfully left the game.' } });
(httpsCallable as vi.Mock).mockReturnValue(mockLeaveGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.leaveGame();
});
expect(httpsCallable).toHaveBeenCalledWith(functions, 'leaveGame');
expect(mockLeaveGameFunction).toHaveBeenCalledWith({ gameId: mockGameId, playerName: 'TestPlayer' });
expect(mockNavigate).toHaveBeenCalledWith('/');
expect(result.current.error).toBeNull();
});
it('should start the game successfully', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockStartGameFunction = vi.fn().mockResolvedValue({ data: { message: 'Game started successfully.' } });
(httpsCallable as vi.Mock).mockReturnValue(mockStartGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.startGame();
});
expect(httpsCallable).toHaveBeenCalledWith(functions, 'startGame');
expect(mockStartGameFunction).toHaveBeenCalledWith({ gameId: mockGameId });
expect(result.current.error).toBeNull();
expect(result.current.isStartingGame).toBe(false);
});
it('should handle startGame error correctly', async () => {
const mockGameData = {
id: mockGameId,
teams: [
{
teamName: 'Team 1',
players: [{ name: 'TestPlayer', isReady: false }],
},
],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockStartGameFunction = vi.fn().mockRejectedValue(new Error('Start game failed'));
(httpsCallable as vi.Mock).mockReturnValue(mockStartGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.startGame();
});
expect(httpsCallable).toHaveBeenCalledWith(functions, 'startGame');
expect(mockStartGameFunction).toHaveBeenCalledWith({ gameId: mockGameId });
expect(result.current.error).toBe('Failed to start the game.');
expect(result.current.isStartingGame).toBe(false);
});
it('should handle game not found', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: 'Game not found.',
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.error).toBe('Game not found.');
expect(result.current.players).toEqual([]);
});
});
it('should handle error in fetching game data', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: 'Failed to fetch game data.',
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.error).toBe('Failed to fetch game data.');
expect(result.current.players).toEqual([]);
});
});
it('should navigate to game screen when game status changes to in-progress', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: {
id: mockGameId,
status: 'in-progress',
teams: [],
createdBy: 'SomeoneElse',
},
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith(`/game/${mockGameId}`);
});
});
it('should not allow non-host to start the game', async () => {
const mockGameData = {
id: mockGameId,
teams: [{ teamName: 'Team 1', players: [{ name: 'TestPlayer', isReady: false }] }],
createdBy: 'SomeoneElse',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockStartGameFunction = vi.fn();
(httpsCallable as vi.Mock).mockReturnValue(mockStartGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await waitFor(() => {
expect(result.current.isHost).toBe(false);
});
await act(async () => {
await result.current.startGame();
});
expect(mockStartGameFunction).not.toHaveBeenCalled();
});
it('should handle error when leaving game', async () => {
const mockGameData = {
id: mockGameId,
teams: [{ teamName: 'Team 1', players: [{ name: 'TestPlayer', isReady: false }] }],
createdBy: 'TestPlayer',
status: 'waiting',
};
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: mockGameData,
error: null,
});
const mockLeaveGameFunction = vi.fn().mockRejectedValue(new Error('Leave game failed'));
(httpsCallable as vi.Mock).mockReturnValue(mockLeaveGameFunction);
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.leaveGame();
});
expect(result.current.error).toBe('Failed to leave the game.');
});
it('should handle game data not available when updating player status', async () => {
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: null,
error: null,
});
const { result } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
await act(async () => {
await result.current.updatePlayerStatus('TestPlayer', true);
});
expect(result.current.error).toBe('Game data is not available.');
});
});