import functionsTest from 'firebase-functions-test';
import { createGame } from './createGame';
import { db, FieldValue } from './firebase/config';
const testEnv = functionsTest();
// Access the mocks from the mocked module
const mockCollection = db.collection as jest.Mock;
const mockFieldValue = FieldValue as unknown as jest.Mock;
describe('createGame', () => {
let wrapped: any;
code
Assistant
// Declare mockGet and mockAdd at the describe block level
let mockGet: jest.Mock;
let mockAdd: jest.Mock;
beforeAll(() => {
wrapped = testEnv.wrap(createGame);
});
beforeEach(() => {
jest.resetAllMocks();
// Initialize mocks
mockGet = jest.fn();
mockAdd = jest.fn();
// Mock db.collection()
mockCollection.mockImplementation((collectionName: string) => {
if (collectionName === 'games') {
return {
// For collection('games').where('gameCode', '==', code).get()
where: jest.fn().mockImplementation(() => ({
get: mockGet,
})),
// For collection('games').add(newGame)
add: mockAdd,
};
}
// Mock other collections if needed
return {};
});
// Default behavior for mockGet and mockAdd
mockGet.mockResolvedValue({ empty: true }); // No collision by default
mockAdd.mockResolvedValue({ id: 'game123' });
});
afterAll(() => {
jest.restoreAllMocks();
testEnv.cleanup();
});
it('should successfully create a new game with valid inputs', async () => {
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
const result = await wrapped(data, context);
expect(result).toHaveProperty('gameId', 'game123');
expect(result).toHaveProperty('gameCode');
// Verify that collection was called with 'games'
expect(mockCollection).toHaveBeenCalledWith('games');
// Verify that add was called with expected data
const expectedGameData = expect.objectContaining({
gameCode: expect.any(String),
createdBy: 'TestPlayer',
roundHost: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
teams: expect.arrayContaining([
expect.objectContaining({
teamName: 'Team 1',
players: expect.arrayContaining([{ name: 'TestPlayer' }]),
}),
]),
createdAt: 'mocked-timestamp',
currentRound: 0,
});
expect(mockAdd).toHaveBeenCalledWith(expectedGameData);
});
it('should throw an unauthenticated error if user is not authenticated', async () => {
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {}; // No auth
jest.spyOn(console, 'error').mockImplementation(() => { });
await expect(wrapped(data, context)).rejects.toThrow(
'The function must be called while authenticated.'
);
});
it('should throw an invalid-argument error for missing name', async () => {
const data = {
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
jest.spyOn(console, 'error').mockImplementation(() => { });
await expect(wrapped(data, context)).rejects.toThrow(
'Name is required and must be between 3 and 20 characters.'
);
});
it('should throw an invalid-argument error for missing numberOfTeams', async () => {
const data = {
name: 'TestPlayer',
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
await expect(wrapped(data, context)).rejects.toThrow(
'Number of teams is required and must be a positive integer.'
);
});
it('should throw an invalid-argument error for invalid playersPerTeam', async () => {
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: -1,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
jest.spyOn(console, 'error').mockImplementation(() => { });
await expect(wrapped(data, context)).rejects.toThrow(
'Number of players per team is required and must be a positive integer.'
);
});
it('should throw an invalid-argument error for invalid numberOfRounds', async () => {
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 0,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
jest.spyOn(console, 'error').mockImplementation(() => { });
await expect(wrapped(data, context)).rejects.toThrow(
'Number of rounds is required and must be a positive integer.'
);
});
it('should throw an invalid-argument error for invalid jokerUsage', async () => {
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: 'yes', // Invalid boolean
};
const context = {
auth: {
uid: 'creator-uid',
},
};
jest.spyOn(console, 'error').mockImplementation(() => { });
await expect(wrapped(data, context)).rejects.toThrow(
'Joker usage must be a boolean.'
);
});
it('should throw an internal error if Firestore add fails', async () => {
// Mock add to throw an error
mockAdd.mockRejectedValueOnce(new Error('Firestore add error'));
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
jest.spyOn(console, 'error').mockImplementation(() => { });
await expect(wrapped(data, context)).rejects.toThrow(
'Unable to create game at this time.'
);
// Verify that add was called
expect(mockAdd).toHaveBeenCalled();
});
it('should retry generating a unique game code on collision', async () => {
// Mock get to return collision on first call, then no collision
mockGet
.mockResolvedValueOnce({ empty: false }) // Collision
.mockResolvedValueOnce({ empty: true }); // No collision
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
const result = await wrapped(data, context);
expect(result).toHaveProperty('gameId', 'game123');
expect(result).toHaveProperty('gameCode');
// Ensure the get method was called twice due to collision retry
expect(mockGet).toHaveBeenCalledTimes(2);
});
});
====
import * as functions from 'firebase-functions';
import { db as firestore, FieldValue } from './firebase/config';
import { v4 as uuidv4 } from 'uuid';
import { Game, Team, Player } from './types';
/**
Firebase Cloud Function to create a new game session.
Initializes a game document in Firestore with specified parameters,
generates a unique game code, assigns the creator to a team,
and sets them as the initial Round Host.
*/
export const createGame = functions.https.onCall(async (data, context) => {
// Ensure the user is authenticated (using Anonymous Authentication)
if (!context.auth) {
throw new functions.https.HttpsError(
'unauthenticated',
'The function must be called while authenticated.'
);
}
// Validate input parameters
if (
!name ||
typeof name !== 'string' ||
name.trim().length < 3 ||
name.trim().length > 20
) {
throw new functions.https.HttpsError(
'invalid-argument',
'Name is required and must be between 3 and 20 characters.'
);
}
if (
!numberOfTeams ||
typeof numberOfTeams !== 'number' ||
numberOfTeams <= 0
) {
throw new functions.https.HttpsError(
'invalid-argument',
'Number of teams is required and must be a positive integer.'
);
}
if (
!playersPerTeam ||
typeof playersPerTeam !== 'number' ||
playersPerTeam <= 0
) {
throw new functions.https.HttpsError(
'invalid-argument',
'Number of players per team is required and must be a positive integer.'
);
}
if (
!numberOfRounds ||
typeof numberOfRounds !== 'number' ||
numberOfRounds <= 0
) {
throw new functions.https.HttpsError(
'invalid-argument',
'Number of rounds is required and must be a positive integer.'
);
}
if (typeof jokerUsage !== 'boolean') {
throw new functions.https.HttpsError(
'invalid-argument',
'Joker usage must be a boolean.'
);
}
} catch (error) {
console.error('Error creating game:', error);
throw new functions.https.HttpsError(
'internal',
'Unable to create game at this time.'
);
}
});
====
import { DocumentReference, DocumentData, Firestore, CollectionReference } from '@google-cloud/firestore';
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'^firebase-admin': '<rootDir>/__mocks__/firebase-admin.ts', // Mock firebase-admin
'^firebase-functions': '/node_modules/firebase-functions', // Point to actual firebase-functions
},
setupFilesAfterEnv: ['/jest.setup.ts'], // Jest setup file
transform: {
'^.+\.ts?$': [
'ts-jest',
{
tsconfig: 'tsconfig.json', // Specify your TypeScript configuration
},
],
},
};
===
Fix the test. and are the mocs used and how?
The issue with the tests lies in how the mocks are set up and used. Specifically, the mocks are not correctly applied because they are placed after import statements, and they're not providing the necessary mock implementations. Let's break down the problems and see how to fix them.
Problems:
Placement of jest.mock Calls: In Jest, the jest.mock calls should be at the very top of the file, before any import statements. This ensures that the modules are mocked before they're actually imported elsewhere in your code. In the provided code, the jest.mock calls are placed after some initial comments, which can lead to the modules being imported before they're mocked.
Incomplete Mock Implementations: The jest.mock('./firebase/config'); statement doesn't provide any implementation. When no factory is provided, Jest creates an automatic mock where all functions return undefined by default, which might not be what you want. You need to provide a manual mock implementation to ensure that the db and FieldValue variables are mocked correctly.
Mismatch of Mocks and Actual Imports: The FieldValue is not being mocked appropriately in relation to how it's used in your code. The FieldValue from 'firebase-admin/firestore' might not directly correspond to the FieldValue from './firebase/config'. This can cause the mock to not affect the FieldValue used in your function.
How to Fix the Tests:
1. Move jest.mock Calls to the Top
Place all your jest.mock calls at the top of the file, before any imports:
typescript
// jest.mock should be at the top of the file
jest.mock('./firebase/config', () => {
const mockedDb = {
collection: jest.fn(),
};
const mockedFieldValue = {
serverTimestamp: jest.fn(() => 'mocked-timestamp'),
};
return { db: mockedDb, FieldValue: mockedFieldValue };
});
// Mock FieldValue.serverTimestamp()
jest.mock('firebase-admin/firestore', () => ({
FieldValue: {
serverTimestamp: jest.fn(() => 'mocked-timestamp'),
},
}));
2. Provide Manual Mock Implementations
Since Jest's automatic mocks may not provide the desired behavior, we need to provide manual mock implementations for the modules we're mocking.
A mocked db object with a collection method that we can control in our tests.
A mocked FieldValue object with a serverTimestamp method that returns a predictable value.
3. Correctly Access and Use the Mocks in the Tests
After setting up the mocks, you can import your modules and access the mocked functions:
typescript
import functionsTest from 'firebase-functions-test';
import { createGame } from './createGame';
import { db, FieldValue } from './firebase/config'; // These are now the mocked versions
const testEnv = functionsTest();
const mockCollection = db.collection as jest.Mock; // This is the mocked collection method
Now, in your beforeEach or individual tests, you can set up the behavior of the mocks:
4. Update Your Tests to Reflect the Correct Mock Usage
Ensure that your tests use the mocks correctly:
typescript
it('should successfully create a new game with valid inputs', async () => {
const data = {
name: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
};
const context = {
auth: {
uid: 'creator-uid',
},
};
const result = await wrapped(data, context);
expect(result).toHaveProperty('gameId', 'game123');
expect(result).toHaveProperty('gameCode');
// Verify that collection was called with 'games'
expect(mockCollection).toHaveBeenCalledWith('games');
// Verify that add was called with expected data
const expectedGameData = expect.objectContaining({
gameCode: expect.any(String),
createdBy: 'TestPlayer',
roundHost: 'TestPlayer',
numberOfTeams: 2,
playersPerTeam: 3,
numberOfRounds: 5,
jokerUsage: true,
teams: expect.arrayContaining([
expect.objectContaining({
teamName: 'Team 1',
players: expect.arrayContaining([{ name: 'TestPlayer' }]),
}),
]),
createdAt: 'mocked-timestamp',
currentRound: 0,
});
expect(mockAdd).toHaveBeenCalledWith(expectedGameData);
});
How the Mocks Are Used and Why
db.collection Mock: This mock allows you to simulate interactions with Firestore. By mocking the collection method, you control what happens when your function tries to interact with Firestore collections. In this case, you can specify what happens when where, get, or add are called, allowing you to test different scenarios (e.g., collisions, successful additions).
FieldValue.serverTimestamp Mock: By mocking this method, you ensure that when your function sets createdAt using FieldValue.serverTimestamp(), it returns a predictable value ('mocked-timestamp'). This is important for testing because it removes the variability introduced by actual timestamps, allowing you to make precise assertions in your tests.
The Fixed Test File
Here's the corrected version of your test file:
typescript
// jest.mock should be at the top of the file
jest.mock('./firebase/config', () => {
const mockedDb = {
collection: jest.fn(),
};
const mockedFieldValue = {
serverTimestamp: jest.fn(() => 'mocked-timestamp'),
};
return { db: mockedDb, FieldValue: mockedFieldValue };
});
// Mock FieldValue.serverTimestamp()
jest.mock('firebase-admin/firestore', () => ({
FieldValue: {
serverTimestamp: jest.fn(() => 'mocked-timestamp'),
},
}));
import functionsTest from 'firebase-functions-test';
import { createGame } from './createGame';
import { db, FieldValue } from './firebase/config';
const testEnv = functionsTest();
const mockCollection = db.collection as jest.Mock;
describe('createGame', () => {
let wrapped: any;
// Declare mockGet and mockAdd at the describe block level
let mockGet: jest.Mock;
let mockAdd: jest.Mock;
beforeAll(() => {
wrapped = testEnv.wrap(createGame);
});
beforeEach(() => {
jest.resetAllMocks();
// Initialize mocks
mockGet = jest.fn();
mockAdd = jest.fn();
mockCollection.mockImplementation((collectionName: string) => {
if (collectionName === 'games') {
return {
where: jest.fn().mockImplementation(() => ({
get: mockGet,
})),
add: mockAdd,
};
}
// Mock other collections if needed
return {};
});
mockGet.mockResolvedValue({ empty: true }); // Default no collision
mockAdd.mockResolvedValue({ id: 'game123' });
});
// ... rest of your tests
});
Recap
Ensure jest.mock Calls Are Before Imports: Always place your jest.mock statements at the very top of the file, before any imports. This ensures that when the module is imported, it's already been mocked.
Provide Manual Mock Implementations: When you need specific behavior from your mocks (like returning certain values or functions), provide a manual mock implementation.
Access and Control Mocks in Tests: Use the mocked functions in your tests to simulate and control the environment your function operates in. This allows you to test different scenarios and ensure your function behaves as expected.
By fixing the placement of your mocks and providing proper implementations, your tests should now work correctly, and the mocks will accurately simulate the behavior of Firestore and other Firebase services.