From b21b503805450030a4eb750bcb86efa2c61d380b Mon Sep 17 00:00:00 2001 From: Konstantin Dinev Date: Wed, 6 Dec 2023 11:59:48 +0200 Subject: [PATCH] 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 e582280e..9a46adf7 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 53cdf98f..2c011200 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 c241c728..0a14dd49 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 a44082c2..a7dcee60 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 90e91f23..6be74801 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 4f53b486..dd1bf51c 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);