From 381bcfea599c38fe734ae75289410ce78066ec13 Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Wed, 29 Nov 2023 11:49:00 +0200 Subject: [PATCH 01/10] test(*): working on increased coverage --- package-lock.json | 16 +- package.json | 4 +- projects/common/src/models/csgoplayer.ts | 4 +- .../services/bellumgens-api.service.spec.ts | 755 +++++++++++------- .../src/services/bellumgens-api.service.ts | 8 +- 5 files changed, 488 insertions(+), 299 deletions(-) diff --git a/package-lock.json b/package-lock.json index b2ce89dbe..c31131388 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,12 +21,12 @@ "@angular/service-worker": "17.0.4", "@angular/ssr": "^17.0.3", "@igniteui/material-icons-extended": "^3.0.2", - "@infragistics/igniteui-angular": "17.0.3", + "@infragistics/igniteui-angular": "17.0.4", "@types/express": "^4.17.17", "compression": "^1.7.4", "express": "^4.18.1", "hammerjs": "^2.0.8", - "igniteui-angular-i18n": "^17.0.3", + "igniteui-angular-i18n": "^17.0.4", "minireset.css": "0.0.4", "rxjs": "^7.8.0", "tslib": "^2.6.2", @@ -3296,9 +3296,9 @@ "integrity": "sha512-VBbaOKdG27cGiqljWHC0F4C0lDD1pqF7AzWuTcODcSN8olN33GpHlCXI4XQHZ2LUjpXIdD3Hkw/dR/YmhDH9MQ==" }, "node_modules/@infragistics/igniteui-angular": { - "version": "17.0.3", - "resolved": "https://packages.infragistics.com/npm/js-licensed/@infragistics/igniteui-angular/-/igniteui-angular-17.0.3.tgz", - "integrity": "sha512-AmtjDIf4szadTeipui1VfQT0fXDQPhX0lWzNE0l0Frsq4/I2HYOhjpX/iKLj1L5vdkxm5j3dwXd5bqS3zLokqA==", + "version": "17.0.4", + "resolved": "https://packages.infragistics.com/npm/js-licensed/@infragistics/igniteui-angular/-/igniteui-angular-17.0.4.tgz", + "integrity": "sha512-rKKXITPH/VbIrqfE5Irpc0oPkiOvZpJMCr/z/hHCESnEOe+UA/MonqhPQ3WEmGFD/lZrODooT7khSXvlb9K11g==", "license": "SEE LICENSE IN LICENSE", "dependencies": { "@igniteui/material-icons-extended": "^3.0.0", @@ -10199,9 +10199,9 @@ ] }, "node_modules/igniteui-angular-i18n": { - "version": "17.0.3", - "resolved": "https://registry.npmjs.org/igniteui-angular-i18n/-/igniteui-angular-i18n-17.0.3.tgz", - "integrity": "sha512-xbSfvFH4QiYK8FBAMChhGF2ntHI7ClFaDb57SomxjDrrFlPzYXmPUJ4A0yWXx9XyDxqPyBMa3are9LGQLkv2og==" + "version": "17.0.4", + "resolved": "https://registry.npmjs.org/igniteui-angular-i18n/-/igniteui-angular-i18n-17.0.4.tgz", + "integrity": "sha512-jMmkOmstF+Wjw8PEvwOQn91tLHaBBL9a/KydpuuZuiZ5GuZ90q0BzU7n+RGpxW428LK1quwEFcGmZCAaRLEXGQ==" }, "node_modules/igniteui-cli": { "version": "13.0.2", diff --git a/package.json b/package.json index 3cafdcd65..ad92698b3 100644 --- a/package.json +++ b/package.json @@ -43,12 +43,12 @@ "@angular/service-worker": "17.0.4", "@angular/ssr": "^17.0.3", "@igniteui/material-icons-extended": "^3.0.2", - "@infragistics/igniteui-angular": "17.0.3", + "@infragistics/igniteui-angular": "17.0.4", "@types/express": "^4.17.17", "compression": "^1.7.4", "express": "^4.18.1", "hammerjs": "^2.0.8", - "igniteui-angular-i18n": "^17.0.3", + "igniteui-angular-i18n": "^17.0.4", "minireset.css": "0.0.4", "rxjs": "^7.8.0", "tslib": "^2.6.2", diff --git a/projects/common/src/models/csgoplayer.ts b/projects/common/src/models/csgoplayer.ts index 803696732..05168495f 100644 --- a/projects/common/src/models/csgoplayer.ts +++ b/projects/common/src/models/csgoplayer.ts @@ -17,8 +17,8 @@ export interface CSGOPlayer extends ApplicationUser { userStats: CSGOStats; userStatsException: boolean; registered: boolean; - primaryRole: PlaystyleRole; - secondaryRole: PlaystyleRole; + primaryRole?: PlaystyleRole; + secondaryRole?: PlaystyleRole; headshotPercentage: number; killDeathRatio: number; accuracy: number; diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 1a26b006b..066ad83fd 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -7,11 +7,14 @@ import { Availability, DayOfWeek } from '../models/playeravailability'; import { PlaystyleRole, Role } from '../models/playerrole'; import { CSGOMap, CSGOMapPool } from '../models/csgomaps'; import { NotificationState, UserNotification } from '../models/usernotifications'; +import { CommunicationService } from './communication.service'; +import { CSGOPlayer } from '../public_api'; describe('BellumgensApiService', () => { let service: BellumgensApiService; let httpMock: HttpTestingController; + let commsService: CommunicationService; beforeEach(() => { TestBed.configureTestingModule({ @@ -20,6 +23,7 @@ describe('BellumgensApiService', () => { }); service = TestBed.inject(BellumgensApiService); httpMock = TestBed.inject(HttpTestingController); + commsService = TestBed.inject(CommunicationService); }); afterEach(() => { @@ -31,289 +35,474 @@ describe('BellumgensApiService', () => { }); // TODO: Extend each test with req.flush({}) to prevent errors in the console - describe('getUserTeams', () => { - it('should send a GET request to the correct URL', () => { - const userId = '123'; - service.getUserTeams(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/userteams?userid=${userId}`); - expect(req.request.method).toBe('GET'); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('teamApplications', () => { - it('should send a GET request to the correct URL', () => { - const teamId = '456'; - service.teamApplications(teamId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/applications?teamId=${teamId}`); - expect(req.request.method).toBe('GET'); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('getTeam', () => { - it('should send a GET request to the correct URL', () => { - const teamId = '789'; - service.getTeam(teamId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams?teamid=${teamId}`); - expect(req.request.method).toBe('GET'); - }); - }); - - describe('getTeamMembers', () => { - it('should send a GET request to the correct URL', () => { - const teamId = '012'; - service.getTeamMembers(teamId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/members?teamid=${teamId}`); - expect(req.request.method).toBe('GET'); - }); - }); - - describe('getTeamSchedule', () => { - it('should send a GET request to the correct URL', () => { - const teamId = '345'; - service.getTeamSchedule(teamId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability?teamid=${teamId}`); - expect(req.request.method).toBe('GET'); - }); - }); - - describe('registerSteamGroup', () => { - it('should send a POST request to the correct URL', () => { - const group: SteamGroup = { - groupID64: '678', - groupName: 'Test Group', - isPrimary: true, - avatarFull: 'test.jpg', - avatarMedium: 'test.jpg', - avatarIcon: 'test.jpg', - members: [] - }; - service.registerSteamGroup(group).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/team`); - expect(req.request.method).toBe('POST'); - expect(req.request.body).toEqual(group); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('registerTeam', () => { - it('should send a POST request to the correct URL', () => { - const team: CSGOTeam = { teamId: '901', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; - service.registerTeam(team).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/newteam`); - expect(req.request.method).toBe('POST'); - expect(req.request.body).toEqual(team); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('updateTeam', () => { - it('should send a PUT request to the correct URL', () => { - const team: CSGOTeam = { teamId: '234', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; - service.updateTeam(team).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/team`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(team); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('updateTeamMember', () => { - it('should send a PUT request to the correct URL', () => { - const teamMember: TeamMember = { - teamId: '567', - userId: '123', - steamId: '123456789', - isActive: true, - isAdmin: false, - isEditor: false, - role: PlaystyleRole.Awper, - username: 'Test User', - avatarIcon: 'test.jpg', - avatarMedium: 'test.jpg', - avatarFull: 'test.jpg', - customUrl: 'test', - country: 'DE', - realName: 'Test User' - }; - service.updateTeamMember(teamMember).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/member`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(teamMember); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('removeTeamMember', () => { - it('should send a DELETE request to the correct URL', () => { - const teamMember: TeamMember = { - teamId: '123', - userId: '456', - steamId: '123456789', - isActive: true, - isAdmin: false, - isEditor: false, - role: PlaystyleRole.EntryFragger, - username: 'Test User', - avatarIcon: 'test.jpg', - avatarMedium: 'test.jpg', - avatarFull: 'test.jpg', - customUrl: 'test', - country: 'DE', - realName: 'Test User' - }; - service.removeTeamMember(teamMember).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/removemember?teamId=${teamMember.teamId}&userId=${teamMember.userId}`); - expect(req.request.method).toBe('DELETE'); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('abandonTeam', () => { - it('should send a DELETE request to the correct URL', () => { - const team: CSGOTeam = { teamId: '123', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; - service.abandonTeam(team).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/abandon?teamId=${team.teamId}`); - expect(req.request.method).toBe('DELETE'); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('inviteToTeam', () => { - it('should send a POST request to the correct URL', () => { - const steamUser: SteamUser = { - steamID: '456', - steamID64: '2352345', - avatarIcon: 'test.jpg', - avatarMedium: 'test.jpg', - avatarFull: 'test.jpg', - realname: 'Test User', - location: 'Test Location', - country: 'DE', - summary: 'Test Summary', - customURL: 'test', - groups: [] - }; - const team: CSGOTeam = { teamId: '789', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; - service.inviteToTeam(steamUser, team).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/invite`); - expect(req.request.method).toBe('POST'); - expect(req.request.body).toEqual({userId: steamUser.steamID64, teamId: team.teamId}); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('submitApplication', () => { - it('should send a POST request to the correct URL', () => { - const application: TeamApplication = { applicantId: '012', teamId: '123', message: 'Test Application', state: NotificationState.NotSeen }; - service.submitApplication(application).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/apply`); - expect(req.request.method).toBe('POST'); - expect(req.request.body).toEqual(application); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('getTeamApplications', () => { - it('should send a GET request to the correct URL', () => { - const teamId = '345'; - service.getTeamApplications(teamId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/applications?teamId=${teamId}`); - expect(req.request.method).toBe('GET'); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('approveApplication', () => { - it('should send a PUT request to the correct URL', () => { - const application: TeamApplication = { applicantId: '678', teamId: '456', message: 'Test Application', state: NotificationState.NotSeen }; - service.approveApplication(application).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/approveapplication`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(application); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('rejectApplication', () => { - it('should send a PUT request to the correct URL', () => { - const application: TeamApplication = { applicantId: '456', teamId: '789', message: 'Test Application', state: NotificationState.NotSeen }; - service.rejectApplication(application).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/rejectapplication`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(application); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('setTeamMapPool', () => { - it('should send a PUT request to the correct URL', () => { - const mapstatus: CSGOMapPool[] = [ - { mapId: CSGOMap.Dust2, isPlayed: true }, - { mapId: CSGOMap.Inferno, isPlayed: true }, - { mapId: CSGOMap.Mirage, isPlayed: false }, - { mapId: CSGOMap.Nuke, isPlayed: false } - ]; - service.setTeamMapPool(mapstatus).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/mapPool`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(mapstatus); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('getTeamTournaments', () => { - it('should send a GET request to the correct URL', () => { - const teamid = '234'; - service.getTeamTournaments(teamid).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/tournaments?teamid=${teamid}`); - expect(req.request.method).toBe('GET'); - }); - }); - - describe('getTeamPractice', () => { - it('should send a GET request to the correct URL', () => { - const teamid = '567'; - service.getTeamPractice(teamid).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability?teamid=${teamid}`); - expect(req.request.method).toBe('GET'); - }); - }); - - describe('setTeamPractice', () => { - it('should send a PUT request to the correct URL', () => { - const day: Availability = { - teamId: '456', - day: DayOfWeek.Monday, - available: true, - from: new Date(), - to: new Date() - }; - service.setTeamPractice(day).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(day); - expect(req.request.withCredentials).toBe(true); - }); - }); - - describe('getPlayer', () => { - it('should send a GET request to the correct URL', () => { - const userId = '123'; - service.getPlayer(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users?userid=${userId}`); - expect(req.request.method).toBe('GET'); - }); - }); - - describe('getPlayerGroups', () => { - it('should send a GET request to the correct URL', () => { - const userId = '456'; - service.getPlayerGroups(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/usergroups?userid=${userId}`); - expect(req.request.method).toBe('GET'); - }); + it('getUserTeams should send a GET request to the correct URL', () => { + const userId = '123'; + service.getUserTeams(userId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/userteams?userid=${userId}`); + expect(req.request.method).toBe('GET'); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + }); + + it('teamApplications should send a GET request to the correct URL', () => { + const teamId = '456'; + const applications: TeamApplication [] = [{ applicantId: '678', teamId: '456', message: 'Test Application', state: NotificationState.NotSeen }]; + service.teamApplications(teamId).subscribe(data => expect(data).toEqual(applications)); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/applications?teamId=${teamId}`); + expect(req.request.method).toBe('GET'); + expect(req.request.withCredentials).toBe(true); + req.flush(applications); + }); + + it('getTeam should send a GET request to the correct URL', () => { + const teamId = '789'; + const mockteam: CSGOTeam = { teamId: '789', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; + service.getTeam(teamId).subscribe(); + expect(service['_teamReqInProgress']).toBe(true); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams?teamid=${teamId}`); + expect(req.request.method).toBe('GET'); + req.flush(mockteam); + expect(service['_teamReqInProgress']).toBe(false); + expect(service['_currentTeam'].value).toEqual(mockteam); + }); + + it('getTeamMembers should send a GET request to the correct URL', () => { + const teamId = '012'; + const teamMembers: TeamMember [] = [{ + teamId: '012', + userId: '123', + steamId: '123456789', + isActive: true, + isAdmin: false, + isEditor: false, + role: PlaystyleRole.Awper, + username: 'Test User', + avatarIcon: 'test.jpg', + avatarMedium: 'test.jpg', + avatarFull: 'test.jpg', + customUrl: 'test', + country: 'DE', + realName: 'Test User' + }]; + service.getTeamMembers(teamId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/members?teamid=${teamId}`); + expect(req.request.method).toBe('GET'); + req.flush(teamMembers); + expect(service['_currentTeamMembers'].value).toEqual(teamMembers); + }); + + it('getTeamSchedule should send a GET request to the correct URL', () => { + const teamId = '345'; + const availability: Availability[] = [{ + teamId: '345', + day: DayOfWeek.Monday, + available: true, + from: new Date(), + to: new Date() + }]; + service.getTeamSchedule(teamId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability?teamid=${teamId}`); + expect(req.request.method).toBe('GET'); + req.flush(availability); + expect(service['_currentTeamPractice'].value).toEqual(availability); + }); + + it('registerSteamGroup should send a POST request to the correct URL', () => { + const group: SteamGroup = { + groupID64: '678', + groupName: 'Test Group', + isPrimary: true, + avatarFull: 'test.jpg', + avatarMedium: 'test.jpg', + avatarIcon: 'test.jpg', + members: [] + }; + commsService.success.subscribe(success => expect(success).toBe(`${group.groupName} registered successfully!`)); + service.registerSteamGroup(group).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/team`); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual(group); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/team: 500 Steam Group already registered!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.registerSteamGroup(group).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/team`); + expect(req2.request.method).toBe('POST'); + expect(req2.request.body).toEqual(group); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Steam Group already registered!' }); + }); + + it('registerTeam should send a POST request to the correct URL', () => { + const team: CSGOTeam = { teamId: '901', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; + commsService.success.subscribe(success => expect(success).toBe(`${team.teamName} registered successfully!`)); + service.registerTeam(team).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/newteam`); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual(team); + expect(req.request.withCredentials).toBe(true); + req.flush(team); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/newteam: 500 Team already registered!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.registerTeam(team).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/newteam`); + expect(req2.request.method).toBe('POST'); + expect(req2.request.body).toEqual(team); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Team already registered!' }); + }); + + it('updateTeam should send a PUT request to the correct URL', () => { + const team: CSGOTeam = { teamId: '234', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; + commsService.success.subscribe(success => expect(success).toBe(`${team.teamName} updated successfully!`)); + service.updateTeam(team).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/team`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(team); + expect(req.request.withCredentials).toBe(true); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/team: 404 Team not found!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.updateTeam(team).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/team`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(team); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Not Found'), { status: 404, statusText: 'Team not found!' }); + }); + + it('updateTeamMember should send a PUT request to the correct URL', () => { + const teamMember: TeamMember = { + teamId: '567', + userId: '123', + steamId: '123456789', + isActive: true, + isAdmin: false, + isEditor: false, + role: PlaystyleRole.Awper, + username: 'Test User', + avatarIcon: 'test.jpg', + avatarMedium: 'test.jpg', + avatarFull: 'test.jpg', + customUrl: 'test', + country: 'DE', + realName: 'Test User' + }; + commsService.success.subscribe(success => expect(success).toBe(`${teamMember.username} updated successfully!`)); + service.updateTeamMember(teamMember).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/member`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(teamMember); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/member: 404 Team member not found!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.updateTeamMember(teamMember).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/member`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(teamMember); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Not Found'), { status: 404, statusText: 'Team member not found!' }); + }); + + it('removeTeamMember should send a DELETE request to the correct URL', () => { + const teamMember: TeamMember = { + teamId: '123', + userId: '456', + steamId: '123456789', + isActive: true, + isAdmin: false, + isEditor: false, + role: PlaystyleRole.EntryFragger, + username: 'Test User', + avatarIcon: 'test.jpg', + avatarMedium: 'test.jpg', + avatarFull: 'test.jpg', + customUrl: 'test', + country: 'DE', + realName: 'Test User' + }; + commsService.success.subscribe(success => expect(success).toBe(`${teamMember.username} removed from team!`)); + service.removeTeamMember(teamMember).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/removemember?teamId=${teamMember.teamId}&userId=${teamMember.userId}`); + expect(req.request.method).toBe('DELETE'); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/removemember?teamId=${teamMember.teamId}&userId=${teamMember.userId}: 404 Team member not found!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.removeTeamMember(teamMember).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/removemember?teamId=${teamMember.teamId}&userId=${teamMember.userId}`); + expect(req2.request.method).toBe('DELETE'); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Not Found'), { status: 404, statusText: 'Team member not found!' }); + }); + + it('abandonTeam should send a DELETE request to the correct URL', () => { + const team: CSGOTeam = { teamId: '123', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; + commsService.success.subscribe(success => expect(success).toBe(`You're are no longer part of ${team.teamName}`)); + service.abandonTeam(team).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/abandon?teamId=${team.teamId}`); + expect(req.request.method).toBe('DELETE'); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/abandon?teamId=${team.teamId}: 500 Could not remove team because there is an active tournament registration associated with it!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.abandonTeam(team).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/abandon?teamId=${team.teamId}`); + expect(req2.request.method).toBe('DELETE'); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not remove team because there is an active tournament registration associated with it!' }); + }); + + it('inviteToTeam should send a POST request to the correct URL', () => { + const steamUser: SteamUser = { + steamID: '456', + steamID64: '2352345', + avatarIcon: 'test.jpg', + avatarMedium: 'test.jpg', + avatarFull: 'test.jpg', + realname: 'Test User', + location: 'Test Location', + country: 'DE', + summary: 'Test Summary', + customURL: 'test', + groups: [] + }; + const team: CSGOTeam = { teamId: '789', teamName: 'Test Team', visible: true, teamAvatar: 'test.jpg' }; + commsService.success.subscribe(success => expect(success).toBe(`${steamUser.steamID} successfully invited to ${team.teamName}`)); + service.inviteToTeam(steamUser, team).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/invite`); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual({userId: steamUser.steamID64, teamId: team.teamId}); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/invite: 500 Could not invite user to team!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.inviteToTeam(steamUser, team).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/invite`); + expect(req2.request.method).toBe('POST'); + expect(req2.request.body).toEqual({userId: steamUser.steamID64, teamId: team.teamId}); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not invite user to team!' }); + }); + + it('submitApplication should send a POST request to the correct URL', () => { + const application: TeamApplication = { applicantId: '012', teamId: '123', message: 'Test Application', state: NotificationState.NotSeen }; + commsService.success.subscribe(success => expect(success).toBe('Application submitted successfully!')); + service.submitApplication(application).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/apply`); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual(application); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/apply: 500 Could not submit application!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.submitApplication(application).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/apply`); + expect(req2.request.method).toBe('POST'); + expect(req2.request.body).toEqual(application); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not submit application!' }); + }); + + it('getTeamApplications should send a GET request to the correct URL', () => { + const teamId = '345'; + service.getTeamApplications(teamId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/applications?teamId=${teamId}`); + expect(req.request.method).toBe('GET'); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + }); + + it('approveApplication should send a PUT request to the correct URL', () => { + const application: TeamApplication = { applicantId: '678', teamId: '456', message: 'Test Application', state: NotificationState.NotSeen }; + commsService.success.subscribe(success => expect(success).toBe(`${application.userName} is now part of your team!`)); + service.approveApplication(application).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/approveapplication`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(application); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/approveapplication: 500 Could not approve application!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.approveApplication(application).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/approveapplication`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(application); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not approve application!' }); + }); + + it('rejectApplication should send a PUT request to the correct URL', () => { + const application: TeamApplication = { applicantId: '456', teamId: '789', message: 'Test Application', state: NotificationState.NotSeen }; + commsService.success.subscribe(success => expect(success).toBe(`${application.userName} application has been rejected!`)); + service.rejectApplication(application).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/rejectapplication`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(application); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/rejectapplication: 500 Could not reject application!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.rejectApplication(application).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/rejectapplication`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(application); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not reject application!' }); + }); + + it('setTeamMapPool should send a PUT request to the correct URL', () => { + const mapstatus: CSGOMapPool[] = [ + { mapId: CSGOMap.Dust2, isPlayed: true }, + { mapId: CSGOMap.Inferno, isPlayed: true }, + { mapId: CSGOMap.Mirage, isPlayed: false }, + { mapId: CSGOMap.Nuke, isPlayed: false } + ]; + commsService.success.subscribe(success => expect(success).toBe('Map selection saved!')); + service.setTeamMapPool(mapstatus).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/mapPool`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(mapstatus); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/mapPool: 500 Could not save map selection!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setTeamMapPool(mapstatus).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/mapPool`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(mapstatus); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not save map selection!' }); + }); + + it('getTeamTournaments should send a GET request to the correct URL', () => { + const teamid = '234'; + service.getTeamTournaments(teamid).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/tournaments?teamid=${teamid}`); + expect(req.request.method).toBe('GET'); + req.flush({}); + }); + + it('getTeamPractice should send a GET request to the correct URL', () => { + const teamid = '567'; + service.getTeamPractice(teamid).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability?teamid=${teamid}`); + expect(req.request.method).toBe('GET'); + req.flush({}); + }); + + it('setTeamPractice should send a PUT request to the correct URL', () => { + const day: Availability = { + teamId: '456', + day: DayOfWeek.Monday, + available: true, + from: new Date(), + to: new Date() + }; + commsService.success.subscribe(success => expect(success).toBe('Practice schedule updated!')); + service.setTeamPractice(day).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(day); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/availability: 500 Could not update practice schedule!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setTeamPractice(day).subscribe({ + error: err => expect(err.message).toBe(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/teams/availability`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(day); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update practice schedule!' }); + }); + + it('getPlayer should send a GET request to the correct URL', () => { + const userId = '123'; + const player: CSGOPlayer = { + id: '1', + steamId: 'test-steam-id', + battleNetId: 'test-battlenet-id', + username: 'test-username', + email: 'test-email', + avatarFull: 'test-avatar', + avatarMedium: 'test-avatar', + avatarIcon: 'test-avatar', + customURL: 'test-url', + realname: 'test-realname', + searchVisible: true, + externalLogins: [], + steamUser: null, + steamUserException: false, + userStats: null, + userStatsException: false, + registered: false, + headshotPercentage: 0, + killDeathRatio: 0, + accuracy: 0, + steamPrivate: true + }; + service.getPlayer(userId).subscribe(); + expect(service.loadingPlayer.value).toBe(true); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users?userid=${userId}`); + expect(req.request.method).toBe('GET'); + req.flush(player); + expect(service.loadingPlayer.value).toBe(false); + expect(service['_currentPlayer'].value).toEqual(player); + + service.getPlayer(userId).subscribe({ + error: () => { + expect(service.loadingPlayer.value).toBe(false); + expect(service['_currentPlayer'].value).toBeNull(); + } + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users?userid=${userId}`); + expect(req2.request.method).toBe('GET'); + req2.error(new ProgressEvent('Not Found'), { status: 404, statusText: 'Player not found!' }); + }); + + it('getPlayerGroups should send a GET request to the correct URL', () => { + const userId = '456'; + service.getPlayerGroups(userId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/usergroups?userid=${userId}`); + expect(req.request.method).toBe('GET'); + req.flush({}); }); describe('getPlayerFromServer', () => { diff --git a/projects/common/src/services/bellumgens-api.service.ts b/projects/common/src/services/bellumgens-api.service.ts index 9ec24187c..ad0af4cb9 100644 --- a/projects/common/src/services/bellumgens-api.service.ts +++ b/projects/common/src/services/bellumgens-api.service.ts @@ -252,16 +252,16 @@ export class BellumgensApiService { if (!this.playerMatch(userId)) { this._currentPlayer.next(null); this.loadingPlayer.next(true); - this.getPlayerFromServer(userId).subscribe( - player => { + this.getPlayerFromServer(userId).subscribe({ + next: player => { this._currentPlayer.next(player); this.loadingPlayer.next(false); }, - () => { + error: () => { this._currentPlayer.next(null); this.loadingPlayer.next(false); } - ); + }); } return this._currentPlayer; } From 8a1589478dacd8e0c9e519715db0ccafa3a7d81a Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Thu, 30 Nov 2023 09:09:52 +0200 Subject: [PATCH 02/10] chore(*): fixing styling issues --- angular.json | 10 ++- .../src/app/events/events.component.scss | 7 +- .../services/bellumgens-api.service.spec.ts | 69 ++++++++++--------- projects/common/src/styles.scss | 2 +- 4 files changed, 53 insertions(+), 35 deletions(-) diff --git a/angular.json b/angular.json index 1b80ae528..c42a33c6b 100644 --- a/angular.json +++ b/angular.json @@ -26,7 +26,10 @@ "outputPath": "dist/bellumgens/browser", "index": "projects/bellumgens/src/index.html", "main": "projects/bellumgens/src/main.ts", - "polyfills": ["zone.js"], + "polyfills": [ + "zone.js", + "@angular/localize/init" + ], "tsConfig": "projects/bellumgens/tsconfig.app.json", "assets": [ "projects/bellumgens/src/favicon.ico", @@ -352,7 +355,10 @@ "builder": "@angular-devkit/build-angular:karma", "options": { "main": "projects/ebleague/src/test.ts", - "polyfills": ["zone.js"], + "polyfills": [ + "zone.js", + "@angular/localize/init" + ], "tsConfig": "projects/ebleague/tsconfig.spec.json", "karmaConfig": "projects/ebleague/karma.conf.js", "styles": [ diff --git a/projects/bellumgens/src/app/events/events.component.scss b/projects/bellumgens/src/app/events/events.component.scss index 9bafbc724..16d8fd632 100644 --- a/projects/bellumgens/src/app/events/events.component.scss +++ b/projects/bellumgens/src/app/events/events.component.scss @@ -1,8 +1,11 @@ :host { display: flex; - height: 100%; + height: calc(100% - 45px); width: 100%; background-image: url('/assets/bge/bge-background-right.jpg'); + background-repeat: no-repeat; + background-size: cover; + background-position: bottom right; @font-face { font-family: 'dge-ebold'; @@ -42,6 +45,8 @@ } @media screen and (max-width: 1024px) { + background-position: center; + .content-container h1 { font-size: 36pt; } diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 066ad83fd..52dce001b 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -167,6 +167,7 @@ describe('BellumgensApiService', () => { expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual(team); expect(req.request.withCredentials).toBe(true); + req.flush({}); const errorMessage = `Http failure response for ${service['_apiEndpoint']}/teams/team: 404 Team not found!`; commsService.error.subscribe(error => expect(error).toBe(errorMessage)); @@ -454,7 +455,7 @@ describe('BellumgensApiService', () => { }); it('getPlayer should send a GET request to the correct URL', () => { - const userId = '123'; + let userId = '1'; const player: CSGOPlayer = { id: '1', steamId: 'test-steam-id', @@ -471,13 +472,14 @@ describe('BellumgensApiService', () => { steamUser: null, steamUserException: false, userStats: null, - userStatsException: false, + userStatsException: true, registered: false, headshotPercentage: 0, killDeathRatio: 0, accuracy: 0, steamPrivate: true }; + const sub1 = commsService.error.subscribe(error => expect(error).toBe('Account is private!')); service.getPlayer(userId).subscribe(); expect(service.loadingPlayer.value).toBe(true); const req = httpMock.expectOne(`${service['_apiEndpoint']}/users?userid=${userId}`); @@ -486,12 +488,16 @@ describe('BellumgensApiService', () => { expect(service.loadingPlayer.value).toBe(false); expect(service['_currentPlayer'].value).toEqual(player); + sub1.unsubscribe(); + commsService.error.subscribe(error => expect(error).toBe(`Http failure response for ${service['_apiEndpoint']}/users?userid=2: 404 Player not found!`)); + userId = '2'; service.getPlayer(userId).subscribe({ error: () => { expect(service.loadingPlayer.value).toBe(false); expect(service['_currentPlayer'].value).toBeNull(); } }); + expect(service.loadingPlayer.value).toBe(true); const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users?userid=${userId}`); expect(req2.request.method).toBe('GET'); req2.error(new ProgressEvent('Not Found'), { status: 404, statusText: 'Player not found!' }); @@ -505,39 +511,40 @@ describe('BellumgensApiService', () => { req.flush({}); }); - describe('getPlayerFromServer', () => { - it('should send a GET request to the correct URL', () => { - const userId = '789'; - service.getPlayerFromServer(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users?userid=${userId}`); - expect(req.request.method).toBe('GET'); - }); + it('player getAvailability should send a GET request to the correct URL', () => { + const userId = '012'; + service.getAvailability(userId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/availability?userid=${userId}`); + expect(req.request.method).toBe('GET'); + req.flush({}); }); - describe('player getAvailability', () => { - it('should send a GET request to the correct URL', () => { - const userId = '012'; - service.getAvailability(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/availability?userid=${userId}`); - expect(req.request.method).toBe('GET'); - }); - }); + it('player setAvailability should send a PUT request to the correct URL', () => { + const availability: Availability = { + userId: '123', + day: DayOfWeek.Monday, + available: true, + from: new Date(), + to: new Date() + }; + commsService.success.subscribe(success => expect(success).toBe('Availability updated!')); + service.setAvailability(availability).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/availability`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(availability); + expect(req.request.withCredentials).toBe(true); + req.flush({}); - describe('player setAvailability', () => { - it('should send a PUT request to the correct URL', () => { - const availability: Availability = { - userId: '123', - day: DayOfWeek.Monday, - available: true, - from: new Date(), - to: new Date() - }; - service.setAvailability(availability).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/availability`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(availability); - expect(req.request.withCredentials).toBe(true); + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/availability: 500 Could not update availability!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setAvailability(availability).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/availability`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(availability); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update availability!' }); }); describe('setPrimaryRole', () => { diff --git a/projects/common/src/styles.scss b/projects/common/src/styles.scss index 5f316c114..ee83b3667 100644 --- a/projects/common/src/styles.scss +++ b/projects/common/src/styles.scss @@ -189,7 +189,7 @@ textarea { .card-wrapper { display: grid; - grid-template-columns: repeat(auto-fill, minmax(333px, 1fr)); + grid-template-columns: repeat(auto-fill, minmax(334px, 1fr)); grid-gap: 16px; grid-auto-rows: max-content; margin: 24px; From fbb05ffa996980c7c5cf433bcd424bb4aa98f3a0 Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Thu, 30 Nov 2023 13:54:23 +0200 Subject: [PATCH 03/10] test(*): adding more tests --- .../src/lib/login/login.component.spec.ts | 2 - .../user-preferences.component.spec.ts | 153 +++++++++++++++--- .../user-preferences.component.ts | 29 +++- 3 files changed, 153 insertions(+), 31 deletions(-) diff --git a/projects/common/src/lib/login/login.component.spec.ts b/projects/common/src/lib/login/login.component.spec.ts index f6c1c2a41..cf23415cd 100644 --- a/projects/common/src/lib/login/login.component.spec.ts +++ b/projects/common/src/lib/login/login.component.spec.ts @@ -3,7 +3,6 @@ import { LoginComponent } from './login.component'; import { RouterTestingModule } from '@angular/router/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { ServiceWorkerModule } from '@angular/service-worker'; -import { FormsModule } from '@angular/forms'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ApplicationUser, LoginService } from '../../public_api'; import { Router } from '@angular/router'; @@ -32,7 +31,6 @@ describe('LoginComponent', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ - FormsModule, RouterTestingModule, NoopAnimationsModule, HttpClientTestingModule, diff --git a/projects/common/src/lib/login/user-preferences/user-preferences.component.spec.ts b/projects/common/src/lib/login/user-preferences/user-preferences.component.spec.ts index 5a11d7c8c..7bf1455f8 100644 --- a/projects/common/src/lib/login/user-preferences/user-preferences.component.spec.ts +++ b/projects/common/src/lib/login/user-preferences/user-preferences.component.spec.ts @@ -1,55 +1,160 @@ import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; - import { UserPreferencesComponent } from './user-preferences.component'; -import { FormsModule } from '@angular/forms'; -import { - IgxSwitchModule, - IgxIconModule, - IgxDialogModule, - IgxRippleModule, - IgxDividerModule, - IgxButtonModule, - IgxListModule -} from '@infragistics/igniteui-angular'; import { ServiceWorkerModule } from '@angular/service-worker'; import { RouterTestingModule } from '@angular/router/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; -import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { ConfirmComponent } from '../../confirm/confirm.component'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { Router } from '@angular/router'; +import { ApplicationUser, CommunicationService, Game, LoginProvider, LoginService, TournamentApplication, TournamentApplicationState } from '../../../public_api'; + describe('UserPreferencesComponent', () => { let component: UserPreferencesComponent; let fixture: ComponentFixture; + let httpMock: HttpTestingController; + let commsService: CommunicationService; + let router: Router; + let authService: LoginService; + const providers: LoginProvider [] = [ + { name: 'Steam', state: 'test', url: 'test' }, + { name: 'BattleNet', state: 'test', url: 'test' } + ]; + const applicationUser: ApplicationUser = { + id: '1', + steamId: 'test-steam-id', + battleNetId: 'test-battlenet-id', + username: 'test-user', + email: 'test-email', + avatarFull: 'test-avatar', + avatarMedium: 'test-avatar', + avatarIcon: 'test-avatar', + customURL: 'test-url', + realname: 'test-realname', + searchVisible: false, + externalLogins: [ + 'Steam' + ] + }; + const registrations: TournamentApplication [] = [ + { id: '1', game: Game.CSGO, email: 'test-email', dateSubmitted: new Date(), state: TournamentApplicationState.Pending }, + { id: '2', game: Game.StarCraft2, email: 'test-email', dateSubmitted: new Date(), state: TournamentApplicationState.Pending } + ]; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ - FormsModule, HttpClientTestingModule, RouterTestingModule, NoopAnimationsModule, ServiceWorkerModule.register('', { enabled: false }), - IgxSwitchModule, - IgxIconModule, - IgxDialogModule, - IgxDividerModule, - IgxButtonModule, - IgxDividerModule, - IgxRippleModule, - IgxListModule, - UserPreferencesComponent, - ConfirmComponent + UserPreferencesComponent ] }).compileComponents(); + authService = TestBed.inject(LoginService); + httpMock = TestBed.inject(HttpTestingController); + commsService = TestBed.inject(CommunicationService); + router = TestBed.get(Router); })); beforeEach(() => { fixture = TestBed.createComponent(UserPreferencesComponent); component = fixture.componentInstance; fixture.detectChanges(); + const req = httpMock.expectOne(`${authService['_apiEndpoint']}`); + req.flush(applicationUser); + const req2 = httpMock.expectOne(`${authService['_apiBase']}/tournament/registrations`); + req2.flush(registrations); + const req3 = httpMock.expectOne(`${authService['_apiEndpoint']}/ExternalLogins?returnUrl=%2F`); + req3.flush(providers); }); it('should create', () => { expect(component).toBeTruthy(); }); + + it('should have default preferences', () => { + expect(component.authUser).toBe(applicationUser); + expect(component.preferences).toEqual({ searchVisible: false, email: 'test-email' }); + }); + + it('should have providers', () => { + expect(component.providers).toEqual(providers); + }); + + it('should have registrations', () => { + expect(component.registrations).toEqual(registrations); + expect(authService['_registrations'].value).toEqual(registrations); + }); + + it('should call login method', () => { + spyOn(authService, 'login'); + component.login(providers[0]); + expect(authService.login).toHaveBeenCalledWith(providers[0]); + }); + + it('should call submitPreferences method', () => { + commsService.success.subscribe(message => expect(message).toEqual('Preferences updated successfully!')); + component.submitPreferences(); + const req = httpMock.expectOne(`${authService['_apiEndpoint']}/userinfo`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(component.preferences); + expect(req.request.withCredentials).toBeTrue(); + req.flush({}); + + commsService.error.subscribe(message => expect(message).toEqual(`Http failure response for ${authService['_apiEndpoint']}/userinfo: 500 Something went wrong!`)); + component.submitPreferences(); + const req2 = httpMock.expectOne(`${authService['_apiEndpoint']}/userinfo`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(component.preferences); + expect(req2.request.withCredentials).toBeTrue(); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Something went wrong!' }); + }); + + it('should call deleteAccount method', () => { + commsService.success.subscribe(message => expect(message).toEqual('Account deleted!')); + component.deleteAccount(); + const req = httpMock.expectOne(`${authService['_apiEndpoint']}/delete?userid=${applicationUser.id}`); + expect(req.request.method).toBe('DELETE'); + expect(req.request.withCredentials).toBeTrue(); + req.flush({}); + + commsService.error.subscribe(message => expect(message).toEqual(`Http failure response for ${authService['_apiEndpoint']}/delete?userid=${applicationUser.id}: 500 Something went wrong!`)); + component.deleteAccount(); + const req2 = httpMock.expectOne(`${authService['_apiEndpoint']}/delete?userid=${applicationUser.id}`); + expect(req2.request.method).toBe('DELETE'); + expect(req2.request.withCredentials).toBeTrue(); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Something went wrong!' }); + }); + + it('should call deleteRegistration method', () => { + expect(component.registrations).toEqual(registrations); + expect(authService['_registrations'].value).toEqual(registrations); + + const registration = registrations[0]; + commsService.success.subscribe(message => expect(message).toEqual('Tournament application deleted successfully!')); + component.deleteRegistration(registration); + const req2 = httpMock.expectOne(`${authService['_apiBase']}/tournament/delete?id=${registration.id}`); + expect(req2.request.method).toBe('DELETE'); + expect(req2.request.withCredentials).toBeTrue(); + req2.flush({}); + expect(component.registrations).toEqual([registrations[0]]); + + commsService.error.subscribe(message => expect(message).toEqual(`Http failure response for ${authService['_apiBase']}/tournament/delete?id=${registration.id}: 500 Something went wrong!`)); + component.deleteRegistration(registration); + const req3 = httpMock.expectOne(`${authService['_apiBase']}/tournament/delete?id=${registration.id}`); + expect(req3.request.method).toBe('DELETE'); + expect(req3.request.withCredentials).toBeTrue(); + req3.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Something went wrong!' }); + }); + + it('disableLogin should return true for externalLogins on the authUser', () => { + expect(component.disableLogin('BattleNet')).toBeFalse(); + expect(component.disableLogin('Steam')).toBeTrue(); + }); + + it('should call openRegistration method', () => { + spyOn(router, 'navigate'); + component.openRegistration(); + expect(router.navigate).toHaveBeenCalledWith(['register']); + }); }); diff --git a/projects/common/src/lib/login/user-preferences/user-preferences.component.ts b/projects/common/src/lib/login/user-preferences/user-preferences.component.ts index 50a49810b..eb3ec171b 100644 --- a/projects/common/src/lib/login/user-preferences/user-preferences.component.ts +++ b/projects/common/src/lib/login/user-preferences/user-preferences.component.ts @@ -16,7 +16,19 @@ import { NgFor, NgClass, NgIf } from '@angular/common'; templateUrl: './user-preferences.component.html', styleUrls: ['./user-preferences.component.scss'], standalone: true, - imports: [NgFor, IgxButtonModule, IgxRippleModule, IgxIconModule, IgxDividerModule, IgxSwitchModule, FormsModule, IgxListModule, NgClass, NgIf, ConfirmComponent] + imports: [ + NgFor, + IgxButtonModule, + IgxRippleModule, + IgxIconModule, + IgxDividerModule, + IgxSwitchModule, + FormsModule, + IgxListModule, + NgClass, + NgIf, + ConfirmComponent + ] }) export class UserPreferencesComponent { public preferences: UserPreferences = { @@ -48,16 +60,23 @@ export class UserPreferencesComponent { } public submitPreferences() { - this.authManager.updateUserPreferences(this.preferences).subscribe(); + this.authManager.updateUserPreferences(this.preferences).subscribe({ + error: () => {} + }); } public deleteAccount() { - this.authManager.deleteAccount(this.authUser.id).subscribe(); + this.authManager.deleteAccount(this.authUser.id).subscribe({ + error: () => {} + }); } public deleteRegistration(registration: TournamentApplication) { - this.apiService.deleteRegistration(registration.id).subscribe(() => { - this.registrations.splice(this.registrations.indexOf(registration), 1); + this.apiService.deleteRegistration(registration.id).subscribe({ + next: () => { + this.registrations.splice(this.registrations.indexOf(registration), 1); + }, + error: () => {} }); } From 37d9a2134bbe9ea3bdf04acdb3024352452ea9de Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Thu, 30 Nov 2023 14:09:12 +0200 Subject: [PATCH 04/10] test(api service): increasing coverage --- .../services/bellumgens-api.service.spec.ts | 148 ++++++++++++------ 1 file changed, 101 insertions(+), 47 deletions(-) diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 52dce001b..2d7364594 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -547,67 +547,121 @@ describe('BellumgensApiService', () => { req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update availability!' }); }); - describe('setPrimaryRole', () => { - it('should send a PUT request to the correct URL', () => { - const role: Role = { id: PlaystyleRole.Awper, name: 'Awper' }; - service.setPrimaryRole(role).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(role); - expect(req.request.withCredentials).toBe(true); + it('setPrimaryRole should send a PUT request to the correct URL', () => { + const role: Role = { id: PlaystyleRole.Awper, name: 'Awper' }; + commsService.success.subscribe(success => expect(success).toBe(`Primary role set to ${role.name}`)); + service.setPrimaryRole(role).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(role); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/primaryrole?id=${role.id}: 500 Could not update primary role!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setPrimaryRole(role).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(role); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update primary role!' }); }); - describe('setSecondaryRole', () => { - it('should send a PUT request to the correct URL', () => { - const role: Role = { id: PlaystyleRole.IGL, name: 'Ingame Leader' }; - service.setSecondaryRole(role).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(role); - expect(req.request.withCredentials).toBe(true); + it('setSecondaryRole should send a PUT request to the correct URL', () => { + const role: Role = { id: PlaystyleRole.IGL, name: 'Ingame Leader' }; + commsService.success.subscribe(success => expect(success).toBe(`Secondary role set to ${role.name}`)); + service.setSecondaryRole(role).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(role); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}: 500 Could not update secondary role!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setSecondaryRole(role).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(role); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update secondary role!' }); }); - describe('getMapPool', () => { - it('should send a GET request to the correct URL', () => { - const userId = '234'; - service.getMapPool(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool?userid=${userId}`); - expect(req.request.method).toBe('GET'); - }); + it('getMapPool should send a GET request to the correct URL', () => { + const userId = '234'; + service.getMapPool(userId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool?userid=${userId}`); + expect(req.request.method).toBe('GET'); + req.flush({}); }); - describe('setMapPool', () => { - it('should send a PUT request to the correct URL', () => { - const mapstatus: CSGOMapPool = { mapId: CSGOMap.Dust2, isPlayed: true }; - service.setMapPool(mapstatus).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(mapstatus); - expect(req.request.withCredentials).toBe(true); + it('setMapPool should send a PUT request to the correct URL', () => { + const mapstatus: CSGOMapPool = { mapId: CSGOMap.Dust2, isPlayed: true }; + commsService.success.subscribe(success => expect(success).toBe('Map pool updated!')); + service.setMapPool(mapstatus).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(mapstatus); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/mapPool: 500 Could not update map pool!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setMapPool(mapstatus).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(mapstatus); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update map pool!' }); }); - describe('acceptInvite', () => { - it('should send a PUT request to the correct URL', () => { - const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; - service.acceptInvite(notification).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(notification); - expect(req.request.withCredentials).toBe(true); + it('acceptInvite should send a PUT request to the correct URL', () => { + const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; + commsService.success.subscribe(success => expect(success).toBe('Team invite accepted!')); + service.acceptInvite(notification).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(notification); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/acceptTeamInvite: 500 Could not accept team invite!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.acceptInvite(notification).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(notification); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not accept team invite!' }); }); - describe('rejectInvite', () => { - it('should send a PUT request to the correct URL', () => { - const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; - service.rejectInvite(notification).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(notification); - expect(req.request.withCredentials).toBe(true); + it('rejectInvite should send a PUT request to the correct URL', () => { + const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; + commsService.success.subscribe(success => expect(success).toBe('Team invite rejected!')); + service.rejectInvite(notification).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(notification); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/rejectTeamInvite: 500 Could not reject team invite!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.rejectInvite(notification).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(notification); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not reject team invite!' }); }); }); From b4f980950ca857820a3e375001dc572b91464857 Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Thu, 30 Nov 2023 16:31:16 +0200 Subject: [PATCH 05/10] test(api search): increasing coverage --- .../bellumgens-api.search.service.spec.ts | 36 ++++++++++++++----- .../services/bellumgens-api.search.service.ts | 9 ++--- .../services/bellumgens-api.service.spec.ts | 1 - 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/projects/common/src/services/bellumgens-api.search.service.spec.ts b/projects/common/src/services/bellumgens-api.search.service.spec.ts index a308a261b..50ba08455 100644 --- a/projects/common/src/services/bellumgens-api.search.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.search.service.spec.ts @@ -1,11 +1,14 @@ import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { ApiSearchService } from './bellumgens-api.search.service'; +import { CommunicationService } from './communication.service'; +import { SearchResult } from '../public_api'; describe('ApiSearchService', () => { let service: ApiSearchService; let httpMock: HttpTestingController; + let commService: CommunicationService; beforeEach(() => { TestBed.configureTestingModule({ @@ -13,6 +16,7 @@ describe('ApiSearchService', () => { providers: [ ApiSearchService ] }); service = TestBed.inject(ApiSearchService); + commService = TestBed.inject(CommunicationService); httpMock = TestBed.inject(HttpTestingController); }); @@ -25,14 +29,30 @@ describe('ApiSearchService', () => { }); // TODO: Extend each test with req.flush({}) to prevent errors in the console - describe('quickSearch', () => { - it('should make a GET request to the API endpoint with the provided name', () => { - const name = 'testName'; - service.searchResult.subscribe(); - service.quickSearch(name); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=${name}`); - expect(req.request.method).toBe('GET'); - }); + it('should make a GET request to the API endpoint with the provided name', () => { + let name = 'testName'; + const result: SearchResult = { + players: [], + strategies: [], + teams: [], + steamUser: null + }; + service.quickSearch(name); + expect(service.loadingQuickSearch.value).toBeTruthy(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=${name}`); + expect(req.request.method).toBe('GET'); + req.flush(result); + expect(service.searchResult.value).toEqual(result); + expect(service.loadingQuickSearch.value).toBeFalsy(); + expect(service['_searchResultCache'].get(name)).toEqual(result); + + name = 'test'; + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/search?name=${name}: 500 Could not retrieve search results!`; + commService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.quickSearch(name); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=${name}`); + expect(req2.request.method).toBe('GET'); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve search results!' }); }); describe('searchTeams', () => { diff --git a/projects/common/src/services/bellumgens-api.search.service.ts b/projects/common/src/services/bellumgens-api.search.service.ts index 105effcaf..1a9927858 100644 --- a/projects/common/src/services/bellumgens-api.search.service.ts +++ b/projects/common/src/services/bellumgens-api.search.service.ts @@ -35,13 +35,14 @@ export class ApiSearchService { this.searchResult.next(this._searchResultCache.get(name)); } else { this.loadingQuickSearch.next(true); - this.getQuickSearch(name).subscribe( - data => { + this.getQuickSearch(name).subscribe({ + next: data => { this._searchResultCache.set(name, data); this.searchResult.next(data); this.loadingQuickSearch.next(false); - } - ); + }, + error: () => this.loadingQuickSearch.next(false) + }); } } diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 2d7364594..53cdf98f6 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -34,7 +34,6 @@ describe('BellumgensApiService', () => { expect(service).toBeTruthy(); }); - // TODO: Extend each test with req.flush({}) to prevent errors in the console it('getUserTeams should send a GET request to the correct URL', () => { const userId = '123'; service.getUserTeams(userId).subscribe(); From 66e3c6e9f2b5f94042f7c0699874c42e4fed89c3 Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Thu, 30 Nov 2023 18:46:09 +0200 Subject: [PATCH 06/10] test(api search): adding more tests --- .../bellumgens-api.search.service.spec.ts | 169 +++++++++++++++--- .../services/bellumgens-api.search.service.ts | 27 +-- .../services/bellumgens-api.service.spec.ts | 148 +++++---------- 3 files changed, 205 insertions(+), 139 deletions(-) diff --git a/projects/common/src/services/bellumgens-api.search.service.spec.ts b/projects/common/src/services/bellumgens-api.search.service.spec.ts index 50ba08455..e582280eb 100644 --- a/projects/common/src/services/bellumgens-api.search.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.search.service.spec.ts @@ -2,7 +2,7 @@ import { HttpClientTestingModule, HttpTestingController } from '@angular/common/ import { TestBed } from '@angular/core/testing'; import { ApiSearchService } from './bellumgens-api.search.service'; import { CommunicationService } from './communication.service'; -import { SearchResult } from '../public_api'; +import { CSGOMap, CSGOPlayer, CSGOTeam, SearchResult, Side } from '../public_api'; describe('ApiSearchService', () => { @@ -28,7 +28,6 @@ describe('ApiSearchService', () => { expect(service).toBeTruthy(); }); - // TODO: Extend each test with req.flush({}) to prevent errors in the console it('should make a GET request to the API endpoint with the provided name', () => { let name = 'testName'; const result: SearchResult = { @@ -55,33 +54,151 @@ describe('ApiSearchService', () => { req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve search results!' }); }); - describe('searchTeams', () => { - it('should make a GET request to the API endpoint with the provided query', () => { - const query = 'testQuery'; - service.teamSearchResult.subscribe(); - service.searchTeams(query); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/search/teams?${query}`); - expect(req.request.method).toBe('GET'); - }); + it('searchTeams should make a GET request to the API endpoint with the provided query', () => { + let query = 'role=1&overlap=1'; + const teams: CSGOTeam[] = [ + { teamName: 'testTeam', teamId: '1', teamAvatar: 'testLogo', visible: true, description: 'testDescription'}, + { teamName: 'testTeam2', teamId: '2', teamAvatar: 'testLogo2', visible: true, description: 'testDescription2'} + ]; + service.searchTeams(query); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/search/teams?${query}`); + expect(req.request.method).toBe('GET'); + expect(service.loadingSearch.value).toBeTruthy(); + expect(service.teamSearchResult.value).toEqual([]); + req.flush(teams); + expect(service.loadingSearch.value).toBeFalsy(); + expect(service.teamSearchResult.value).toEqual(teams); + expect(service['_teamSearchCache'].get(query)).toEqual(teams); + + query = 'role=2&overlap=1'; + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/search/teams?${query}: 500 Could not retrieve search results!`; + commService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.searchTeams(query); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/search/teams?${query}`); + expect(req2.request.method).toBe('GET'); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve search results!' }); + + // Should return teams from the quick search result cache if the query starts with 'name' + query = 'name=test'; + const result: SearchResult = { + players: [], + strategies: [], + teams: [ + { teamName: 'test', teamId: '1', teamAvatar: 'testLogo', visible: true, description: 'testDescription'} + ], + steamUser: null + }; + service.quickSearch('test'); + const req3 = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=test`); + expect(req3.request.method).toBe('GET'); + req3.flush(result); + service.searchTeams(query); + expect(service.teamSearchResult.value).toEqual(result.teams); }); - describe('searchPlayers', () => { - it('should make a GET request to the API endpoint with the provided query', () => { - const query = 'testQuery'; - service.playerSearchResult.subscribe(); - service.searchPlayers(query); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/search/players?${query}`); - expect(req.request.method).toBe('GET'); - }); + it('searchPlayers should make a GET request to the API endpoint with the provided query', () => { + let query = 'role=1&overlap=1'; + const players: CSGOPlayer [] = [ + { + id: '1', + steamId: 'test-steam-id', + battleNetId: 'test-battlenet-id', + username: 'test-username', + email: 'test-email', + avatarFull: 'test-avatar', + avatarMedium: 'test-avatar', + avatarIcon: 'test-avatar', + customURL: 'test-url', + realname: 'test-realname', + searchVisible: true, + externalLogins: [], + steamUser: null, + steamUserException: false, + userStats: null, + userStatsException: true, + registered: false, + headshotPercentage: 0, + killDeathRatio: 0, + accuracy: 0, + steamPrivate: true + } + ]; + service.searchPlayers(query); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/search/players?${query}`); + expect(req.request.method).toBe('GET'); + expect(service.loadingSearch.value).toBeTruthy(); + req.flush(players); + expect(service.loadingSearch.value).toBeFalsy(); + expect(service.playerSearchResult.value).toEqual(players); + expect(service['_playerSearchCache'].get(query)).toEqual(players); + + query = 'role=2&overlap=1'; + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/search/players?${query}: 500 Could not retrieve search results!`; + commService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.searchPlayers(query); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/search/players?${query}`); + expect(req2.request.method).toBe('GET'); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve search results!' }); + + query = 'name=test'; + const result: SearchResult = { + players: players, + strategies: [], + teams: [ + { teamName: 'test', teamId: '1', teamAvatar: 'testLogo', visible: true, description: 'testDescription'} + ], + steamUser: null + }; + service.quickSearch('test'); + const req3 = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=test`); + expect(req3.request.method).toBe('GET'); + req3.flush(result); + service.searchPlayers(query); + expect(service.playerSearchResult.value).toEqual(result.players); }); - describe('searchStrategies', () => { - it('should make a GET request to the API endpoint with the provided query', () => { - const query = 'testQuery'; - service.strategySearchResult.subscribe(); - service.searchStrategies(query); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/search/strategies?${query}`); - expect(req.request.method).toBe('GET'); - }); + it('searchStrategies should make a GET request to the API endpoint with the provided query', () => { + let query = 'testQuery'; + service.searchStrategies(query); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/search/strategies?${query}`); + expect(req.request.method).toBe('GET'); + expect(service.loadingSearch.value).toBeTruthy(); + req.flush([]); + expect(service.loadingSearch.value).toBeFalsy(); + expect(service.strategySearchResult.value).toEqual([]); + expect(service['_strategySearchCache'].get(query)).toEqual([]); + + query = 'testQuery2'; + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/search/strategies?${query}: 500 Could not retrieve search results!`; + commService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.searchStrategies(query); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/search/strategies?${query}`); + expect(req2.request.method).toBe('GET'); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve search results!' }); + + // Should return strategies from the quick search result cache if the query starts with 'name' + query = 'name=test'; + const result: SearchResult = { + players: [], + strategies: [ + { + id: '123456', + title: 'Test 1', + description: 'Test 2', + map: CSGOMap.Dust2, + side: Side.TSide, + teamId: '123', + url: 'test.com' + } + ], + teams: [], + steamUser: null + }; + service.quickSearch('test'); + const req3 = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=test`); + expect(req3.request.method).toBe('GET'); + req3.flush(result); + service.searchStrategies(query); + expect(service.strategySearchResult.value).toEqual(result.strategies); }); }); diff --git a/projects/common/src/services/bellumgens-api.search.service.ts b/projects/common/src/services/bellumgens-api.search.service.ts index 1a9927858..0a28545b5 100644 --- a/projects/common/src/services/bellumgens-api.search.service.ts +++ b/projects/common/src/services/bellumgens-api.search.service.ts @@ -58,13 +58,14 @@ export class ApiSearchService { } else { this.teamSearchResult.next([]); this.loadingSearch.next(true); - this.getFilteredTeams(query).subscribe( - teams => { + this.getFilteredTeams(query).subscribe({ + next: teams => { this._teamSearchCache.set(query, teams); this.teamSearchResult.next(teams); this.loadingSearch.next(false); - } - ); + }, + error: () => this.loadingSearch.next(false) + }); } } } @@ -81,13 +82,14 @@ export class ApiSearchService { } else { this.playerSearchResult.next([]); this.loadingSearch.next(true); - this.getFilteredPlayers(query).subscribe( - players => { + this.getFilteredPlayers(query).subscribe({ + next: players => { this._playerSearchCache.set(query, players); this.playerSearchResult.next(players); this.loadingSearch.next(false); - } - ); + }, + error: () => this.loadingSearch.next(false) + }); } } } @@ -104,13 +106,14 @@ export class ApiSearchService { } else { this.strategySearchResult.next([]); this.loadingSearch.next(true); - this.getFilteredStrategies(query).subscribe( - strategies => { + this.getFilteredStrategies(query).subscribe({ + next: strategies => { this._strategySearchCache.set(query, strategies); this.strategySearchResult.next(strategies); this.loadingSearch.next(false); - } - ); + }, + error: () => this.loadingSearch.next(false) + }); } } } diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 53cdf98f6..47d76328b 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -546,121 +546,67 @@ describe('BellumgensApiService', () => { req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update availability!' }); }); - it('setPrimaryRole should send a PUT request to the correct URL', () => { - const role: Role = { id: PlaystyleRole.Awper, name: 'Awper' }; - commsService.success.subscribe(success => expect(success).toBe(`Primary role set to ${role.name}`)); - service.setPrimaryRole(role).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(role); - expect(req.request.withCredentials).toBe(true); - req.flush({}); - - const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/primaryrole?id=${role.id}: 500 Could not update primary role!`; - commsService.error.subscribe(error => expect(error).toBe(errorMessage)); - service.setPrimaryRole(role).subscribe({ - error: err => expect(err.message).toBe(errorMessage) + describe('setPrimaryRole', () => { + it('should send a PUT request to the correct URL', () => { + const role: Role = { id: PlaystyleRole.Awper, name: 'Awper' }; + service.setPrimaryRole(role).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(role); + expect(req.request.withCredentials).toBe(true); }); - const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); - expect(req2.request.method).toBe('PUT'); - expect(req2.request.body).toEqual(role); - expect(req2.request.withCredentials).toBe(true); - req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update primary role!' }); }); - it('setSecondaryRole should send a PUT request to the correct URL', () => { - const role: Role = { id: PlaystyleRole.IGL, name: 'Ingame Leader' }; - commsService.success.subscribe(success => expect(success).toBe(`Secondary role set to ${role.name}`)); - service.setSecondaryRole(role).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(role); - expect(req.request.withCredentials).toBe(true); - req.flush({}); - - const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}: 500 Could not update secondary role!`; - commsService.error.subscribe(error => expect(error).toBe(errorMessage)); - service.setSecondaryRole(role).subscribe({ - error: err => expect(err.message).toBe(errorMessage) + describe('setSecondaryRole', () => { + it('should send a PUT request to the correct URL', () => { + const role: Role = { id: PlaystyleRole.IGL, name: 'Ingame Leader' }; + service.setSecondaryRole(role).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(role); + expect(req.request.withCredentials).toBe(true); }); - const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); - expect(req2.request.method).toBe('PUT'); - expect(req2.request.body).toEqual(role); - expect(req2.request.withCredentials).toBe(true); - req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update secondary role!' }); }); - it('getMapPool should send a GET request to the correct URL', () => { - const userId = '234'; - service.getMapPool(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool?userid=${userId}`); - expect(req.request.method).toBe('GET'); - req.flush({}); + describe('getMapPool', () => { + it('should send a GET request to the correct URL', () => { + const userId = '234'; + service.getMapPool(userId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool?userid=${userId}`); + expect(req.request.method).toBe('GET'); + }); }); - it('setMapPool should send a PUT request to the correct URL', () => { - const mapstatus: CSGOMapPool = { mapId: CSGOMap.Dust2, isPlayed: true }; - commsService.success.subscribe(success => expect(success).toBe('Map pool updated!')); - service.setMapPool(mapstatus).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(mapstatus); - expect(req.request.withCredentials).toBe(true); - req.flush({}); - - const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/mapPool: 500 Could not update map pool!`; - commsService.error.subscribe(error => expect(error).toBe(errorMessage)); - service.setMapPool(mapstatus).subscribe({ - error: err => expect(err.message).toBe(errorMessage) + describe('setMapPool', () => { + it('should send a PUT request to the correct URL', () => { + const mapstatus: CSGOMapPool = { mapId: CSGOMap.Dust2, isPlayed: true }; + service.setMapPool(mapstatus).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(mapstatus); + expect(req.request.withCredentials).toBe(true); }); - const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); - expect(req2.request.method).toBe('PUT'); - expect(req2.request.body).toEqual(mapstatus); - expect(req2.request.withCredentials).toBe(true); - req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update map pool!' }); }); - it('acceptInvite should send a PUT request to the correct URL', () => { - const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; - commsService.success.subscribe(success => expect(success).toBe('Team invite accepted!')); - service.acceptInvite(notification).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(notification); - expect(req.request.withCredentials).toBe(true); - req.flush({}); - - const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/acceptTeamInvite: 500 Could not accept team invite!`; - commsService.error.subscribe(error => expect(error).toBe(errorMessage)); - service.acceptInvite(notification).subscribe({ - error: err => expect(err.message).toBe(errorMessage) + describe('acceptInvite', () => { + it('should send a PUT request to the correct URL', () => { + const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; + service.acceptInvite(notification).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(notification); + expect(req.request.withCredentials).toBe(true); }); - const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); - expect(req2.request.method).toBe('PUT'); - expect(req2.request.body).toEqual(notification); - expect(req2.request.withCredentials).toBe(true); - req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not accept team invite!' }); }); - it('rejectInvite should send a PUT request to the correct URL', () => { - const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; - commsService.success.subscribe(success => expect(success).toBe('Team invite rejected!')); - service.rejectInvite(notification).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(notification); - expect(req.request.withCredentials).toBe(true); - req.flush({}); - - const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/rejectTeamInvite: 500 Could not reject team invite!`; - commsService.error.subscribe(error => expect(error).toBe(errorMessage)); - service.rejectInvite(notification).subscribe({ - error: err => expect(err.message).toBe(errorMessage) + describe('rejectInvite', () => { + it('should send a PUT request to the correct URL', () => { + const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; + service.rejectInvite(notification).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(notification); + expect(req.request.withCredentials).toBe(true); }); - const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); - expect(req2.request.method).toBe('PUT'); - expect(req2.request.body).toEqual(notification); - expect(req2.request.withCredentials).toBe(true); - req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not reject team invite!' }); }); }); From 336d5f11986ebc0773769c153c40bfd0bead3162 Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Mon, 4 Dec 2023 10:41:05 +0200 Subject: [PATCH 07/10] test(*): increasing coverage of common --- .../login-buttons.component.spec.ts | 3 +- .../login-dialog.component.spec.ts | 109 ++++++++++++++---- .../login-dialog/login-dialog.component.ts | 8 +- .../services/bellumgens-api.service.spec.ts | 54 ++++++--- 4 files changed, 130 insertions(+), 44 deletions(-) diff --git a/projects/common/src/lib/login/login-buttons/login-buttons.component.spec.ts b/projects/common/src/lib/login/login-buttons/login-buttons.component.spec.ts index 4e058b95f..b9d08ef6e 100644 --- a/projects/common/src/lib/login/login-buttons/login-buttons.component.spec.ts +++ b/projects/common/src/lib/login/login-buttons/login-buttons.component.spec.ts @@ -3,9 +3,8 @@ import { LoginButtonsComponent } from './login-buttons.component'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ServiceWorkerModule } from '@angular/service-worker'; import { RouterTestingModule } from '@angular/router/testing'; -import { LoginProvider } from '../../../models/login-provider'; import { LOGIN_ASSETS } from '../../../models/misc'; -import { LoginService } from '../../../services/login.service'; +import { LoginProvider, LoginService } from '../../../public_api'; describe('LoginButtonsComponent', () => { let component: LoginButtonsComponent; diff --git a/projects/common/src/lib/login/login-dialog/login-dialog.component.spec.ts b/projects/common/src/lib/login/login-dialog/login-dialog.component.spec.ts index 7065ab593..45e9e8f00 100644 --- a/projects/common/src/lib/login/login-dialog/login-dialog.component.spec.ts +++ b/projects/common/src/lib/login/login-dialog/login-dialog.component.spec.ts @@ -1,43 +1,56 @@ import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; - -import { LoginDialogComponent } from './login-dialog.component'; -import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { ServiceWorkerModule } from '@angular/service-worker'; -import { - IgxDialogModule, - IgxButtonModule, - IgxIconModule, - IgxDividerModule, - IgxCheckboxModule, - IgxInputGroupModule -} from '@infragistics/igniteui-angular'; +import { FormsModule } from '@angular/forms'; +import { Router } from '@angular/router'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; -import { FormsModule } from '@angular/forms'; -import { LoginButtonsComponent } from '../login-buttons/login-buttons.component'; +import { ServiceWorkerModule } from '@angular/service-worker'; + +import { ApplicationUser, CommunicationService, LoginService } from '../../../public_api'; + +import { LoginDialogComponent } from './login-dialog.component'; describe('LoginDialogComponent', () => { let component: LoginDialogComponent; let fixture: ComponentFixture; + let httpMock: HttpTestingController; + let loginService: LoginService; + let commsService: CommunicationService; + let router: Router; + const applicationUser: ApplicationUser = { + id: '1', + steamId: 'test-steam-id', + battleNetId: 'test-battlenet-id', + username: 'test-user', + email: 'test-email', + avatarFull: 'test-avatar', + avatarMedium: 'test-avatar', + avatarIcon: 'test-avatar', + customURL: 'test-url', + realname: 'test-realname', + searchVisible: false, + externalLogins: [ + 'Steam' + ] + }; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ - imports: [ + imports: [ FormsModule, HttpClientTestingModule, RouterTestingModule, NoopAnimationsModule, ServiceWorkerModule.register('', { enabled: false }), - IgxDialogModule, - IgxButtonModule, - IgxIconModule, - IgxDividerModule, - IgxCheckboxModule, - IgxInputGroupModule, - LoginDialogComponent, LoginButtonsComponent - ] -}) + LoginDialogComponent + ] + }) .compileComponents(); + + loginService = TestBed.inject(LoginService); + httpMock = TestBed.inject(HttpTestingController); + commsService = TestBed.inject(CommunicationService); + router = TestBed.get(Router); })); beforeEach(() => { @@ -49,4 +62,52 @@ describe('LoginDialogComponent', () => { it('should create', () => { expect(component).toBeTruthy(); }); + + it('should initialize logininfo with empty values', () => { + expect(component.logininfo).toEqual({ + username: '', + password: '', + rememberMe: false + }) + }); + + it('should open the login dialog', () => { + spyOn(component.dialog, 'open'); + component.openLogin(); + expect(component.dialog.open).toHaveBeenCalled(); + }); + + it('should open the registration dialog', () => { + spyOn(component.dialog, 'close'); + spyOn(router, 'navigate'); + component.openRegistration(); + expect(component.dialog.close).toHaveBeenCalled(); + expect(router.navigate).toHaveBeenCalledWith(['register']); + }); + + it('should perform login with form data', () => { + spyOn(component.dialog, 'close'); + // Set form data + component.logininfo.username = 'testuser'; + component.logininfo.password = 'testpassword'; + + commsService.success.subscribe(message => expect(message).toEqual('Logged in successfully!')); + // Call the loginWithForm method + component.loginWithForm(); + const req = httpMock.expectOne(`${loginService['_apiEndpoint']}/login`); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual(component.logininfo); + expect(req.request.withCredentials).toBe(true); + expect(component.submitInProgress).toBe(true); + req.flush(applicationUser); + expect(component.submitInProgress).toBe(false); + expect(component.dialog.close).toHaveBeenCalled(); + expect(loginService['_applicationUser'].value).toEqual(applicationUser); + + const req2 = httpMock.expectOne(`${loginService['_apiBase']}/tournament/registrations`); + expect(req2.request.method).toBe('GET'); + expect(req2.request.withCredentials).toBe(true); + req2.flush([]); + expect(loginService['_registrations'].value).toEqual([]); + }); }); diff --git a/projects/common/src/lib/login/login-dialog/login-dialog.component.ts b/projects/common/src/lib/login/login-dialog/login-dialog.component.ts index 363a146cf..c6f70f986 100644 --- a/projects/common/src/lib/login/login-dialog/login-dialog.component.ts +++ b/projects/common/src/lib/login/login-dialog/login-dialog.component.ts @@ -32,11 +32,15 @@ export class LoginDialogComponent { } public openRegistration() { - this.router.navigate(['register']); this.dialog.close(); + this.router.navigate(['register']); } public loginWithForm() { - this.authManager.loginWithForm(this.logininfo).subscribe(() => this.dialog.close()); + this.submitInProgress = true; + this.authManager.loginWithForm(this.logininfo).subscribe(() => { + this.dialog.close(); + this.submitInProgress = false; + }); } } diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 47d76328b..fe4ee9556 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -546,26 +546,48 @@ describe('BellumgensApiService', () => { req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update availability!' }); }); - describe('setPrimaryRole', () => { - it('should send a PUT request to the correct URL', () => { - const role: Role = { id: PlaystyleRole.Awper, name: 'Awper' }; - service.setPrimaryRole(role).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(role); - expect(req.request.withCredentials).toBe(true); + it('setPrimaryRole should send a PUT request to the correct URL', () => { + const role: Role = { id: PlaystyleRole.Awper, name: 'Awper' }; + commsService.success.subscribe(success => expect(success).toBe(`Primary role set to ${role.name}`)); + service.setPrimaryRole(role).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(role); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/primaryrole?id=${role.id}: 500 Could not update primary role!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setPrimaryRole(role).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/primaryrole?id=${role.id}`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(role); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update primary role!' }); }); - describe('setSecondaryRole', () => { - it('should send a PUT request to the correct URL', () => { - const role: Role = { id: PlaystyleRole.IGL, name: 'Ingame Leader' }; - service.setSecondaryRole(role).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(role); - expect(req.request.withCredentials).toBe(true); + it('setSecondaryRole should send a PUT request to the correct URL', () => { + const role: Role = { id: PlaystyleRole.IGL, name: 'Ingame Leader' }; + commsService.success.subscribe(success => expect(success).toBe(`Secondary role set to ${role.name}`)); + service.setSecondaryRole(role).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(role); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}: 500 Could not update secondary role!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setSecondaryRole(role).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/secondaryrole?id=${role.id}`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(role); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update secondary role!' }); }); describe('getMapPool', () => { From b841351db373bc69b4256b1f8600e69026dc722c Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Mon, 4 Dec 2023 15:08:50 +0200 Subject: [PATCH 08/10] test(api service): finishing api service spec --- .../services/bellumgens-api.service.spec.ts | 94 +++++++++++++------ 1 file changed, 63 insertions(+), 31 deletions(-) diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index fe4ee9556..53cdf98f6 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -590,45 +590,77 @@ describe('BellumgensApiService', () => { req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update secondary role!' }); }); - describe('getMapPool', () => { - it('should send a GET request to the correct URL', () => { - const userId = '234'; - service.getMapPool(userId).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool?userid=${userId}`); - expect(req.request.method).toBe('GET'); - }); + it('getMapPool should send a GET request to the correct URL', () => { + const userId = '234'; + service.getMapPool(userId).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool?userid=${userId}`); + expect(req.request.method).toBe('GET'); + req.flush({}); }); - describe('setMapPool', () => { - it('should send a PUT request to the correct URL', () => { - const mapstatus: CSGOMapPool = { mapId: CSGOMap.Dust2, isPlayed: true }; - service.setMapPool(mapstatus).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(mapstatus); - expect(req.request.withCredentials).toBe(true); + it('setMapPool should send a PUT request to the correct URL', () => { + const mapstatus: CSGOMapPool = { mapId: CSGOMap.Dust2, isPlayed: true }; + commsService.success.subscribe(success => expect(success).toBe('Map pool updated!')); + service.setMapPool(mapstatus).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(mapstatus); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/mapPool: 500 Could not update map pool!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.setMapPool(mapstatus).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/mapPool`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(mapstatus); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not update map pool!' }); }); - describe('acceptInvite', () => { - it('should send a PUT request to the correct URL', () => { - const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; - service.acceptInvite(notification).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(notification); - expect(req.request.withCredentials).toBe(true); + it('acceptInvite should send a PUT request to the correct URL', () => { + const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; + commsService.success.subscribe(success => expect(success).toBe('Team invite accepted!')); + service.acceptInvite(notification).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(notification); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/acceptTeamInvite: 500 Could not accept team invite!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.acceptInvite(notification).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/acceptTeamInvite`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(notification); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not accept team invite!' }); }); - describe('rejectInvite', () => { - it('should send a PUT request to the correct URL', () => { - const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; - service.rejectInvite(notification).subscribe(); - const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); - expect(req.request.method).toBe('PUT'); - expect(req.request.body).toEqual(notification); - expect(req.request.withCredentials).toBe(true); + it('rejectInvite should send a PUT request to the correct URL', () => { + const notification: UserNotification = { state: NotificationState.NotSeen, teamInfo: null, invitingUser: null, sent: '' }; + commsService.success.subscribe(success => expect(success).toBe('Team invite rejected!')); + service.rejectInvite(notification).subscribe(); + const req = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); + expect(req.request.method).toBe('PUT'); + expect(req.request.body).toEqual(notification); + expect(req.request.withCredentials).toBe(true); + req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/users/rejectTeamInvite: 500 Could not reject team invite!`; + commsService.error.subscribe(error => expect(error).toBe(errorMessage)); + service.rejectInvite(notification).subscribe({ + error: err => expect(err.message).toBe(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/users/rejectTeamInvite`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(notification); + expect(req2.request.withCredentials).toBe(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not reject team invite!' }); }); }); From b21b503805450030a4eb750bcb86efa2c61d380b Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Wed, 6 Dec 2023 11:59:48 +0200 Subject: [PATCH 09/10] test(*): bumping coverage more --- .../bellumgens-api.search.service.spec.ts | 27 +++- .../services/bellumgens-api.service.spec.ts | 3 +- .../bellumgens-api.shop.service.spec.ts | 36 ++++- .../bellumgens-api.strategies.service.spec.ts | 151 +++++++++++++++++- .../bellumgens-api.strategies.service.ts | 30 ++-- ...bellumgens-api.tournaments.service.spec.ts | 3 +- 6 files changed, 219 insertions(+), 31 deletions(-) diff --git a/projects/common/src/services/bellumgens-api.search.service.spec.ts b/projects/common/src/services/bellumgens-api.search.service.spec.ts index e582280eb..9a46adf77 100644 --- a/projects/common/src/services/bellumgens-api.search.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.search.service.spec.ts @@ -12,8 +12,7 @@ describe('ApiSearchService', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ HttpClientTestingModule ], - providers: [ ApiSearchService ] + imports: [ HttpClientTestingModule ] }); service = TestBed.inject(ApiSearchService); commService = TestBed.inject(CommunicationService); @@ -52,6 +51,12 @@ describe('ApiSearchService', () => { const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/search?name=${name}`); expect(req2.request.method).toBe('GET'); req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve search results!' }); + + // Should return the search result from the cache if the name is already cached + name = 'testName'; + service.quickSearch(name); + expect(service.loadingQuickSearch.value).toBeFalsy(); + expect(service.searchResult.value).toEqual(result); }); it('searchTeams should make a GET request to the API endpoint with the provided query', () => { @@ -94,6 +99,12 @@ describe('ApiSearchService', () => { req3.flush(result); service.searchTeams(query); expect(service.teamSearchResult.value).toEqual(result.teams); + + // Should return the team search result from the cache if the query is already cached + query = 'role=1&overlap=1'; + service.searchTeams(query); + expect(service.loadingSearch.value).toBeFalsy(); + expect(service.teamSearchResult.value).toEqual(teams); }); it('searchPlayers should make a GET request to the API endpoint with the provided query', () => { @@ -155,6 +166,12 @@ describe('ApiSearchService', () => { req3.flush(result); service.searchPlayers(query); expect(service.playerSearchResult.value).toEqual(result.players); + + // Should return the player search result from the cache if the query is already cached + query = 'role=1&overlap=1'; + service.searchPlayers(query); + expect(service.loadingSearch.value).toBeFalsy(); + expect(service.playerSearchResult.value).toEqual(players); }); it('searchStrategies should make a GET request to the API endpoint with the provided query', () => { @@ -200,5 +217,11 @@ describe('ApiSearchService', () => { req3.flush(result); service.searchStrategies(query); expect(service.strategySearchResult.value).toEqual(result.strategies); + + // Should return the strategy search result from the cache if the query is already cached + query = 'testQuery'; + service.searchStrategies(query); + expect(service.loadingSearch.value).toBeFalsy(); + expect(service.strategySearchResult.value).toEqual([]); }); }); diff --git a/projects/common/src/services/bellumgens-api.service.spec.ts b/projects/common/src/services/bellumgens-api.service.spec.ts index 53cdf98f6..2c011200f 100644 --- a/projects/common/src/services/bellumgens-api.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.service.spec.ts @@ -18,8 +18,7 @@ describe('BellumgensApiService', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ HttpClientTestingModule ], - providers: [ BellumgensApiService ] + imports: [ HttpClientTestingModule ] }); service = TestBed.inject(BellumgensApiService); httpMock = TestBed.inject(HttpTestingController); diff --git a/projects/common/src/services/bellumgens-api.shop.service.spec.ts b/projects/common/src/services/bellumgens-api.shop.service.spec.ts index c241c7281..0a14dd491 100644 --- a/projects/common/src/services/bellumgens-api.shop.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.shop.service.spec.ts @@ -1,21 +1,23 @@ import { TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ApiShopService } from './bellumgens-api.shop.service'; -import { JerseyCut, JerseyOrder, JerseySize } from '../models/jerseyorder'; +import { JerseyCut, JerseyOrder, JerseySize, Promo } from '../models/jerseyorder'; +import { CommunicationService } from './communication.service'; describe('ApiShopService', () => { let service: ApiShopService; let httpMock: HttpTestingController; + let commsService: CommunicationService; beforeEach(() => { TestBed.configureTestingModule({ - imports: [ HttpClientTestingModule ], - providers: [ ApiShopService ] + imports: [ HttpClientTestingModule ] }); service = TestBed.inject(ApiShopService); httpMock = TestBed.inject(HttpTestingController); + commsService = TestBed.inject(CommunicationService); }); afterEach(() => { @@ -40,21 +42,34 @@ describe('ApiShopService', () => { describe('deleteOrder', () => { it('should send a DELETE request to the API with the order ID', () => { const orderId = '123'; + commsService.success.subscribe(message => expect(message).toEqual('Order deleted successfully!')); service.deleteOrder(orderId).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/shop/order?orderId=${orderId}`); expect(req.request.method).toBe('DELETE'); expect(req.request.withCredentials).toEqual(true); req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/shop/order?orderId=${orderId}: 500 Could not delete order!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.deleteOrder(orderId).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/shop/order?orderId=${orderId}`); + expect(req2.request.method).toBe('DELETE'); + expect(req2.request.withCredentials).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not delete order!' }); }); }); describe('checkForPromo', () => { it('should send a GET request to the API with the promo code', () => { const code = 'SUMMER21'; + const promo: Promo = { code: code, discount: .1, expiration: new Date() }; service.checkForPromo(code).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/shop/promo?code=${code}`); expect(req.request.method).toBe('GET'); - req.flush({}); + req.flush(promo); }); }); @@ -71,12 +86,25 @@ describe('ApiShopService', () => { describe('confirmOrder', () => { it('should send a PUT request to the API with the order data', () => { const order: JerseyOrder = { id: '123', jerseys: [{ cut: JerseyCut.Male, size: JerseySize.L }] }; + commsService.success.subscribe(message => expect(message).toEqual('Order confirmed successfully!')); service.confirmOrder(order).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/shop/edit?orderId=${order.id}`); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual(order); expect(req.request.withCredentials).toEqual(true); req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/shop/edit?orderId=${order.id}: 500 Could not confirm order!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.confirmOrder(order).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/shop/edit?orderId=${order.id}`); + expect(req2.request.method).toBe('PUT'); + expect(req2.request.body).toEqual(order); + expect(req2.request.withCredentials).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not confirm order!' }); }); }); }); diff --git a/projects/common/src/services/bellumgens-api.strategies.service.spec.ts b/projects/common/src/services/bellumgens-api.strategies.service.spec.ts index a44082c26..a7dcee601 100644 --- a/projects/common/src/services/bellumgens-api.strategies.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.strategies.service.spec.ts @@ -1,17 +1,19 @@ import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; -import { CSGOStrategy, Side, StrategyComment, VoteDirection } from '../models/csgostrategy'; +import { CSGOStrategy, Side, StrategyComment, StrategyVote, VoteDirection } from '../models/csgostrategy'; import { ApiStrategiesService } from './bellumgens-api.strategies.service'; -import { CSGOMap } from '../public_api'; +import { CSGOMap, CommunicationService } from '../public_api'; describe('ApiStrategiesService', () => { let service: ApiStrategiesService; let httpMock: HttpTestingController; + let commsService: CommunicationService; beforeEach(() => { TestBed.configureTestingModule({imports: [ HttpClientTestingModule ]}); service = TestBed.inject(ApiStrategiesService); httpMock = TestBed.inject(HttpTestingController); + commsService = TestBed.inject(CommunicationService); }); afterEach(() => { @@ -24,10 +26,24 @@ describe('ApiStrategiesService', () => { it('should load strategies page on `strategies` getter', () => { const page = 0; - const sub = service.strategies.subscribe(); + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/strategies?page=${page}: 500 Could not retrieve strategies!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + let sub = service.strategies.subscribe({ + error: error => expect(error.message).toEqual(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategies?page=${page}`); + expect(req2.request.method).toEqual('GET'); + expect(service.loadingStrategies.value).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve strategies!' }); + expect(service.loadingStrategies.value).toEqual(false); + sub.unsubscribe(); + + sub = service.strategies.subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategies?page=${page}`); expect(req.request.method).toEqual('GET'); + expect(service.loadingStrategies.value).toEqual(true); req.flush([]); + expect(service.loadingStrategies.value).toEqual(false); expect(service['_strategies'].value).toEqual([]); sub.unsubscribe(); }); @@ -37,8 +53,19 @@ describe('ApiStrategiesService', () => { service.loadStrategiesPage(page); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategies?page=${page}`); expect(req.request.method).toEqual('GET'); + expect(service.loadingStrategies.value).toEqual(true); req.flush([]); + expect(service.loadingStrategies.value).toEqual(false); expect(service['_strategies'].value).toEqual([]); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/strategies?page=${page}: 500 Could not retrieve strategies!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.loadStrategiesPage(page); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategies?page=${page}`); + expect(req2.request.method).toEqual('GET'); + expect(service.loadingStrategies.value).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not retrieve strategies!' }); + expect(service.loadingStrategies.value).toEqual(false); }); it('should get user strategies', () => { @@ -116,21 +143,56 @@ describe('ApiStrategiesService', () => { teamId: '123', url: 'test.com' }; + commsService.success.subscribe(message => expect(message).toEqual('Strategy saved!')); service.submitStrategy(strat).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategy`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual(strat); expect(req.request.withCredentials).toEqual(true); req.flush(strat); - expect(service['_strategyCache'].get(strat.id).value).toEqual({ + expect(service['_strategyCache'].get(strat.id).value).toEqual(strat); + + const strat2: CSGOStrategy = { id: '123456', title: 'Test 1', description: 'Test 2', map: CSGOMap.Dust2, side: Side.TSide, teamId: '123', - url: 'test.com' + url: 'test.com', + comments: [] + }; + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/strategy: 500 Could not save strategy!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.submitStrategy(strat2).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategy`); + expect(req2.request.method).toEqual('POST'); + expect(req2.request.body).toEqual(strat2); + expect(req2.request.withCredentials).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not save strategy!' }); + + // Should update the strategy cache if the strategy is already cached + const strat3: CSGOStrategy = { + id: '123456', + title: 'Test 1', + description: 'Test 2', + map: CSGOMap.Dust2, + side: Side.TSide, + teamId: '123', + url: 'test.com', + comments: [] + }; + commsService.success.subscribe(message => expect(message).toEqual('Strategy saved!')); + service.submitStrategy(strat3).subscribe(); + const req3 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strategy`); + expect(req3.request.method).toEqual('POST'); + expect(req3.request.body).toEqual(strat3); + expect(req3.request.withCredentials).toEqual(true); + req3.flush(strat3); + expect(service['_strategyCache'].get(strat3.id).value).toEqual(strat3); }); it('should submit strat vote', () => { @@ -146,12 +208,37 @@ describe('ApiStrategiesService', () => { }; const direction = VoteDirection.Up; const userId = '123'; + const vote: StrategyVote = { userId: userId, vote: direction }; + commsService.success.subscribe(message => expect(message).toEqual('Vote submitted successfully!')); service.submitStratVote(strat, direction, userId).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/vote`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual({ id: strat.id, direction }); expect(req.request.withCredentials).toEqual(true); - req.flush({}); + req.flush(vote); + + // Should update the vote if the user already voted + const vote2: StrategyVote = { userId: userId, vote: VoteDirection.Down }; + commsService.success.subscribe(message => expect(message).toEqual('Vote submitted successfully!')); + service.submitStratVote(strat, direction, userId).subscribe(); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/vote`); + expect(req2.request.method).toEqual('POST'); + expect(req2.request.body).toEqual({ id: strat.id, direction }); + expect(req2.request.withCredentials).toEqual(true); + req2.flush(vote2); + expect(strat.votes.find(v => v.userId === userId).vote).toEqual(vote2.vote); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/vote: 500 Could not submit vote!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.submitStratVote(strat, direction, userId).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) + }); + const req3 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/vote`); + expect(req3.request.method).toEqual('POST'); + expect(req3.request.body).toEqual({ id: strat.id, direction }); + expect(req3.request.withCredentials).toEqual(true); + req3.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not submit vote!' }); }); it('should submit strat comment', () => { @@ -166,12 +253,37 @@ describe('ApiStrategiesService', () => { url: 'test', comments: [] }; + const sub = commsService.success.subscribe(message => expect(message).toEqual('Comment submitted successfully!')); service.submitStratComment(comment, strat).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/comment`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual(comment); expect(req.request.withCredentials).toEqual(true); - req.flush({}); + req.flush(comment); + sub.unsubscribe(); + + // Should update the comment if the comment is already cached + const comment2: StrategyComment = { id: '123', stratId: '456', comment: 'Updated test comment', userId: '123', published: new Date() }; + commsService.success.subscribe(message => expect(message).toEqual('Comment edited successfully!')); + service.submitStratComment(comment2, strat).subscribe(); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/comment`); + expect(req2.request.method).toEqual('POST'); + expect(req2.request.body).toEqual(comment2); + expect(req2.request.withCredentials).toEqual(true); + req2.flush(comment2); + expect(strat.comments.find(c => c.id === comment2.id).comment).toEqual(comment2.comment); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/comment: 500 Could not submit comment!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.submitStratComment(comment, strat).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) + }); + const req3 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/comment`); + expect(req3.request.method).toEqual('POST'); + expect(req3.request.body).toEqual(comment); + expect(req3.request.withCredentials).toEqual(true); + req3.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not submit comment!' }); }); it('should delete strat comment', () => { @@ -188,20 +300,45 @@ describe('ApiStrategiesService', () => { { id: '123', stratId: '456', comment: 'Test', userId: '123', published: new Date() } ] }; + commsService.success.subscribe(message => expect(message).toEqual('Comment deleted successfully!')); service.deleteStratComment(comment, strat).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/comment?id=${comment.id}`); expect(req.request.method).toEqual('DELETE'); expect(req.request.withCredentials).toEqual(true); req.flush({}); + expect(strat.comments.length).toEqual(0); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/comment?id=${comment.id}: 500 Could not delete comment!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.deleteStratComment(comment, strat).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/comment?id=${comment.id}`); + expect(req2.request.method).toEqual('DELETE'); + expect(req2.request.withCredentials).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not delete comment!' }); }); it('should delete strategy', () => { const stratId = '345'; + commsService.success.subscribe(message => expect(message).toEqual('Strategy successfully deleted!')); service.deleteStrategy(stratId).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strat?id=${stratId}`); expect(req.request.method).toEqual('DELETE'); expect(req.request.withCredentials).toEqual(true); req.flush({}); + + const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/strat?id=${stratId}: 500 Could not delete strategy!`; + commsService.error.subscribe(message => expect(message).toEqual(errorMessage)); + service.deleteStrategy(stratId).subscribe({ + next: () => fail('Should not succeed'), + error: error => expect(error.message).toEqual(errorMessage) + }); + const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/strat?id=${stratId}`); + expect(req2.request.method).toEqual('DELETE'); + expect(req2.request.withCredentials).toEqual(true); + req2.error(new ProgressEvent('Server Error'), { status: 500, statusText: 'Could not delete strategy!' }); }); it('should handle errors', () => { diff --git a/projects/common/src/services/bellumgens-api.strategies.service.ts b/projects/common/src/services/bellumgens-api.strategies.service.ts index 90e91f23a..6be748011 100644 --- a/projects/common/src/services/bellumgens-api.strategies.service.ts +++ b/projects/common/src/services/bellumgens-api.strategies.service.ts @@ -7,7 +7,6 @@ import { environment } from '../environments/environment'; import { CSGOStrategy, StrategyComment, StrategyVote, VoteDirection } from '../models/csgostrategy'; import { CommunicationService } from './communication.service'; -const PAGE_SIZE = 25; @Injectable({ providedIn: 'root' }) @@ -18,31 +17,35 @@ export class ApiStrategiesService { private _apiEndpoint = environment.apiEndpoint; private _strategyCache = new Map>(); private _strategies = new BehaviorSubject([]); + private readonly PAGE_SIZE = 25; constructor(private http: HttpClient, private commService: CommunicationService) { } public get strategies() { if (!this._strategies.value.length) { this.loadingStrategies.next(true); - this.getStrategies().subscribe( - data => { + this.getStrategies().subscribe({ + next: data => { this._strategies.next(data); this.loadingStrategies.next(false); - this.hasMoreStrats.next(data.length === PAGE_SIZE); - } - ); + this.hasMoreStrats.next(data.length === this.PAGE_SIZE); + }, + error: () => this.loadingStrategies.next(false) + }); } return this._strategies; } public loadStrategiesPage(page: number) { - this.getStrategies(page).subscribe( - data => { - this._strategies.next(this._strategies.value.concat(data)); + this.loadingStrategies.next(true); + this.getStrategies(page).subscribe({ + next: data => { + this._strategies.next(data); this.loadingStrategies.next(false); - this.hasMoreStrats.next(data.length === PAGE_SIZE); - } - ); + this.hasMoreStrats.next(data.length === this.PAGE_SIZE); + }, + error: () => this.loadingStrategies.next(false) + }); } public getUserStrategies(userId: string) { @@ -141,7 +144,7 @@ export class ApiStrategiesService { return this.http.delete(`${this._apiEndpoint}/strategy/comment?id=${comment.id}`, { withCredentials: true }).pipe( map(response => { - this.commService.emitSuccess('Comment submitted successfully!'); + this.commService.emitSuccess('Comment deleted successfully!'); strat.comments.splice(strat.comments.indexOf(comment), 1); return response; }), @@ -173,7 +176,6 @@ export class ApiStrategiesService { }), catchError(error => { this.commService.emitError(error.message); - this.loadingStrategies.next(false); return throwError(() => error); }) ); diff --git a/projects/common/src/services/bellumgens-api.tournaments.service.spec.ts b/projects/common/src/services/bellumgens-api.tournaments.service.spec.ts index 4f53b486b..dd1bf51cf 100644 --- a/projects/common/src/services/bellumgens-api.tournaments.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.tournaments.service.spec.ts @@ -11,8 +11,7 @@ describe('ApiTournamentsService', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ HttpClientTestingModule ], - providers: [ ApiTournamentsService ] + imports: [ HttpClientTestingModule ] }); service = TestBed.inject(ApiTournamentsService); httpMock = TestBed.inject(HttpTestingController); From 243b093b8f481d421a64198db324db6eea32369a Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Thu, 7 Dec 2023 11:47:12 +0200 Subject: [PATCH 10/10] test(strategy service): extending voting test --- .../bellumgens-api.strategies.service.spec.ts | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/projects/common/src/services/bellumgens-api.strategies.service.spec.ts b/projects/common/src/services/bellumgens-api.strategies.service.spec.ts index a7dcee601..de39878dd 100644 --- a/projects/common/src/services/bellumgens-api.strategies.service.spec.ts +++ b/projects/common/src/services/bellumgens-api.strategies.service.spec.ts @@ -209,24 +209,37 @@ describe('ApiStrategiesService', () => { const direction = VoteDirection.Up; const userId = '123'; const vote: StrategyVote = { userId: userId, vote: direction }; - commsService.success.subscribe(message => expect(message).toEqual('Vote submitted successfully!')); + let sub = commsService.success.subscribe(message => expect(message).toEqual('Vote submitted successfully!')); service.submitStratVote(strat, direction, userId).subscribe(); const req = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/vote`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual({ id: strat.id, direction }); expect(req.request.withCredentials).toEqual(true); req.flush(vote); + sub.unsubscribe(); // Should update the vote if the user already voted const vote2: StrategyVote = { userId: userId, vote: VoteDirection.Down }; - commsService.success.subscribe(message => expect(message).toEqual('Vote submitted successfully!')); - service.submitStratVote(strat, direction, userId).subscribe(); + sub = commsService.success.subscribe(message => expect(message).toEqual('Vote submitted successfully!')); + service.submitStratVote(strat, VoteDirection.Down, userId).subscribe(); const req2 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/vote`); expect(req2.request.method).toEqual('POST'); - expect(req2.request.body).toEqual({ id: strat.id, direction }); + expect(req2.request.body).toEqual({ id: strat.id, direction: VoteDirection.Down }); expect(req2.request.withCredentials).toEqual(true); req2.flush(vote2); expect(strat.votes.find(v => v.userId === userId).vote).toEqual(vote2.vote); + sub.unsubscribe(); + + // Should remove the vote if the user already voted and the direction is the same + sub = commsService.success.subscribe(message => expect(message).toEqual('Vote removed successfully!')); + service.submitStratVote(strat, VoteDirection.Down, userId).subscribe(); + const req4 = httpMock.expectOne(`${service['_apiEndpoint']}/strategy/vote`); + expect(req4.request.method).toEqual('POST'); + expect(req4.request.body).toEqual({ id: strat.id, direction: VoteDirection.Down }); + expect(req4.request.withCredentials).toEqual(true); + req4.flush(null); + expect(strat.votes.find(v => v.userId === userId)).toBeUndefined(); + sub.unsubscribe(); const errorMessage = `Http failure response for ${service['_apiEndpoint']}/strategy/vote: 500 Could not submit vote!`; commsService.error.subscribe(message => expect(message).toEqual(errorMessage));