import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { MatchHistoryService } from './match-history.service'; const SEASON_START = Date.parse('2026-01-01T00:00:00Z'); describe('MatchHistoryService champion filtering', () => { it('selects a lane before limiting and uses only the requested participant, including legacy individualPosition', async () => { const { service, scope, find } = createHarness(); const result = await service.getRecentMatches({ ...scope, filters: { rank: 'solo', lane: 'MIDDLE', limit: 20 }, }); expect(result.matches.map((game) => game.matchId)).toEqual([ 'KR_3', 'KR_2', 'KR_1', ]); expect(result.matches.every((game) => game.teamPosition === 'MIDDLE')).toBe( true, ); expect(result.matches[0].damageShare).toBe(100); expect(find.mock.calls[0][0]['raw.info.participants']?.$elemMatch).toEqual({ puuid: 'player', $or: [ { teamPosition: 'MIDDLE' }, { teamPosition: { $in: ['', null] }, individualPosition: 'MIDDLE' }, ], }); }); it('combines champion and lane filtering and rejects invalid lanes', async () => { const { service, scope } = createHarness(); const result = await service.getRecentMatches({ ...scope, filters: { rank: 'solo', championId: 1, lane: 'MIDDLE', limit: 20 }, }); expect(result.matches).toEqual([]); await expect( service.getRecentMatches({ ...scope, filters: { lane: 'unknown' } }), ).rejects.toThrow('Invalid lane'); }); it('counts independent lane windows across the season and caps each at twenty', async () => { const { service, scope, aggregate } = createHarness(); const result = await service.getRecentMatches({ ...scope, filters: { rank: 'solo', lane: 'MIDDLE', limit: 20, includePositionCounts: true, }, }); expect(result.positionCounts).toEqual({ ALL: 20, TOP: 20, JUNGLE: 0, MIDDLE: 3, BOTTOM: 0, UTILITY: 0, }); expect(aggregate.mock.calls[0][0][0]).toEqual({ $match: { participantPuuids: 'player', queueId: { $in: [420] }, gameCreation: { $gte: SEASON_START }, }, }); expect(JSON.stringify(aggregate.mock.calls[0][0])).toContain('$$p.puuid'); expect(JSON.stringify(aggregate.mock.calls[0][0])).not.toContain('$limit'); }); it('paginates matching games beyond 120 newer games and excludes opponents using the champion', async () => { const harness = createHarness(); const filters = { championId: 99, rank: 'solo', limit: 2 }; const first = await harness.service.getRecentMatches({ ...harness.scope, filters, }); expect(first.matches.map((match) => match.matchId)).toEqual([ 'KR_3', 'KR_2', ]); expect(first.nextCursor).toBe(SEASON_START + 2_000); expect(first.matches[0].largestMultiKill).toBe(3); expect(first.matches[0].teams[0].participants[0].tier).toMatchObject({ tier: 'GOLD', rank: 'II', }); const second = await harness.service.getRecentMatches({ ...harness.scope, filters: { ...filters, cursor: first.nextCursor! }, }); expect(second.matches.map((match) => match.matchId)).toEqual(['KR_1']); expect(second.nextCursor).toBeNull(); expect(harness.returnedCounts).toEqual([3, 1]); expect(harness.find).toHaveBeenLastCalledWith({ participantPuuids: 'player', queueId: { $in: [420] }, gameCreation: { $gte: SEASON_START, $lt: first.nextCursor }, 'raw.info.participants': { $elemMatch: { puuid: 'player', championId: 99 }, }, }); }); it('summarizes matching games across the former scan boundary', async () => { const { service, scope, returnedCounts } = createHarness(); const summary = await service.getRecentSummary({ ...scope, filters: { championId: 99, rank: 'solo', limit: 20 }, }); expect(summary).toMatchObject({ windowSize: 3, wins: 3, losses: 0 }); expect(summary.topChampions).toEqual([ expect.objectContaining({ championId: 99, games: 3 }), ]); expect(returnedCounts).toEqual([3]); }); it('keeps unfiltered pagination and does not transfer timeline payloads', async () => { const { service, scope, find, select, returnedCounts } = createHarness(); const result = await service.getRecentMatches({ ...scope, filters: { rank: 'solo', limit: 2 }, }); expect(result.matches.map((match) => match.matchId)).toEqual([ 'KR_130', 'KR_129', ]); expect(result.nextCursor).toBe(SEASON_START + 129_000); expect(find.mock.calls[0][0]['raw.info.participants']).toBeUndefined(); expect(select).toHaveBeenCalledWith({ timeline: 0 }); expect(returnedCounts).toEqual([3]); }); }); interface HistoryQuery { participantPuuids: string; queueId: { $in: number[] }; gameCreation?: { $gte?: number; $lt?: number }; 'raw.info.participants'?: { $elemMatch: { puuid: string; championId?: number; $or?: Array<{ teamPosition: string | { $in: (string | null)[] }; individualPosition?: string; }>; }; }; } function createHarness() { const communityId = new mongoose.Types.ObjectId(); const userId = new mongoose.Types.ObjectId(); // In the newer games only the opponent played champion 99. const rows = [ ...Array.from({ length: 127 }, (_, index) => storedMatch(index + 4, 1)), storedMatch(3, 99), storedMatch(2, 99), storedMatch(1, 99), storedMatch(131, 99, 450), // Wrong queue. storedMatch(-1, 99), // Before the season. ]; const returnedCounts: number[] = []; const select = jest.fn(); const find = jest.fn((filter: HistoryQuery) => { let limit = rows.length; const query = { sort: jest.fn().mockReturnThis(), limit: (value: number) => { limit = value; return query; }, select: (projection: unknown) => { select(projection); return query; }, exec: async () => { const participant = filter['raw.info.participants']?.$elemMatch; const result = rows .filter( (row) => row.participantPuuids.includes(filter.participantPuuids) && filter.queueId.$in.includes(row.queueId) && (filter.gameCreation?.$gte === undefined || row.gameCreation >= filter.gameCreation.$gte) && (filter.gameCreation?.$lt === undefined || row.gameCreation < filter.gameCreation.$lt) && (!participant || row.raw.info.participants.some( (entry) => entry.puuid === participant.puuid && (participant.championId === undefined || entry.championId === participant.championId) && (!participant.$or || participant.$or.some((condition) => typeof condition.teamPosition === 'string' ? entry.teamPosition === condition.teamPosition : condition.teamPosition.$in.includes( entry.teamPosition ?? null, ) && entry.individualPosition === condition.individualPosition, )), )), ) .sort((a, b) => b.gameCreation - a.gameCreation) .slice(0, limit); returnedCounts.push(result.length); return result; }, }; return query; }); const aggregate = jest.fn< { exec: () => Promise> }, [unknown[]] >(() => ({ exec: async () => [ { _id: 'TOP', count: 127 }, { _id: 'MIDDLE', count: 3 }, ], })); const models = { user: { find: () => ({ select: () => ({ lean: () => ({ exec: async () => [ { riotAccounts: [ { puuid: 'player', tierHistory: [ { queueType: 'RANKED_SOLO_5x5', tier: 'PLATINUM', recordedAt: new Date(SEASON_START + 4_000), }, { queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', recordedAt: new Date(SEASON_START), }, ], }, ], }, ], }), }), }), findById: () => ({ exec: async () => ({ _id: userId, communityId, riotAccounts: [{ puuid: 'player', isPrimary: true }], }), }), }, community: { findById: () => ({ exec: async () => ({ _id: communityId, seasonStartedAt: new Date(SEASON_START), }), }), }, riotMatch: { find, aggregate }, }; const connection = { getModel: async (name: keyof typeof models) => models[name], } as unknown as ConnectionService; return { service: new MatchHistoryService(connection), scope: { communityId, userId }, find, select, returnedCounts, aggregate, }; } function storedMatch(sequence: number, championId: number, queueId = 420) { const gameCreation = SEASON_START + sequence * 1_000; const participant = { puuid: 'player', championId, teamPosition: sequence === 2 ? undefined : championId === 99 ? 'MIDDLE' : 'TOP', individualPosition: championId === 99 ? 'MIDDLE' : 'TOP', teamId: 100, win: true, kills: 5, tripleKills: 1, deaths: 2, assists: 3, totalMinionsKilled: 100, neutralMinionsKilled: 20, goldEarned: 10_000, totalDamageDealtToChampions: 10_000, totalDamageTaken: 5_000, perks: { styles: [] }, }; return { gameCreation, queueId, participantPuuids: ['player', 'opponent'], fetchedAt: new Date(), raw: { metadata: { matchId: `KR_${sequence}` }, info: { gameCreation, queueId, gameDuration: 1_800, participants: [ participant, { ...participant, puuid: 'opponent', teamId: 200, championId: 99, teamPosition: 'MIDDLE', win: false, }, ], teams: [ { teamId: 100, win: true }, { teamId: 200, win: false }, ], }, }, }; }