/** * Integration Test: League Creation Use Case Orchestration * * Tests the orchestration logic of league creation-related Use Cases: * - CreateLeagueUseCase: Creates a new league with basic information, structure, schedule, scoring, and stewarding configuration * - Validates that Use Cases correctly interact with their Ports (Repositories, Event Publishers) * - Uses In-Memory adapters for fast, deterministic testing * * Focus: Business logic orchestration, NOT UI rendering */ import { describe, it, expect, beforeAll, beforeEach } from 'vitest'; import { InMemoryLeagueRepository } from '../../../adapters/leagues/persistence/inmemory/InMemoryLeagueRepository'; import { InMemoryLeagueEventPublisher } from '../../../adapters/leagues/events/InMemoryLeagueEventPublisher'; import { CreateLeagueUseCase } from '../../../core/leagues/application/use-cases/CreateLeagueUseCase'; import { LeagueCreateCommand } from '../../../core/leagues/application/ports/LeagueCreateCommand'; describe('League Creation Use Case Orchestration', () => { let leagueRepository: InMemoryLeagueRepository; let eventPublisher: InMemoryLeagueEventPublisher; let createLeagueUseCase: CreateLeagueUseCase; beforeAll(() => { leagueRepository = new InMemoryLeagueRepository(); eventPublisher = new InMemoryLeagueEventPublisher(); createLeagueUseCase = new CreateLeagueUseCase(leagueRepository, eventPublisher); }); beforeEach(() => { leagueRepository.clear(); eventPublisher.clear(); }); describe('CreateLeagueUseCase - Success Path', () => { it('should create a league with complete configuration', async () => { // Scenario: Driver creates a league with complete configuration // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with complete league configuration const command: LeagueCreateCommand = { name: 'Test League', description: 'A test league for integration testing', visibility: 'public', ownerId: driverId, maxDrivers: 20, approvalRequired: true, lateJoinAllowed: true, raceFrequency: 'weekly', raceDay: 'Saturday', raceTime: '18:00', tracks: ['Monza', 'Spa', 'Nürburgring'], scoringSystem: { points: [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] }, bonusPointsEnabled: true, penaltiesEnabled: true, protestsEnabled: true, appealsEnabled: true, stewardTeam: ['steward-1', 'steward-2'], gameType: 'iRacing', skillLevel: 'Intermediate', category: 'GT3', tags: ['competitive', 'weekly-races'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created in the repository expect(result).toBeDefined(); expect(result.id).toBeDefined(); expect(result.name).toBe('Test League'); expect(result.description).toBe('A test league for integration testing'); expect(result.visibility).toBe('public'); expect(result.ownerId).toBe(driverId); expect(result.status).toBe('active'); // And: The league should have all configured properties expect(result.maxDrivers).toBe(20); expect(result.approvalRequired).toBe(true); expect(result.lateJoinAllowed).toBe(true); expect(result.raceFrequency).toBe('weekly'); expect(result.raceDay).toBe('Saturday'); expect(result.raceTime).toBe('18:00'); expect(result.tracks).toEqual(['Monza', 'Spa', 'Nürburgring']); expect(result.scoringSystem).toEqual({ points: [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] }); expect(result.bonusPointsEnabled).toBe(true); expect(result.penaltiesEnabled).toBe(true); expect(result.protestsEnabled).toBe(true); expect(result.appealsEnabled).toBe(true); expect(result.stewardTeam).toEqual(['steward-1', 'steward-2']); expect(result.gameType).toBe('iRacing'); expect(result.skillLevel).toBe('Intermediate'); expect(result.category).toBe('GT3'); expect(result.tags).toEqual(['competitive', 'weekly-races']); // And: The league should be associated with the creating driver as owner const savedLeague = await leagueRepository.findById(result.id); expect(savedLeague).toBeDefined(); expect(savedLeague?.ownerId).toBe(driverId); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); const events = eventPublisher.getLeagueCreatedEvents(); expect(events[0].leagueId).toBe(result.id); expect(events[0].ownerId).toBe(driverId); }); it('should create a league with minimal configuration', async () => { // Scenario: Driver creates a league with minimal configuration // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with minimal league configuration const command: LeagueCreateCommand = { name: 'Minimal League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created in the repository expect(result).toBeDefined(); expect(result.id).toBeDefined(); expect(result.name).toBe('Minimal League'); expect(result.visibility).toBe('public'); expect(result.ownerId).toBe(driverId); expect(result.status).toBe('active'); // And: The league should have default values for all properties expect(result.description).toBeNull(); expect(result.maxDrivers).toBeNull(); expect(result.approvalRequired).toBe(false); expect(result.lateJoinAllowed).toBe(false); expect(result.raceFrequency).toBeNull(); expect(result.raceDay).toBeNull(); expect(result.raceTime).toBeNull(); expect(result.tracks).toBeNull(); expect(result.scoringSystem).toBeNull(); expect(result.bonusPointsEnabled).toBe(false); expect(result.penaltiesEnabled).toBe(false); expect(result.protestsEnabled).toBe(false); expect(result.appealsEnabled).toBe(false); expect(result.stewardTeam).toBeNull(); expect(result.gameType).toBeNull(); expect(result.skillLevel).toBeNull(); expect(result.category).toBeNull(); expect(result.tags).toBeNull(); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with public visibility', async () => { // Scenario: Driver creates a public league // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with visibility set to "Public" const command: LeagueCreateCommand = { name: 'Public League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with public visibility expect(result).toBeDefined(); expect(result.visibility).toBe('public'); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with private visibility', async () => { // Scenario: Driver creates a private league // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with visibility set to "Private" const command: LeagueCreateCommand = { name: 'Private League', visibility: 'private', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with private visibility expect(result).toBeDefined(); expect(result.visibility).toBe('private'); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with approval required', async () => { // Scenario: Driver creates a league requiring approval // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with approval required enabled const command: LeagueCreateCommand = { name: 'Approval Required League', visibility: 'public', ownerId: driverId, approvalRequired: true, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with approval required expect(result).toBeDefined(); expect(result.approvalRequired).toBe(true); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with late join allowed', async () => { // Scenario: Driver creates a league allowing late join // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with late join enabled const command: LeagueCreateCommand = { name: 'Late Join League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: true, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with late join allowed expect(result).toBeDefined(); expect(result.lateJoinAllowed).toBe(true); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with custom scoring system', async () => { // Scenario: Driver creates a league with custom scoring // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with custom scoring configuration const command: LeagueCreateCommand = { name: 'Custom Scoring League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, scoringSystem: { points: [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] }, bonusPointsEnabled: true, penaltiesEnabled: true, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with the custom scoring system expect(result).toBeDefined(); expect(result.scoringSystem).toEqual({ points: [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] }); expect(result.bonusPointsEnabled).toBe(true); expect(result.penaltiesEnabled).toBe(true); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with stewarding configuration', async () => { // Scenario: Driver creates a league with stewarding configuration // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with stewarding configuration const command: LeagueCreateCommand = { name: 'Stewarding League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: true, appealsEnabled: true, stewardTeam: ['steward-1', 'steward-2'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with the stewarding configuration expect(result).toBeDefined(); expect(result.protestsEnabled).toBe(true); expect(result.appealsEnabled).toBe(true); expect(result.stewardTeam).toEqual(['steward-1', 'steward-2']); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with schedule configuration', async () => { // Scenario: Driver creates a league with schedule configuration // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with schedule configuration const command: LeagueCreateCommand = { name: 'Schedule League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, raceFrequency: 'weekly', raceDay: 'Saturday', raceTime: '18:00', tracks: ['Monza', 'Spa', 'Nürburgring'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with the schedule configuration expect(result).toBeDefined(); expect(result.raceFrequency).toBe('weekly'); expect(result.raceDay).toBe('Saturday'); expect(result.raceTime).toBe('18:00'); expect(result.tracks).toEqual(['Monza', 'Spa', 'Nürburgring']); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with max drivers limit', async () => { // Scenario: Driver creates a league with max drivers limit // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with max drivers set to 20 const command: LeagueCreateCommand = { name: 'Max Drivers League', visibility: 'public', ownerId: driverId, maxDrivers: 20, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with max drivers limit of 20 expect(result).toBeDefined(); expect(result.maxDrivers).toBe(20); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should create a league with no max drivers limit', async () => { // Scenario: Driver creates a league with no max drivers limit // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called without max drivers const command: LeagueCreateCommand = { name: 'No Max Drivers League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with no max drivers limit expect(result).toBeDefined(); expect(result.maxDrivers).toBeNull(); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); }); describe('CreateLeagueUseCase - Edge Cases', () => { it('should handle league with empty description', async () => { // Scenario: Driver creates a league with empty description // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with empty description const command: LeagueCreateCommand = { name: 'Empty Description League', description: '', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with empty description (mapped to null or empty string depending on implementation) expect(result).toBeDefined(); expect(result.description).toBeNull(); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with very long description', async () => { // Scenario: Driver creates a league with very long description // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; const longDescription = 'a'.repeat(2000); // When: CreateLeagueUseCase.execute() is called with very long description const command: LeagueCreateCommand = { name: 'Long Description League', description: longDescription, visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with the long description expect(result).toBeDefined(); expect(result.description).toBe(longDescription); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with special characters in name', async () => { // Scenario: Driver creates a league with special characters in name // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; const specialName = 'League! @#$%^&*()_+'; // When: CreateLeagueUseCase.execute() is called with special characters in name const command: LeagueCreateCommand = { name: specialName, visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with the special characters in name expect(result).toBeDefined(); expect(result.name).toBe(specialName); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with max drivers set to 1', async () => { // Scenario: Driver creates a league with max drivers set to 1 // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with max drivers set to 1 const command: LeagueCreateCommand = { name: 'Single Driver League', visibility: 'public', ownerId: driverId, maxDrivers: 1, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with max drivers limit of 1 expect(result).toBeDefined(); expect(result.maxDrivers).toBe(1); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with very large max drivers', async () => { // Scenario: Driver creates a league with very large max drivers // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with max drivers set to 1000 const command: LeagueCreateCommand = { name: 'Large League', visibility: 'public', ownerId: driverId, maxDrivers: 1000, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with max drivers limit of 1000 expect(result).toBeDefined(); expect(result.maxDrivers).toBe(1000); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with empty track list', async () => { // Scenario: Driver creates a league with empty track list // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with empty track list const command: LeagueCreateCommand = { name: 'No Tracks League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, tracks: [], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with empty track list expect(result).toBeDefined(); expect(result.tracks).toEqual([]); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with very large track list', async () => { // Scenario: Driver creates a league with very large track list // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; const manyTracks = Array.from({ length: 50 }, (_, i) => `Track ${i}`); // When: CreateLeagueUseCase.execute() is called with very large track list const command: LeagueCreateCommand = { name: 'Many Tracks League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, tracks: manyTracks, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with the large track list expect(result).toBeDefined(); expect(result.tracks).toEqual(manyTracks); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with custom scoring but no bonus points', async () => { // Scenario: Driver creates a league with custom scoring but no bonus points // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with custom scoring but bonus points disabled const command: LeagueCreateCommand = { name: 'Custom Scoring No Bonus League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, scoringSystem: { points: [10, 8, 6, 4, 2, 1] }, bonusPointsEnabled: false, penaltiesEnabled: true, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with custom scoring and no bonus points expect(result).toBeDefined(); expect(result.scoringSystem).toEqual({ points: [10, 8, 6, 4, 2, 1] }); expect(result.bonusPointsEnabled).toBe(false); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with stewarding but no protests', async () => { // Scenario: Driver creates a league with stewarding but no protests // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with stewarding but protests disabled const command: LeagueCreateCommand = { name: 'Stewarding No Protests League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: true, stewardTeam: ['steward-1'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with stewarding but no protests expect(result).toBeDefined(); expect(result.protestsEnabled).toBe(false); expect(result.appealsEnabled).toBe(true); expect(result.stewardTeam).toEqual(['steward-1']); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with stewarding but no appeals', async () => { // Scenario: Driver creates a league with stewarding but no appeals // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with stewarding but appeals disabled const command: LeagueCreateCommand = { name: 'Stewarding No Appeals League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: true, appealsEnabled: false, stewardTeam: ['steward-1'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with stewarding but no appeals expect(result).toBeDefined(); expect(result.protestsEnabled).toBe(true); expect(result.appealsEnabled).toBe(false); expect(result.stewardTeam).toEqual(['steward-1']); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with stewarding but empty steward team', async () => { // Scenario: Driver creates a league with stewarding but empty steward team // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with stewarding but empty steward team const command: LeagueCreateCommand = { name: 'Stewarding Empty Team League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: true, appealsEnabled: true, stewardTeam: [], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with stewarding but empty steward team expect(result).toBeDefined(); expect(result.stewardTeam).toEqual([]); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with schedule but no tracks', async () => { // Scenario: Driver creates a league with schedule but no tracks // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with schedule but no tracks const command: LeagueCreateCommand = { name: 'Schedule No Tracks League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, raceFrequency: 'weekly', raceDay: 'Monday', raceTime: '20:00', tracks: [], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with schedule but no tracks expect(result).toBeDefined(); expect(result.raceFrequency).toBe('weekly'); expect(result.tracks).toEqual([]); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with schedule but no race frequency', async () => { // Scenario: Driver creates a league with schedule but no race frequency // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with schedule but no race frequency const command: LeagueCreateCommand = { name: 'Schedule No Frequency League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, raceDay: 'Monday', raceTime: '20:00', tracks: ['Monza'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with schedule but no race frequency expect(result).toBeDefined(); expect(result.raceFrequency).toBeNull(); expect(result.raceDay).toBe('Monday'); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with schedule but no race day', async () => { // Scenario: Driver creates a league with schedule but no race day // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with schedule but no race day const command: LeagueCreateCommand = { name: 'Schedule No Day League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, raceFrequency: 'weekly', raceTime: '20:00', tracks: ['Monza'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with schedule but no race day expect(result).toBeDefined(); expect(result.raceDay).toBeNull(); expect(result.raceFrequency).toBe('weekly'); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should handle league with schedule but no race time', async () => { // Scenario: Driver creates a league with schedule but no race time // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with schedule but no race time const command: LeagueCreateCommand = { name: 'Schedule No Time League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, raceFrequency: 'weekly', raceDay: 'Monday', tracks: ['Monza'], }; const result = await createLeagueUseCase.execute(command); // Then: The league should be created with schedule but no race time expect(result).toBeDefined(); expect(result.raceTime).toBeNull(); expect(result.raceDay).toBe('Monday'); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); }); describe('CreateLeagueUseCase - Error Handling', () => { it('should create league even when driver does not exist', async () => { // Scenario: Non-existent driver tries to create a league // Given: No driver exists with the given ID const driverId = 'non-existent-driver'; // When: CreateLeagueUseCase.execute() is called with non-existent driver ID const command: LeagueCreateCommand = { name: 'Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: The league should be created (Use Case doesn't validate driver existence) const result = await createLeagueUseCase.execute(command); expect(result).toBeDefined(); expect(result.ownerId).toBe(driverId); // And: EventPublisher should emit LeagueCreatedEvent expect(eventPublisher.getLeagueCreatedEventCount()).toBe(1); }); it('should throw error when driver ID is invalid', async () => { // Scenario: Invalid driver ID // Given: An invalid driver ID (empty string) const driverId = ''; // When: CreateLeagueUseCase.execute() is called with invalid driver ID const command: LeagueCreateCommand = { name: 'Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: Should throw ValidationError (or generic Error if not specialized yet) await expect(createLeagueUseCase.execute(command)).rejects.toThrow('Owner ID is required'); // And: EventPublisher should NOT emit any events expect(eventPublisher.getLeagueCreatedEventCount()).toBe(0); }); it('should throw error when league name is empty', async () => { // Scenario: Empty league name // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with empty league name const command: LeagueCreateCommand = { name: '', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: Should throw error await expect(createLeagueUseCase.execute(command)).rejects.toThrow(); // And: EventPublisher should NOT emit any events expect(eventPublisher.getLeagueCreatedEventCount()).toBe(0); }); it('should throw error when league name is too long', async () => { // Scenario: League name exceeds maximum length // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; const longName = 'a'.repeat(256); // Assuming 255 is max // When: CreateLeagueUseCase.execute() is called with league name exceeding max length const command: LeagueCreateCommand = { name: longName, visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: Should throw error await expect(createLeagueUseCase.execute(command)).rejects.toThrow('League name is too long'); // And: EventPublisher should NOT emit any events expect(eventPublisher.getLeagueCreatedEventCount()).toBe(0); }); it('should throw error when max drivers is invalid', async () => { // Scenario: Invalid max drivers value // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called with invalid max drivers (negative number) const command: LeagueCreateCommand = { name: 'Test League', visibility: 'public', ownerId: driverId, maxDrivers: -1, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: Should throw error await expect(createLeagueUseCase.execute(command)).rejects.toThrow(); // And: EventPublisher should NOT emit any events expect(eventPublisher.getLeagueCreatedEventCount()).toBe(0); }); it('should throw error when repository throws error', async () => { // Scenario: Repository throws error during save // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // And: LeagueRepository throws an error during save const errorRepo = new InMemoryLeagueRepository(); errorRepo.create = async () => { throw new Error('Database error'); }; const errorUseCase = new CreateLeagueUseCase(errorRepo, eventPublisher); // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: Should propagate the error appropriately await expect(errorUseCase.execute(command)).rejects.toThrow('Database error'); // And: EventPublisher should NOT emit any events expect(eventPublisher.getLeagueCreatedEventCount()).toBe(0); }); it('should throw error when event publisher throws error', async () => { // Scenario: Event publisher throws error during emit // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // And: EventPublisher throws an error during emit const errorPublisher = new InMemoryLeagueEventPublisher(); errorPublisher.emitLeagueCreated = async () => { throw new Error('Publisher error'); }; const errorUseCase = new CreateLeagueUseCase(leagueRepository, errorPublisher); // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; // Then: Should propagate the error appropriately await expect(errorUseCase.execute(command)).rejects.toThrow('Publisher error'); // And: League should still be saved in repository (assuming no transaction or rollback implemented yet) const leagues = await leagueRepository.findByOwner(driverId); expect(leagues.length).toBe(1); }); }); describe('League Creation Data Orchestration', () => { it('should correctly associate league with creating driver as owner', async () => { // Scenario: League ownership association // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Ownership Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have the driver as owner expect(result.ownerId).toBe(driverId); // And: The driver should be listed in the league roster as owner const savedLeague = await leagueRepository.findById(result.id); expect(savedLeague?.ownerId).toBe(driverId); }); it('should correctly set league status to active', async () => { // Scenario: League status initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Status Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have status "active" expect(result.status).toBe('active'); }); it('should correctly set league creation timestamp', async () => { // Scenario: League creation timestamp // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Timestamp Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have a creation timestamp expect(result.createdAt).toBeDefined(); expect(result.createdAt instanceof Date).toBe(true); // And: The timestamp should be current or very recent const now = new Date().getTime(); expect(result.createdAt.getTime()).toBeLessThanOrEqual(now); expect(result.createdAt.getTime()).toBeGreaterThan(now - 5000); }); it('should correctly initialize league statistics', async () => { // Scenario: League statistics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Stats Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized statistics const stats = await leagueRepository.getStats(result.id); expect(stats).toBeDefined(); expect(stats.memberCount).toBe(1); // owner expect(stats.raceCount).toBe(0); expect(stats.sponsorCount).toBe(0); expect(stats.prizePool).toBe(0); expect(stats.rating).toBe(0); expect(stats.reviewCount).toBe(0); }); it('should correctly initialize league financials', async () => { // Scenario: League financials initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Financials Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized financials const financials = await leagueRepository.getFinancials(result.id); expect(financials).toBeDefined(); expect(financials.walletBalance).toBe(0); expect(financials.totalRevenue).toBe(0); expect(financials.totalFees).toBe(0); expect(financials.pendingPayouts).toBe(0); expect(financials.netBalance).toBe(0); }); it('should correctly initialize league stewarding metrics', async () => { // Scenario: League stewarding metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Stewarding Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized stewarding metrics const metrics = await leagueRepository.getStewardingMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.averageResolutionTime).toBe(0); expect(metrics.averageProtestResolutionTime).toBe(0); expect(metrics.averagePenaltyAppealSuccessRate).toBe(0); expect(metrics.averageProtestSuccessRate).toBe(0); expect(metrics.averageStewardingActionSuccessRate).toBe(0); }); it('should correctly initialize league performance metrics', async () => { // Scenario: League performance metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Performance Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized performance metrics const metrics = await leagueRepository.getPerformanceMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.averageLapTime).toBe(0); expect(metrics.averageFieldSize).toBe(0); expect(metrics.averageIncidentCount).toBe(0); expect(metrics.averagePenaltyCount).toBe(0); expect(metrics.averageProtestCount).toBe(0); expect(metrics.averageStewardingActionCount).toBe(0); }); it('should correctly initialize league rating metrics', async () => { // Scenario: League rating metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Rating Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized rating metrics const metrics = await leagueRepository.getRatingMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.overallRating).toBe(0); expect(metrics.ratingTrend).toBe(0); expect(metrics.rankTrend).toBe(0); expect(metrics.pointsTrend).toBe(0); expect(metrics.winRateTrend).toBe(0); expect(metrics.podiumRateTrend).toBe(0); expect(metrics.dnfRateTrend).toBe(0); }); it('should correctly initialize league trend metrics', async () => { // Scenario: League trend metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Trend Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized trend metrics const metrics = await leagueRepository.getTrendMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.incidentRateTrend).toBe(0); expect(metrics.penaltyRateTrend).toBe(0); expect(metrics.protestRateTrend).toBe(0); expect(metrics.stewardingActionRateTrend).toBe(0); expect(metrics.stewardingTimeTrend).toBe(0); expect(metrics.protestResolutionTimeTrend).toBe(0); }); it('should correctly initialize league success rate metrics', async () => { // Scenario: League success rate metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Success Rate Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized success rate metrics const metrics = await leagueRepository.getSuccessRateMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.penaltyAppealSuccessRate).toBe(0); expect(metrics.protestSuccessRate).toBe(0); expect(metrics.stewardingActionSuccessRate).toBe(0); expect(metrics.stewardingActionAppealSuccessRate).toBe(0); expect(metrics.stewardingActionPenaltySuccessRate).toBe(0); expect(metrics.stewardingActionProtestSuccessRate).toBe(0); }); it('should correctly initialize league resolution time metrics', async () => { // Scenario: League resolution time metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Resolution Time Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized resolution time metrics const metrics = await leagueRepository.getResolutionTimeMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.averageStewardingTime).toBe(0); expect(metrics.averageProtestResolutionTime).toBe(0); expect(metrics.averageStewardingActionAppealPenaltyProtestResolutionTime).toBe(0); }); it('should correctly initialize league complex success rate metrics', async () => { // Scenario: League complex success rate metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Complex Success Rate Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized complex success rate metrics const metrics = await leagueRepository.getComplexSuccessRateMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.stewardingActionAppealPenaltyProtestSuccessRate).toBe(0); expect(metrics.stewardingActionAppealProtestSuccessRate).toBe(0); expect(metrics.stewardingActionPenaltyProtestSuccessRate).toBe(0); }); it('should correctly initialize league complex resolution time metrics', async () => { // Scenario: League complex resolution time metrics initialization // Given: A driver exists with ID "driver-123" const driverId = 'driver-123'; // When: CreateLeagueUseCase.execute() is called const command: LeagueCreateCommand = { name: 'Complex Resolution Time Metrics Test League', visibility: 'public', ownerId: driverId, approvalRequired: false, lateJoinAllowed: false, bonusPointsEnabled: false, penaltiesEnabled: false, protestsEnabled: false, appealsEnabled: false, }; const result = await createLeagueUseCase.execute(command); // Then: The created league should have initialized complex resolution time metrics const metrics = await leagueRepository.getComplexResolutionTimeMetrics(result.id); expect(metrics).toBeDefined(); expect(metrics.stewardingActionAppealPenaltyProtestResolutionTime).toBe(0); expect(metrics.stewardingActionAppealProtestResolutionTime).toBe(0); expect(metrics.stewardingActionPenaltyProtestResolutionTime).toBe(0); }); }); });