/** * Unit tests for GetRatingLeaderboardUseCase */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { GetRatingLeaderboardUseCase } from './GetRatingLeaderboardUseCase'; import { Rating } from '../../domain/Rating'; const mockRatingRepository = { findByDriver: vi.fn(), }; const mockDriverRepository = { findAll: vi.fn(), findById: vi.fn(), }; describe('GetRatingLeaderboardUseCase', () => { let useCase: GetRatingLeaderboardUseCase; beforeEach(() => { vi.clearAllMocks(); useCase = new GetRatingLeaderboardUseCase({ ratingRepository: mockRatingRepository as any, driverRepository: mockDriverRepository as any, }); }); describe('Scenario 10: Pagination + Sorting', () => { it('should return latest rating per driver, sorted desc, sliced by limit/offset', async () => { // Given const drivers = [ { id: 'd1', name: { toString: () => 'Driver 1' } }, { id: 'd2', name: { toString: () => 'Driver 2' } }, { id: 'd3', name: { toString: () => 'Driver 3' } }, ]; const ratingsD1 = [ Rating.create({ driverId: 'd1' as any, raceId: 'r1' as any, rating: 1000, components: {} as any, timestamp: new Date('2023-01-01') }), Rating.create({ driverId: 'd1' as any, raceId: 'r2' as any, rating: 1200, // Latest for D1 components: {} as any, timestamp: new Date('2023-01-02') }) ]; const ratingsD2 = [ Rating.create({ driverId: 'd2' as any, raceId: 'r1' as any, rating: 1500, // Latest for D2 components: {} as any, timestamp: new Date('2023-01-01') }) ]; const ratingsD3 = [ Rating.create({ driverId: 'd3' as any, raceId: 'r1' as any, rating: 800, // Latest for D3 components: {} as any, timestamp: new Date('2023-01-01') }) ]; mockDriverRepository.findAll.mockResolvedValue(drivers); mockDriverRepository.findById.mockImplementation((id) => Promise.resolve(drivers.find(d => d.id === id)) ); mockRatingRepository.findByDriver.mockImplementation((id) => { if (id === 'd1') return Promise.resolve(ratingsD1); if (id === 'd2') return Promise.resolve(ratingsD2); if (id === 'd3') return Promise.resolve(ratingsD3); return Promise.resolve([]); }); // When: limit 2, offset 0 const result = await useCase.execute({ limit: 2, offset: 0 }); // Then: Sorted D2 (1500), D1 (1200), D3 (800). Slice(0, 2) -> D2, D1 expect(result).toHaveLength(2); expect(result[0].driverId).toBe('d2'); expect(result[0].rating).toBe(1500); expect(result[1].driverId).toBe('d1'); expect(result[1].rating).toBe(1200); // When: limit 2, offset 1 const resultOffset = await useCase.execute({ limit: 2, offset: 1 }); // Then: Slice(1, 3) -> D1, D3 expect(resultOffset).toHaveLength(2); expect(resultOffset[0].driverId).toBe('d1'); expect(resultOffset[1].driverId).toBe('d3'); }); }); });