import mongoose from 'mongoose'; import { MatchService } from './match.service'; describe('MatchService', () => { function createService(match: Record) { const MatchModel = { findById: jest.fn().mockResolvedValue(match), }; const connectionService = { getModel: jest.fn().mockImplementation(async (name: string) => { if (name === 'match') return MatchModel; return {}; }), }; const tournamentCodeService = { buildSlots: jest.fn().mockResolvedValue([]), releaseFromMatch: jest.fn().mockResolvedValue(undefined), }; const communityStatsService = { invalidateCommunity: jest.fn().mockResolvedValue(undefined), }; const matchStatsService = { buildAndUpsert: jest.fn().mockResolvedValue(undefined), removeByMatch: jest.fn().mockResolvedValue(undefined), }; return { service: new MatchService( connectionService as never, tournamentCodeService as never, communityStatsService as never, matchStatsService as never, ), tournamentCodeService, matchStatsService, }; } it('clears game schedule when a built match returns to recruiting', async () => { const communityId = new mongoose.Types.ObjectId(); const match = { communityId, status: 'team-built', tournamentCodeIds: [], gameSchedule: [{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 }], teams: [{ teamIndex: 1 }], teamBuiltAt: new Date(), result: { games: [] }, resultPollState: { state: 'polling' }, set: jest.fn(function ( this: Record, patch: Record, ) { Object.assign(this, patch); }), save: jest.fn().mockResolvedValue(undefined), }; const { service, tournamentCodeService, matchStatsService } = createService(match); await service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { status: 'recruiting' }, }); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); expect(match.tournamentCodeIds).toEqual([]); expect(match.gameSchedule).toEqual([]); expect(match.teamBuiltAt).toBeUndefined(); expect(match.result).toBeUndefined(); expect(match.resultPollState).toBeUndefined(); expect(match.save).toHaveBeenCalledTimes(1); expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); }); it('releases reserved codes when returning a built match to recruiting', async () => { const communityId = new mongoose.Types.ObjectId(); const codeId = new mongoose.Types.ObjectId(); const match = { communityId, status: 'in-progress', tournamentCodeIds: [codeId], gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 }], set: jest.fn(function ( this: Record, patch: Record, ) { Object.assign(this, patch); }), save: jest.fn().mockResolvedValue(undefined), }; const { service, tournamentCodeService } = createService(match); await service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { status: 'recruiting' }, }); expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match); expect(match.tournamentCodeIds).toEqual([]); expect(match.gameSchedule).toEqual([]); }); });