import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { vi } from 'vitest';
import JoinGame from './JoinGame';
import { httpsCallable } from 'firebase/functions';
import { ensureAnonymousAuth } from '../../firebase/auth/auth';
import usePlayerStore from '../../store/usePlayerStore';
// Mock the dependencies
vi.mock('firebase/functions');
vi.mock('../../firebase/auth/auth');
vi.mock('../../store/usePlayerStore');
const validateGameCode = (code: string): boolean => {
// Game code should be 6 characters long and alphanumeric
const gameCodeRegex = /^[A-Za-z0-9]{6}$/;
return gameCodeRegex.test(code);
};
if (!validateGameCode(gameCode)) {
setError('Invalid game code. Please enter a 6-character alphanumeric code.');
return;
}
if (!playerName) {
setError('Please set your name before joining a game.');
return;
}
setIsLoading(true);
try {
await ensureAnonymousAuth();
const joinGameFunction = httpsCallable(functions, 'joinGame');
const result = await joinGameFunction({ gameCode, playerName });
const data = result.data as { gameId: string };
navigate(`/game-lobby/${data.gameId}`, { state: { gameCode } });
} catch (err: any) {
console.error('Error joining game:', err);
setError(err.message || 'An unexpected error occurred. Please try again.');
} finally {
setIsLoading(false);
}
};
return (
Join a Game
Game Code
<input
type="text"
id="gameCode"
value={gameCode}
onChange={(e) => setGameCode(e.target.value.toUpperCase())}
className="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500"
placeholder="Enter 6-character game code"
required
/>
{error && {error}}
{isLoading ? 'Joining Game...' : 'Join Game'}
);
};
export default JoinGame;
====
successfully submit test fails
The issue with your failing test, specifically the "successfully joins a game" test, stems from the fact that the mockJoinGame function is not returning the expected resolved value.
In your component code, after calling joinGameFunction({ gameCode, playerName }), you are awaiting the result and extracting data.gameId:
javascript
const result = await joinGameFunction({ gameCode, playerName });
const data = result.data as { gameId: string };
navigate(`/game-lobby/${data.gameId}`, { state: { gameCode } });
This means that joinGameFunction must return a promise that resolves to an object with a data property containing a gameId.
However, in your test setup, you're mocking httpsCallable to return mockJoinGame, but you haven't specified what mockJoinGame should return when called. By default, vi.fn() returns undefined, which means result in your component code would be undefined, leading to errors when you try to access result.data.gameId.
Here's how you can fix the test:
Modify mockJoinGame to return a resolved promise with the expected data.
In your test file, when you define mockJoinGame, make sure it returns a promise that resolves to an object containing the expected data:
Adjust your beforeEach block to set up the mock correctly:
javascript
beforeEach(() => {
vi.clearAllMocks();
(usePlayerStore as unknown as vi.Mock).mockReturnValue('TestPlayer');
mockJoinGame.mockResolvedValue({ data: { gameId: 'testGameId' } }); // Add this line
(httpsCallable as unknown as vi.Mock).mockReturnValue(mockJoinGame);
(ensureAnonymousAuth as unknown as vi.Mock).mockResolvedValue(null);
});
Confirm that other expectations match the actual behavior.
Make sure your expectations in the test match what actually happens in the component. For example, verify that the navigation path is correct, and any functions are called with the right arguments.
Updated Test File Snippet:
javascript
const mockJoinGame = vi.fn().mockResolvedValue({ data: { gameId: 'testGameId' } });
beforeEach(() => {
vi.clearAllMocks();
(usePlayerStore as unknown as vi.Mock).mockReturnValue('TestPlayer');
mockJoinGame.mockResolvedValue({ data: { gameId: 'testGameId' } }); // Ensure this is set
(httpsCallable as unknown as vi.Mock).mockReturnValue(mockJoinGame);
(ensureAnonymousAuth as unknown as vi.Mock).mockResolvedValue(null);
});
it('successfully joins a game', async () => {
render(
<BrowserRouter>
<JoinGame />
</BrowserRouter>
);
const input = screen.getByLabelText('Game Code');
const submitButton = screen.getByRole('button', { name: 'Join Game' });
fireEvent.change(input, { target: { value: 'ABC123' } });
fireEvent.click(submitButton);
await waitFor(() => {
expect(ensureAnonymousAuth).toHaveBeenCalled();
expect(mockJoinGame).toHaveBeenCalledWith({ gameCode: 'ABC123', playerName: 'TestPlayer' });
expect(mockNavigate).toHaveBeenCalledWith('/game-lobby/testGameId', { state: { gameCode: 'ABC123' } });
});
});
Explanation:
Mocking mockJoinGame Return Value:
By setting mockResolvedValue on mockJoinGame, we ensure that when joinGameFunction (which is mockJoinGame in the test) is called, it returns a promise that resolves to the expected data structure { data: { gameId: 'testGameId' } }.
Matching the Component's Behavior:
The component expects the result of joinGameFunction to have a data property with a gameId. The test must provide this structure to simulate the real function's behavior accurately.
Including the Navigation State (Optional):
If your navigate call includes a state object (as in your component code), make sure your test also accounts for that in the expectation:
Ensuring Consistent Mock Implementations:
All your mocks should align with the actual implementations in terms of expected inputs and outputs. Any discrepancies can lead to tests that don't accurately reflect real-world usage.
Conclusion:
By adjusting mockJoinGame to return the expected resolved value, your test should now pass, accurately simulating the component's behavior when successfully joining a game. This approach ensures that your test provides the necessary context and data for the component to function correctly within the test environment.