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, updatedMatch: Record | null = match, ) { const MatchModel = { findById: jest.fn().mockResolvedValue(match), findOne: jest.fn().mockResolvedValue(match), findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch), }; 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, 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; updatedMatch?: Record | null; }) { const UserModel = { findById: jest.fn().mockResolvedValue(params.user), }; const MatchModel = { findById: jest.fn().mockResolvedValue(params.match), findOneAndUpdate: jest .fn() .mockResolvedValue(params.updatedMatch ?? 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('scopes Match detail lookup to the URL community', async () => { const matchId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId(); const match = { _id: matchId, communityId }; const { service, MatchModel } = createService(match); await expect(service.getById(matchId, communityId)).resolves.toBe(match); expect(MatchModel.findOne).toHaveBeenCalledWith({ _id: matchId, communityId, }); }); 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 updatedMatch = { ...match, participants: [ { userId, puuid: 'puuid-1', gameName: 'Dahyeon', tagLine: 'KR1', profileIconId: 7, preferredPositions: [{ position: 'MID', priority: 1 }], excluded: false, }, ], }; const { service, MatchModel } = createServiceWithJoinModels({ user, match, updatedMatch, }); const joined = await service.join({ matchId, userId, }); expect(joined).toBe(updatedMatch); expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith( expect.objectContaining({ _id: matchId, communityId, status: 'recruiting', 'participants.userId': { $ne: userId }, $expr: expect.any(Object), }), { $push: { participants: expect.objectContaining({ userId, puuid: 'puuid-1', gameName: 'Dahyeon', tagLine: 'KR1', profileIconId: 7, preferredPositions: [{ position: 'MID', priority: 1 }], excluded: false, }), }, }, expect.objectContaining({ returnDocument: 'after', runValidators: true }), ); expect(match.participants).toEqual([]); expect(match.save).not.toHaveBeenCalled(); }); it('does not join a user from a different community', async () => { const requestedCommunityId = new mongoose.Types.ObjectId(); const userId = new mongoose.Types.ObjectId(); const user = { _id: userId, communityId: new mongoose.Types.ObjectId(), preferredPositions: [], riotAccounts: [], }; const match = { _id: new mongoose.Types.ObjectId(), communityId: requestedCommunityId, status: 'recruiting', participants: [], }; const { service, MatchModel } = createServiceWithJoinModels({ user, match, }); await expect( service.join({ matchId: match._id, communityId: requestedCommunityId, userId, }), ).rejects.toThrow('Match not found.'); expect(MatchModel.findOneAndUpdate).not.toHaveBeenCalled(); }); it('cancels a join with an atomic participant pull', async () => { const communityId = new mongoose.Types.ObjectId(); const userId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const user = { _id: userId, communityId, riotAccounts: [], preferredPositions: [], }; const match = { _id: matchId, communityId, status: 'recruiting', participants: [{ userId }], save: jest.fn(), }; const updatedMatch = { ...match, participants: [] }; const { service, MatchModel } = createServiceWithJoinModels({ user, match, updatedMatch, }); await expect(service.cancelJoin({ matchId, userId })).resolves.toBe( updatedMatch, ); expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith( { _id: matchId, communityId, status: 'recruiting', 'participants.userId': userId, }, { $pull: { participants: { userId } } }, expect.objectContaining({ returnDocument: 'after', runValidators: true }), ); expect(match.save).not.toHaveBeenCalled(); }); it('removes a participant with an atomic participant pull', async () => { const communityId = new mongoose.Types.ObjectId(); const targetUserId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const match = { _id: matchId, communityId, status: 'recruiting', participants: [{ userId: targetUserId }], save: jest.fn(), }; const updatedMatch = { ...match, participants: [] }; const { service, MatchModel } = createService(match, updatedMatch); await expect( service.removeParticipant({ matchId, communityId, targetUserId }), ).resolves.toBe(updatedMatch); expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith( { _id: matchId, communityId, status: 'recruiting', 'participants.userId': targetUserId, }, { $pull: { participants: { userId: targetUserId } } }, expect.objectContaining({ returnDocument: 'after', runValidators: true }), ); expect(match.save).not.toHaveBeenCalled(); }); it('updates participant positions with an array-filtered atomic update', async () => { const communityId = new mongoose.Types.ObjectId(); const targetUserId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const match = { _id: matchId, communityId, status: 'recruiting', participants: [ { userId: targetUserId, preferredPositions: [ { position: 'TOP', priority: 1 }, { position: 'JUNGLE', priority: 2 }, { position: 'MID', priority: 3 }, ], }, ], save: jest.fn(), }; const updatedMatch = { ...match }; const { service, MatchModel } = createService(match, updatedMatch); await expect( service.updateParticipantPositions({ matchId, communityId, targetUserId, mainPosition: 'MID', subPosition: 'SUPPORT', }), ).resolves.toBe(updatedMatch); expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith( { _id: matchId, communityId, status: 'recruiting', 'participants.userId': targetUserId, }, { $set: { 'participants.$[participant].preferredPositions': [ { position: 'MID', priority: 1 }, { position: 'SUPPORT', priority: 2 }, { position: 'TOP', priority: 3 }, { position: 'JUNGLE', priority: 4 }, ], }, }, expect.objectContaining({ arrayFilters: [{ 'participant.userId': targetUserId }], returnDocument: 'after', runValidators: true, }), ); expect(match.save).not.toHaveBeenCalled(); }); 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: 5, 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('rejects returning a finalized team build 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 expect( service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { status: 'recruiting' }, }), ).rejects.toThrow('cannot return to recruiting'); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); expect(match.tournamentCodeIds).toEqual([]); expect(match.gameSchedule).toEqual([ { gameNumber: 1, teamAIndex: 2, teamBIndex: 4 }, ]); expect(match.teamBuiltAt).toBeInstanceOf(Date); expect(match.result).toEqual({ games: [] }); expect(match.resultPollState).toEqual({ state: 'polling' }); expect(match.save).not.toHaveBeenCalled(); expect(matchStatsService.removeByMatch).not.toHaveBeenCalled(); }); 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, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.', ); expect(match.set).not.toHaveBeenCalled(); }); it('rejects game count changes after recruiting', async () => { const communityId = new mongoose.Types.ObjectId(); const match = { communityId, status: 'team-built', tournamentCodeIds: [], set: jest.fn(), save: jest.fn(), }; const { service } = createService(match); await expect( service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { gameCount: 5 }, }), ).rejects.toThrow('gameCount'); expect(match.set).not.toHaveBeenCalled(); }); it('rejects returning to recruiting after Competition bootstrap', async () => { const communityId = new mongoose.Types.ObjectId(); const match = { communityId, competitionId: new mongoose.Types.ObjectId(), status: 'team-built', tournamentCodeIds: [], set: jest.fn(), save: jest.fn(), }; const { service, tournamentCodeService } = createService(match); await expect( service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { status: 'recruiting' }, }), ).rejects.toThrow('cannot return to recruiting'); expect(match.set).not.toHaveBeenCalled(); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); }); it('rejects hard deletion after Competition bootstrap', async () => { const communityId = new mongoose.Types.ObjectId(); const match = { _id: new mongoose.Types.ObjectId(), communityId, competitionId: new mongoose.Types.ObjectId(), status: 'recruiting', tournamentCodeIds: [], deleteOne: jest.fn(), }; const { service, tournamentCodeService, matchStatsService } = createService(match); await expect( service.remove({ matchId: match._id, communityId }), ).rejects.toThrow('cannot be hard-deleted'); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); expect(matchStatsService.removeByMatch).not.toHaveBeenCalled(); expect(match.deleteOne).not.toHaveBeenCalled(); }); it('preserves reserved codes when a recruiting rollback is rejected', 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 expect( service.update({ matchId: new mongoose.Types.ObjectId(), communityId, patch: { status: 'recruiting' }, }), ).rejects.toThrow('cannot return to recruiting'); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); expect(match.tournamentCodeIds).toEqual([codeId]); expect(match.gameSchedule).toEqual([ { gameNumber: 1, teamAIndex: 1, teamBIndex: 3 }, ]); expect(match.save).not.toHaveBeenCalled(); }); });