The failing tests indicate that certain expected behaviors in your useLobbyData hook are not occurring as intended. Specifically:
-
Error Propagation from useGame:
- Tests expect the
error state in useLobbyData to reflect the error from useGame. However, the current implementation of useLobbyData does not set the error state based on useGame's error.
-
Navigation After Leaving the Game:
- The
leaveGame function is expected to call navigate('/'), but this isn't happening because the mock for useGameStore and usePlayerStore isn’t fully implemented, potentially causing unexpected behavior or errors that prevent the navigation.
-
Additional Mocking for useGameStore and usePlayerStore:
- The
useGameStore is used in the hook but isn’t mocked in the tests, which might lead to undefined behavior during tests.
To address these issues, follow these steps:
1. Update the useLobbyData Hook to Propagate Errors from useGame
Modify the useLobbyData hook to set its internal error state based on the error from useGame. This ensures that when useGame encounters an error (e.g., invalid game ID, game not found), the hook's error state reflects this, allowing tests to pass as expected.
Updated useLobbyData.tsx:
import { 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 { useGame } from '../../contexts/GameContext';
import { useNavigate } from 'react-router-dom';
import useGameStore from '../../store/useGameStore';
const useLobbyData = () => {
const { gameId, gameData, error: gameError } = useGame(); // Destructure error from 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();
useEffect(() => {
if (gameError) { // Set the local error state based on useGame's error
setError(gameError);
} else {
setError(null); // Clear any existing errors if there's no game error
}
if (gameData) {
setPlayers(gameData.teams?.flatMap((team) => team.players) || []);
setIsHost(gameData.createdBy === currentPlayer);
} else {
setPlayers([]);
setIsHost(false);
}
}, [gameData, currentPlayer, gameError]); // Add gameError to dependencies
// ... rest of the hook remains unchanged
};
export default useLobbyData;
Explanation:
- Destructure
error from useGame: This allows the hook to be aware of any errors reported by the useGame context.
- Update the
useEffect Hook: Inside the useEffect, check if there's an error from useGame. If so, set the local error state; otherwise, clear it.
- Update Dependencies: Ensure that
gameError is included in the dependency array so that the effect runs whenever the game's error state changes.
2. Mock useGameStore and usePlayerStore Properly in Tests
The leaveGame and other functions rely on useGameStore and usePlayerStore to perform actions like clearing the game ID and player name. These stores should be mocked to ensure that these actions don't cause unexpected behavior during tests.
Update your test file to include mocks for useGameStore:
// Add this mock at the top along with other mocks
vi.mock('../../store/useGameStore', () => ({
__esModule: true,
default: {
getState: () => ({
clearGameId: vi.fn(),
}),
},
}));
// Similarly, update usePlayerStore mock if clearName is called
vi.mock('../../store/usePlayerStore', () => ({
__esModule: true,
default: vi.fn(),
getState: () => ({
clearName: vi.fn(),
}),
}));
Explanation:
- Mock
useGameStore: Ensure that getState().clearGameId is a mock function that can be called without causing errors.
- Update
usePlayerStore Mock: If clearName is an action invoked within leaveGame, ensure it's also mocked to prevent unexpected behavior.
3. Ensure useGame Context Includes error
Ensure that your useGame context provides the error property. If it doesn't, you need to update the context to include it.
Example useGame Context Update (if necessary):
// Assuming useGame is defined like this
interface GameContextType {
gameId: string;
gameData: GameData | null;
error: string | null; // Add this line
}
const GameContext = React.createContext<GameContextType>({
gameId: '',
gameData: null,
error: null, // Initialize error
});
// Ensure the provider sets the error appropriately
Explanation:
- The
useGame context needs to provide an error field that reflects any issues encountered while fetching or managing game data.
4. Fix the Specific Test Issues
After updating the hook and mocks, the existing tests should pass. However, ensure that all tests are correctly set up to reflect the changes.
A. Fix should handle invalid gameId gracefully Test:
Original Test Error:
AssertionError: expected null to be 'Invalid game ID.'
Reason:
The hook wasn’t setting the error state based on useGame's error.
Solution:
With the updated hook, this test should now pass as the error state is correctly set.
B. Fix should leave the game successfully Test:
Original Test Error:
AssertionError: expected "spy" to be called with arguments: [ '/' ]
Received:
Number of calls: 0
Reason:
navigate('/') wasn’t called because either the mocked useGameStore or usePlayerStore wasn't correctly set up, causing the hook to potentially throw an error before reaching the navigation step.
Solution:
With the updated mocks for useGameStore and usePlayerStore, ensure that clearGameId and clearName are properly mocked to prevent unintended behavior. The navigation should now occur as expected.
C. Fix should handle game not found and should handle error in fetching game data Tests:
Original Test Errors:
AssertionError: expected null to be 'Game not found.'
AssertionError: expected null to be 'Failed to fetch game data.'
Reason:
Similar to the first issue, the hook wasn’t propagating useGame's error to its own error state.
Solution:
With the updated hook that sets the error state based on useGame's error, these tests should pass.
D. Fix should navigate to game screen when game status changes to in-progress Test:
Original Test Error:
AssertionError: expected "spy" to be called with arguments: [ '/game/testGameId' ]
Received:
Number of calls: 0
Reason:
The useNavigate mock wasn't being triggered because the state change in useGame wasn't causing a re-render or the hook wasn't set up to detect the change properly.
Solution:
Ensure that after updating the mock return value of useGame, the component re-renders to detect the state change. Additionally, consider using rerender or triggering the relevant effect manually if necessary.
Updated Test Example:
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, rerender } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
// Initial render with 'waiting' status
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: {
id: mockGameId,
status: 'waiting',
teams: [],
createdBy: 'SomeoneElse',
},
error: null,
});
rerender();
// Update to 'in-progress' status
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: {
id: mockGameId,
status: 'in-progress',
teams: [],
createdBy: 'SomeoneElse',
},
error: null,
});
rerender();
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith(`/game/${mockGameId}`);
});
});
Explanation:
- Use
rerender: After changing the mock return value of useGame, call rerender to ensure the hook picks up the new value.
- Wait for Navigation: Use
waitFor to allow asynchronous effects to complete before asserting that navigate was called.
5. Final Updated Test File
Here is the updated useLobbyData.test.tsx with all necessary fixes:
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 useGameStore from '../../store/useGameStore'; // Import useGameStore
import { BrowserRouter } from 'react-router-dom';
import { useGame } from '../../contexts/GameContext';
// Mock usePlayerStore
vi.mock('../../store/usePlayerStore', () => ({
__esModule: true,
default: vi.fn(),
getState: () => ({
clearName: vi.fn(),
}),
}));
// Mock useGameStore
vi.mock('../../store/useGameStore', () => ({
__esModule: true,
default: {
getState: () => ({
clearGameId: vi.fn(),
}),
},
}));
// Mock react-router-dom
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: 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 vi.Mock;
const mockUseGameStore = useGameStore as unknown as {
getState: () => { clearGameId: () => void };
};
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, rerender } = renderHook(() => useLobbyData(), {
wrapper: BrowserRouter,
});
// Initial render with 'waiting' status
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: {
id: mockGameId,
status: 'waiting',
teams: [],
createdBy: 'SomeoneElse',
},
error: null,
});
rerender();
// Update to 'in-progress' status
mockUseGame.mockReturnValue({
gameId: mockGameId,
gameData: {
id: mockGameId,
status: 'in-progress',
teams: [],
createdBy: 'SomeoneElse',
},
error: null,
});
rerender();
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.');
});
});
Key Changes:
- Mocked
useGameStore and usePlayerStore Properly: Ensured that clearGameId and clearName are mocked to prevent errors during leaveGame.
- Updated Hook to Handle
useGame Errors: The useLobbyData hook now correctly sets the error state based on useGame's error.
- Updated Tests to Use
rerender: For tests that involve state changes (like navigation when game status changes), the hook is re-rendered after updating the mock to ensure effects run correctly.
6. Additional Recommendations
- Ensure Consistent Mock Implementations: Whenever you use stores or contexts, ensure that all necessary functions and state are mocked to prevent unintended behavior.
- Use Type Assertions Carefully: Ensure that type assertions (like
as vi.Mock) accurately reflect the intended mock behavior to avoid type mismatches or runtime errors.
- Maintain Clear Separation of Concerns: Keep your hooks modular and ensure that their dependencies are well-defined and consistently mocked in tests.
By implementing these changes, your tests should pass successfully, accurately reflecting the intended behavior of the useLobbyData hook.