import mongoose from 'mongoose'; import { MatchService } from './match.service'; describe('MatchService', () => { function createServiceWithCreateModels() { const createdPayloads: Record[] = []; const MatchModel = { create: jest.fn().mockImplementation(async (payload) => { createdPayloads.push(payload); return payload; }), exists: jest.fn().mockResolvedValue(null), }; const CommunityModel = { findById: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({ matchGameCount: 3 }), }), }), }), }; const connectionService = { getModel: jest.fn().mockImplementation(async (name: string) => { if (name === 'match') return MatchModel; if (name === 'community') return CommunityModel; 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, ), MatchModel, createdPayloads, }; } 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, }; } function createServiceWithListModel() { const exec = jest.fn().mockResolvedValue([{ title: 'second page' }]); const limit = jest.fn().mockReturnValue({ exec }); const skip = jest.fn().mockReturnValue({ limit }); const sort = jest.fn().mockReturnValue({ skip }); const find = jest.fn().mockReturnValue({ sort }); const countExec = jest.fn().mockResolvedValue(12); const countDocuments = jest.fn().mockReturnValue({ exec: countExec }); const MatchModel = { find, countDocuments, }; 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, ), MatchModel, sort, skip, limit, }; } function createServiceWithJoinModels(params: { user: Record | null; match: Record | null; }) { const UserModel = { findById: jest.fn().mockResolvedValue(params.user), }; const MatchModel = { findById: jest.fn().mockResolvedValue(params.match), }; const connectionService = { getModel: jest.fn().mockImplementation(async (name: string) => { if (name === 'user') return UserModel; 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, ), UserModel, MatchModel, }; } it('returns a paginated match list with total count', async () => { const communityId = new mongoose.Types.ObjectId(); const { service, MatchModel, sort, skip, limit } = createServiceWithListModel(); const page = await service.listPage({ communityId, page: 2, limit: 5, }); expect(MatchModel.find).toHaveBeenCalledWith({ communityId }); expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId }); expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); expect(skip).toHaveBeenCalledWith(5); expect(limit).toHaveBeenCalledWith(5); expect(page).toEqual({ matches: [{ title: 'second page' }], total: 12, page: 2, limit: 5, }); }); it('applies offset before page-based pagination', async () => { const communityId = new mongoose.Types.ObjectId(); const { service, skip } = createServiceWithListModel(); const page = await service.listPage({ communityId, offset: 4, page: 2, limit: 5, }); expect(skip).toHaveBeenCalledWith(9); expect(page.total).toBe(8); }); it('filters future matches and sorts oldest first for upcoming sections', async () => { const communityId = new mongoose.Types.ObjectId(); const scheduledFrom = new Date('2026-06-08T12:00:00.000Z'); const { service, MatchModel, sort } = createServiceWithListModel(); await service.listPage({ communityId, scheduledFrom, sort: 'asc', limit: 4, }); expect(MatchModel.find).toHaveBeenCalledWith({ communityId, scheduledAt: { $gte: scheduledFrom }, }); expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId, scheduledAt: { $gte: scheduledFrom }, }); expect(sort).toHaveBeenCalledWith({ scheduledAt: 1 }); }); it('filters past matches and keeps newest first for history sections', async () => { const communityId = new mongoose.Types.ObjectId(); const scheduledTo = new Date('2026-06-08T12:00:00.000Z'); const { service, MatchModel, sort } = createServiceWithListModel(); await service.listPage({ communityId, scheduledTo, sort: 'desc', limit: 10, }); expect(MatchModel.find).toHaveBeenCalledWith({ communityId, scheduledAt: { $lt: scheduledTo }, }); expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId, scheduledAt: { $lt: scheduledTo }, }); expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); }); it('uses saved user preferences when joining without explicit positions', async () => { const communityId = new mongoose.Types.ObjectId(); const userId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const user = { _id: userId, communityId, preferredPositions: [{ position: 'MID', priority: 1 }], riotAccounts: [ { puuid: 'puuid-1', gameName: 'Dahyeon', tagLine: 'KR1', profileIconId: 7, isPrimary: true, tiers: [], }, ], }; const match = { _id: matchId, communityId, status: 'recruiting', maxParticipants: 10, participants: [], save: jest.fn().mockResolvedValue(undefined), }; const { service } = createServiceWithJoinModels({ user, match }); await service.join({ matchId, userId, }); expect(match.participants).toEqual([ expect.objectContaining({ userId, puuid: 'puuid-1', gameName: 'Dahyeon', tagLine: 'KR1', profileIconId: 7, preferredPositions: [{ position: 'MID', priority: 1 }], excluded: false, }), ]); expect(match.save).toHaveBeenCalledTimes(1); }); it('normalizes double-elimination match creation', async () => { const { service, createdPayloads } = createServiceWithCreateModels(); const communityId = new mongoose.Types.ObjectId(); await service.create({ communityId, data: { title: 'Double elimination', scheduledAt: new Date('2026-06-01T10:00:00.000Z'), maxParticipants: 20, gameCount: 5, gameMode: 'double-elimination', doubleEliminationResetFinalEnabled: true, }, }); expect(createdPayloads[0]).toMatchObject({ communityId, maxParticipants: 20, gameCount: 1, gameMode: 'double-elimination', roundRobinMaxRounds: undefined, doubleElimination: { teamCount: 4, resetFinalEnabled: true, resetFinalCreated: false, seeds: [], bracketMatches: [], placements: {}, events: [], }, }); }); it('rejects unsupported double-elimination participant counts', async () => { const { service, MatchModel } = createServiceWithCreateModels(); await expect( service.create({ communityId: new mongoose.Types.ObjectId(), data: { title: 'Invalid double elimination', scheduledAt: new Date('2026-06-01T10:00:00.000Z'), maxParticipants: 30, gameMode: 'double-elimination', }, }), ).rejects.toThrow('Double elimination supports only 20 or 40 participants.'); expect(MatchModel.create).not.toHaveBeenCalled(); }); 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('rejects round-robin max round changes after recruiting', async () => { const communityId = new mongoose.Types.ObjectId(); const match = { communityId, status: 'team-built', tournamentCodeIds: [], set: jest.fn(), save: jest.fn().mockResolvedValue(undefined), }; const { service } = createService(match); await expect( service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { roundRobinMaxRounds: 3 }, }), ).rejects.toThrow( 'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.', ); expect(match.set).not.toHaveBeenCalled(); }); 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([]); }); });