i keep encountring errors. how to fix this tests to use best practices and to be examples for following tests

import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import * as admin from 'firebase-admin';
import firebaseFunctionsTest from "firebase-functions-test";
import { submitPlayerName } from './index';
import * as functions from 'firebase-functions';

const testEnv = firebaseFunctionsTest();

// Mock Firestore
const mockGet = vi.fn();
const mockWhere = vi.fn(() => ({ where: mockWhere, get: mockGet }));
const mockCollection = vi.fn(() => ({ where: mockWhere }));
const mockSet = vi.fn();
const mockDoc = vi.fn(() => ({ set: mockSet, id: 'newPlayerId' }));

vi.mock('firebase-admin', () => ({
  initializeApp: vi.fn(),
  firestore: vi.fn(() => ({
    collection: mockCollection,
  })),
}));

vi.mock('firebase-functions', () => ({
  https: {
    HttpsError: class HttpsError extends Error {
      constructor(code: string, message: string) {
        super(message);
        this.code = code;
      }
    },
    onCall: (handler: any) => handler,
  },
}));

describe('submitPlayerName', () => {
  beforeAll(() => {
    // No setup needed
  });

  afterAll(() => {
    testEnv.cleanup();
  });

  it('submits a valid player name', async () => {
    const data = { name: 'JaneDoe' };
    const context = {};

    mockGet.mockResolvedValueOnce({ empty: true });
    mockCollection.mockReturnValueOnce({ doc: mockDoc });

    const result = await submitPlayerName(data, context);
    expect(result.name).toBe('JaneDoe');
    expect(result.playerId).toBe('newPlayerId');
    expect(mockSet).toHaveBeenCalledWith(expect.objectContaining({
      name: 'JaneDoe',
      playerId: 'newPlayerId',
      gameId: 'some-game-id',
    }));
  });

  it('rejects duplicate player name', async () => {
    const data = { name: 'ExistingPlayer' };
    const context = {};

    mockGet.mockResolvedValueOnce({ empty: false });

    await expect(submitPlayerName(data, context)).rejects.toThrow('Name already taken in this game.');
  });

  it('rejects invalid player name', async () => {
    const data = { name: 'ab' };
    const context = {};

    await expect(submitPlayerName(data, context)).rejects.toThrow('Name must be 3-20 characters long and can include letters, numbers, spaces, underscores, or hyphens.');
  });
});

/**
 * Import function triggers from their respective submodules:
 *
 * import {onCall} from "firebase-functions/v2/https";
 * import {onDocumentWritten} from "firebase-functions/v2/firestore";
 *
 * See a full list of supported triggers at https://firebase.google.com/docs/functions
 */

import {onRequest} from "firebase-functions/v2/https";
import * as logger from "firebase-functions/logger";
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { Player } from '../../src/types';

admin.initializeApp();

export const submitPlayerName = functions.https.onCall(async (data, context) => {
  const { name } = data;

  // Server-side validation
  if (!name || typeof name !== 'string' || name.trim().length === 0) {
    throw new functions.https.HttpsError('invalid-argument', 'Name is required.');
  }

  const trimmedName = name.trim();
  const nameRegex = /^[a-zA-Z0-9 _-]{3,20}$/;

  if (!nameRegex.test(trimmedName)) {
    throw new functions.https.HttpsError(
      'invalid-argument',
      'Name must be 3-20 characters long and can include letters, numbers, spaces, underscores, or hyphens.'
    );
  }

  try {
    const firestore = admin.firestore();

    // TODO: Determine how to retrieve or assign gameId
    const gameId = 'some-game-id'; // Replace with actual gameId retrieval logic

    // Check for duplicate names within the same game session
    const playersRef = firestore.collection('players');
    const duplicateSnapshot = await playersRef
      .where('gameId', '==', gameId)
      .where('name', '==', trimmedName)
      .get();

    if (!duplicateSnapshot.empty) {
      throw new functions.https.HttpsError('already-exists', 'Name already taken in this game.');
    }

    // Create a new player document
    const newPlayerRef = playersRef.doc();
    const newPlayer: Player = {
      playerId: newPlayerRef.id,
      name: trimmedName,
      gameId,
      teamId: null,
      jokerUsed: false,
    };

    await newPlayerRef.set(newPlayer);

    return { name: trimmedName, playerId: newPlayerRef.id };
  } catch (error) {
    console.error('Error submitting player name:', error);
    if (error instanceof functions.https.HttpsError) {
      throw error;
    }
    throw new functions.https.HttpsError('internal', 'Internal Server Error');
  }
});