From 3f7065448453ba4e1d7cfd588976fd013c281298 Mon Sep 17 00:00:00 2001 From: Suyash Patil <127177049+suyashpatil78@users.noreply.github.com> Date: Sat, 4 May 2024 10:30:53 +0530 Subject: [PATCH] test: fixing tests - part 3 (#2941) * test: fixing tests - part 3 * test: fixing tests - part 4 (#2943) * test: fixing tests - part 4 * test: fixing tests - part 5 (#2945) * minor --- .../core/mock-data/split-expense-form.data.ts | 194 ++++++++---------- .../services/advance-request.service.spec.ts | 63 +++--- src/app/core/services/advance.service.spec.ts | 4 +- .../services/custom-fields.service.spec.ts | 15 +- src/app/core/services/date.service.spec.ts | 8 +- .../services/expense-fields.service.spec.ts | 4 +- .../core/services/location.service.spec.ts | 5 +- .../services/merge-expenses.service.spec.ts | 5 +- .../services/org-settings.service.spec.ts | 12 +- ...recent-local-storage-items.service.spec.ts | 23 ++- src/app/core/services/status.service.spec.ts | 12 +- .../core/services/transaction.service.spec.ts | 24 ++- src/app/core/services/utility.service.spec.ts | 5 +- .../services/virtual-cards.service.spec.ts | 7 +- .../add-edit-mileage-1.spec.ts | 2 +- .../my-create-report.page.spec.ts | 5 +- .../employee-details-card.component.spec.ts | 4 +- .../fyle/my-reports/my-reports.page.spec.ts | 28 ++- .../my-view-report.page.spec.ts | 26 ++- .../notifications/notifications.page.spec.ts | 17 +- .../split-expense/split-expense.page.spec.ts | 32 +-- .../team-reports/team-reports-1.page.spec.ts | 3 +- .../view-team-report.page.spec.ts | 89 ++++---- .../setup-account/setup-account.page.spec.ts | 51 ++--- .../view-comment.component.spec.ts | 7 +- .../view-comment/view-comment.component.ts | 6 +- .../route-selector.component.spec.ts | 9 +- .../sidemenu-content.component.spec.ts | 17 +- .../virtual-select-modal.component.spec.ts | 2 +- 29 files changed, 369 insertions(+), 310 deletions(-) diff --git a/src/app/core/mock-data/split-expense-form.data.ts b/src/app/core/mock-data/split-expense-form.data.ts index e5a827e5d3..277360b704 100644 --- a/src/app/core/mock-data/split-expense-form.data.ts +++ b/src/app/core/mock-data/split-expense-form.data.ts @@ -1,113 +1,97 @@ -import deepFreeze from 'deep-freeze-strict'; - import { FormControl, FormGroup } from '@angular/forms'; -export const splitExpenseFormData1 = deepFreeze( - new FormGroup({ - amount: new FormControl(120), - currency: new FormControl('INR'), - percentage: new FormControl(60), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl(''), - }) -); +export const splitExpenseFormData1 = new FormGroup({ + amount: new FormControl(120), + currency: new FormControl('INR'), + percentage: new FormControl(60), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl(''), +}); -export const splitExpenseFormData2 = deepFreeze( - new FormGroup({ - amount: new FormControl(), - currency: new FormControl('INR'), - percentage: new FormControl(60), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl(''), - }) -); +export const splitExpenseFormData2 = new FormGroup({ + amount: new FormControl(), + currency: new FormControl('INR'), + percentage: new FormControl(60), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl(''), +}); -export const splitExpenseFormData3 = deepFreeze( - new FormGroup({ - amount: new FormControl(120), - currency: new FormControl('INR'), - percentage: new FormControl(), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl(''), - }) -); +export const splitExpenseFormData3 = new FormGroup({ + amount: new FormControl(120), + currency: new FormControl('INR'), + percentage: new FormControl(), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl(''), +}); -export const splitExpenseFormData4 = deepFreeze( - new FormGroup({ - amount: new FormControl(800), - currency: new FormControl('INR'), - percentage: new FormControl(40), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl(''), - }) -); +export const splitExpenseFormData4 = new FormGroup({ + amount: new FormControl(800), + currency: new FormControl('INR'), + percentage: new FormControl(40), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl(''), +}); -export const splitExpenseFormData5 = deepFreeze( - new FormGroup({ - amount: new FormControl(800), - currency: new FormControl('INR'), - percentage: new FormControl(90), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl(''), - }) -); +export const splitExpenseFormData5 = new FormGroup({ + amount: new FormControl(800), + currency: new FormControl('INR'), + percentage: new FormControl(90), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl(''), +}); -export const splitExpenseFormData6 = deepFreeze( - new FormGroup({ - amount: new FormControl(80), - currency: new FormControl('INR'), - percentage: new FormControl(96), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl(''), - }) -); +export const splitExpenseFormData6 = new FormGroup({ + amount: new FormControl(80), + currency: new FormControl('INR'), + percentage: new FormControl(96), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl(''), +}); -export const splitExpenseFormData7 = deepFreeze( - new FormGroup({ - amount: new FormControl(80), - currency: new FormControl('INR'), - percentage: new FormControl(96), - txn_dt: new FormControl('2023-01-11'), - category: new FormControl({ - code: null, - created_at: '2023-05-08T10:32:49.142566+00:00', - displayName: 'Food', - enabled: true, - fyle_category: 'Food', - id: 256621, - name: 'Food', - org_id: 'orNbIQloYtfa', - sub_category: 'Food', - updated_at: '2024-01-18T08:11:42.313617+00:00', - }), - project: new FormControl({ - ap1_email: null, - ap1_full_name: null, - ap2_email: null, - ap2_full_name: null, - project_active: true, - project_approver1_id: null, - project_approver2_id: null, - project_code: null, - project_created_at: '2023-12-18T02:01:14.842Z', - project_description: null, - project_id: 325126, - project_name: 'Project 1', - project_org_category_ids: [256621, 256627, 256633], - project_org_id: 'orNbIQloYtfa', - project_updated_at: '2024-01-13T04:18:53.330Z', - projectv2_name: 'Project 1', - sub_project_name: null, - }), - cost_center: new FormControl({ - active: true, - code: null, - created_at: '2023-12-13T09:20:18.568121+00:00', - description: null, - id: 20424, - name: 'Cost Center 1', - org_id: 'orNbIQloYtfa', - updated_at: '2024-01-10T16:48:41.754415+00:00', - }), - }) -); +export const splitExpenseFormData7 = new FormGroup({ + amount: new FormControl(80), + currency: new FormControl('INR'), + percentage: new FormControl(96), + txn_dt: new FormControl('2023-01-11'), + category: new FormControl({ + code: null, + created_at: '2023-05-08T10:32:49.142566+00:00', + displayName: 'Food', + enabled: true, + fyle_category: 'Food', + id: 256621, + name: 'Food', + org_id: 'orNbIQloYtfa', + sub_category: 'Food', + updated_at: '2024-01-18T08:11:42.313617+00:00', + }), + project: new FormControl({ + ap1_email: null, + ap1_full_name: null, + ap2_email: null, + ap2_full_name: null, + project_active: true, + project_approver1_id: null, + project_approver2_id: null, + project_code: null, + project_created_at: '2023-12-18T02:01:14.842Z', + project_description: null, + project_id: 325126, + project_name: 'Project 1', + project_org_category_ids: [256621, 256627, 256633], + project_org_id: 'orNbIQloYtfa', + project_updated_at: '2024-01-13T04:18:53.330Z', + projectv2_name: 'Project 1', + sub_project_name: null, + }), + cost_center: new FormControl({ + active: true, + code: null, + created_at: '2023-12-13T09:20:18.568121+00:00', + description: null, + id: 20424, + name: 'Cost Center 1', + org_id: 'orNbIQloYtfa', + updated_at: '2024-01-10T16:48:41.754415+00:00', + }), +}); diff --git a/src/app/core/services/advance-request.service.spec.ts b/src/app/core/services/advance-request.service.spec.ts index 502907c65c..1a81496382 100644 --- a/src/app/core/services/advance-request.service.spec.ts +++ b/src/app/core/services/advance-request.service.spec.ts @@ -461,16 +461,16 @@ describe('AdvanceRequestService', () => { describe('fixDates():', () => { it('should convert string values to dates', () => { + const mockAdvanceReqData = cloneDeep(extendedAdvReqWithoutDates); //@ts-ignore - expect(advanceRequestService.fixDates(extendedAdvReqWithoutDates)).toEqual(extendedAdvReqWithDates); + expect(advanceRequestService.fixDates(mockAdvanceReqData)).toEqual(extendedAdvReqWithDates); }); }); it('fixDatesForPlatformFields(): should convert string values to dates', () => { + const mockAdvanceReqData = cloneDeep(advanceRequestPlatform.data[0]); //@ts-ignore - expect(advanceRequestService.fixDatesForPlatformFields(advanceRequestPlatform.data[0])).toEqual( - advanceRequestPlatform.data[0] - ); + expect(advanceRequestService.fixDatesForPlatformFields(mockAdvanceReqData)).toEqual(advanceRequestPlatform.data[0]); }); it('getEReq(): should get advance request', (done) => { @@ -532,10 +532,11 @@ describe('AdvanceRequestService', () => { fileService.post.and.returnValue(of(fileObjectData3)); spyOn(advanceRequestService, 'submit').and.returnValue(of(advanceRequests)); - advanceRequestService.createAdvReqWithFilesAndSubmit(advanceRequests, of(fileData1)).subscribe((res) => { + const mockFileObject = cloneDeep(fileData1); + advanceRequestService.createAdvReqWithFilesAndSubmit(advanceRequests, of(mockFileObject)).subscribe((res) => { expect(res).toEqual(advRequestFile); expect(advanceRequestService.submit).toHaveBeenCalledOnceWith(advanceRequests); - expect(fileService.post).toHaveBeenCalledOnceWith(fileData1[0]); + expect(fileService.post).toHaveBeenCalledOnceWith(mockFileObject[0]); done(); }); }); @@ -556,10 +557,11 @@ describe('AdvanceRequestService', () => { fileService.post.and.returnValue(of(fileObjectData4)); spyOn(advanceRequestService, 'saveDraft').and.returnValue(of(advancedRequests2)); - advanceRequestService.saveDraftAdvReqWithFiles(advancedRequests2, of(fileData2)).subscribe((res) => { + const mockFileObject = cloneDeep(fileData2); + advanceRequestService.saveDraftAdvReqWithFiles(advancedRequests2, of(mockFileObject)).subscribe((res) => { expect(res).toEqual(advRequestFile2); expect(advanceRequestService.saveDraft).toHaveBeenCalledOnceWith(advancedRequests2); - expect(fileService.post).toHaveBeenCalledOnceWith(fileData2[0]); + expect(fileService.post).toHaveBeenCalledOnceWith(mockFileObject[0]); done(); }); }); @@ -592,11 +594,15 @@ describe('AdvanceRequestService', () => { describe('modifyAdvanceRequestCustomFields():', () => { it('should modify advance request custom fields', () => { - expect(advanceRequestService.modifyAdvanceRequestCustomFields(customFields)).toEqual(expectedCustomFieldsWoDate); + const mockCustomFields = cloneDeep(customFields); + expect(advanceRequestService.modifyAdvanceRequestCustomFields(mockCustomFields)).toEqual( + expectedCustomFieldsWoDate + ); }); it('should modify custom fields with date value', () => { - expect(advanceRequestService.modifyAdvanceRequestCustomFields(customField2)).toEqual( + const mockCustomFields = cloneDeep(customField2); + expect(advanceRequestService.modifyAdvanceRequestCustomFields(mockCustomFields)).toEqual( expectedCustomFieldsWithDate ); }); @@ -728,6 +734,7 @@ describe('AdvanceRequestService', () => { done(); }); }); + it('should get all advance request with default params', (done) => { spenderService.get.and.returnValue(of(advanceRequestPlatform)); @@ -747,8 +754,9 @@ describe('AdvanceRequestService', () => { describe('getMyadvanceRequests():', () => { it('should get all advance request', (done) => { - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - apiv2Service.get.and.returnValue(of(allAdvanceRequestsRes)); + authService.getEou.and.resolveTo(apiEouRes); + const mockApiV2Res = cloneDeep(allAdvanceRequestsRes); + apiv2Service.get.and.returnValue(of(mockApiV2Res)); const param = { offset: 0, @@ -760,7 +768,7 @@ describe('AdvanceRequestService', () => { }; advanceRequestService.getMyadvanceRequests(param).subscribe((res) => { - expect(res).toEqual(allAdvanceRequestsRes); + expect(res).toEqual(mockApiV2Res); expect(apiv2Service.get).toHaveBeenCalledOnceWith('/advance_requests', { params: { offset: param.offset, @@ -773,12 +781,14 @@ describe('AdvanceRequestService', () => { done(); }); }); + it('should get all advance request with default params', (done) => { - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - apiv2Service.get.and.returnValue(of(allAdvanceRequestsRes)); + authService.getEou.and.resolveTo(apiEouRes); + const mockApiV2Res = cloneDeep(allAdvanceRequestsRes); + apiv2Service.get.and.returnValue(of(mockApiV2Res)); advanceRequestService.getMyadvanceRequests().subscribe((res) => { - expect(res).toEqual(allAdvanceRequestsRes); + expect(res).toEqual(mockApiV2Res); expect(apiv2Service.get).toHaveBeenCalledOnceWith('/advance_requests', { params: { offset: 0, @@ -827,8 +837,9 @@ describe('AdvanceRequestService', () => { describe('getTeamAdvanceRequests():', () => { it('should get all team advance requests | APPROVAL PENDING AND APPROVED', (done) => { - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - apiv2Service.get.and.returnValue(of(allTeamAdvanceRequestsRes)); + authService.getEou.and.resolveTo(apiEouRes); + const mockApiV2Res = cloneDeep(allTeamAdvanceRequestsRes); + apiv2Service.get.and.returnValue(of(mockApiV2Res)); const params = { offset: 0, @@ -849,7 +860,7 @@ describe('AdvanceRequestService', () => { }; advanceRequestService.getTeamAdvanceRequests(params).subscribe((res) => { - expect(res).toEqual(allTeamAdvanceRequestsRes); + expect(res).toEqual(mockApiV2Res); expect(apiv2Service.get).toHaveBeenCalledOnceWith('/advance_requests', { params: { offset: params.offset, @@ -866,8 +877,9 @@ describe('AdvanceRequestService', () => { }); it('should get all team advance requests | APPROVAL PENDING', (done) => { - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - apiv2Service.get.and.returnValue(of(allTeamAdvanceRequestsRes)); + authService.getEou.and.resolveTo(apiEouRes); + const mockApiV2Res = cloneDeep(allTeamAdvanceRequestsRes); + apiv2Service.get.and.returnValue(of(mockApiV2Res)); const params = { offset: 0, @@ -888,7 +900,7 @@ describe('AdvanceRequestService', () => { }; advanceRequestService.getTeamAdvanceRequests(params).subscribe((res) => { - expect(res).toEqual(allTeamAdvanceRequestsRes); + expect(res).toEqual(mockApiV2Res); expect(apiv2Service.get).toHaveBeenCalledOnceWith('/advance_requests', { params: { offset: params.offset, @@ -905,8 +917,9 @@ describe('AdvanceRequestService', () => { }); it('should get all team advance requests | APPROVED', (done) => { - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - apiv2Service.get.and.returnValue(of(allTeamAdvanceRequestsRes)); + authService.getEou.and.resolveTo(apiEouRes); + const mockApiV2Res = cloneDeep(allTeamAdvanceRequestsRes); + apiv2Service.get.and.returnValue(of(mockApiV2Res)); const params = { offset: 0, @@ -927,7 +940,7 @@ describe('AdvanceRequestService', () => { }; advanceRequestService.getTeamAdvanceRequests(params).subscribe((res) => { - expect(res).toEqual(allTeamAdvanceRequestsRes); + expect(res).toEqual(mockApiV2Res); expect(apiv2Service.get).toHaveBeenCalledOnceWith('/advance_requests', { params: { offset: params.offset, diff --git a/src/app/core/services/advance.service.spec.ts b/src/app/core/services/advance.service.spec.ts index 9928262776..0c2fc4fc66 100644 --- a/src/app/core/services/advance.service.spec.ts +++ b/src/app/core/services/advance.service.spec.ts @@ -9,6 +9,7 @@ import { apiEouRes } from '../mock-data/extended-org-user.data'; import { of } from 'rxjs'; import { SpenderService } from './platform/v1/spender/spender.service'; import { advancePlatform } from '../mock-data/advance-platform.data'; +import { cloneDeep } from 'lodash'; describe('AdvanceService', () => { let advanceService: AdvanceService; @@ -59,8 +60,9 @@ describe('AdvanceService', () => { }); it('fixDates(): should convert string values to dates', () => { + const mockExtendedAdvData = cloneDeep(extendedAdvWithoutDates); //@ts-ignore - expect(advanceService.fixDates(extendedAdvWithoutDates)).toEqual(extendedAdvWithDates); + expect(advanceService.fixDates(mockExtendedAdvData)).toEqual(extendedAdvWithDates); }); describe('getSpenderAdvances():', () => { diff --git a/src/app/core/services/custom-fields.service.spec.ts b/src/app/core/services/custom-fields.service.spec.ts index e44f62bbdd..2e9db98db7 100644 --- a/src/app/core/services/custom-fields.service.spec.ts +++ b/src/app/core/services/custom-fields.service.spec.ts @@ -9,6 +9,7 @@ import { import { customInputData, platformApiResponse } from '../test-data/custom-inputs.spec.data'; import { CustomFieldsService } from './custom-fields.service'; +import { cloneDeep } from 'lodash'; describe('CustomFieldsService', () => { let customFieldsService: CustomFieldsService; @@ -41,22 +42,26 @@ describe('CustomFieldsService', () => { describe('setDefaultValue():', () => { it('should set default value to false for boolean type', () => { - const result = customFieldsService.setDefaultValue(txnCustomPropertiesData3[0], 'BOOLEAN'); - expect(result.value).toBe(false); + const mockTxnCustomProperties = cloneDeep(txnCustomPropertiesData3[0]); + const result = customFieldsService.setDefaultValue(mockTxnCustomProperties, 'BOOLEAN'); + expect(result.value).toBeFalse(); }); it('should set default value to empty string for select type', () => { - const result = customFieldsService.setDefaultValue(txnCustomPropertiesData3[1], 'SELECT'); + const mockTxnCustomProperties = cloneDeep(txnCustomPropertiesData3[1]); + const result = customFieldsService.setDefaultValue(mockTxnCustomProperties, 'SELECT'); expect(result.value).toBe(''); }); it('should set default value to empty string for multi select type', () => { - const result = customFieldsService.setDefaultValue(txnCustomPropertiesData[2], 'MULTI_SELECT'); + const mockTxnCustomProperties = cloneDeep(txnCustomPropertiesData3[2]); + const result = customFieldsService.setDefaultValue(mockTxnCustomProperties, 'MULTI_SELECT'); expect(result.value).toBe(''); }); it('should set default value to empty string for user select type', () => { - const result = customFieldsService.setDefaultValue(txnCustomPropertiesData[0], 'USER_LIST'); + const mockTxnCustomProperties = cloneDeep(txnCustomPropertiesData[0]); + const result = customFieldsService.setDefaultValue(mockTxnCustomProperties, 'USER_LIST'); expect(result.value).toEqual([]); }); }); diff --git a/src/app/core/services/date.service.spec.ts b/src/app/core/services/date.service.spec.ts index b01cce04d3..cf2961e769 100644 --- a/src/app/core/services/date.service.spec.ts +++ b/src/app/core/services/date.service.spec.ts @@ -24,11 +24,11 @@ describe('DateService', () => { }); it('firstOfThisMonth(): get the first day of the month', () => { - expect(dateService.firstOfThisMonth()).toEqual(new Date(year, month, 1)); + expect(dateService.firstOfThisMonth().toDateString()).toEqual(new Date(year, month, 1).toDateString()); }); it('lastOfThisMonth(): get the last day of the month', () => { - expect(dateService.lastOfThisMonth()).toEqual(new Date(year, month + 1, 0, 23, 59)); + expect(dateService.lastOfThisMonth().toDateString()).toEqual(new Date(year, month + 1, 0, 23, 59).toDateString()); }); it('isValidDate(): check if date is valid', () => { @@ -60,11 +60,11 @@ describe('DateService', () => { }); it('firstOfLastMonth(): should get the first of last month', () => { - expect(dateService.firstOfLastMonth()).toEqual(new Date(year, month - 1, 1)); + expect(dateService.firstOfLastMonth().toDateString()).toEqual(new Date(year, month - 1, 1).toDateString()); }); it('lastOfLastMonth(): should get the last of last month', () => { - expect(dateService.lastOfLastMonth()).toEqual(new Date(year, month, 0, 23, 59)); + expect(dateService.lastOfLastMonth().toDateString()).toEqual(new Date(year, month, 0, 23, 59).toDateString()); }); it("getLastMonthRange(): should get last month's range", () => { diff --git a/src/app/core/services/expense-fields.service.spec.ts b/src/app/core/services/expense-fields.service.spec.ts index bdd8c9cc81..dece8e2e40 100644 --- a/src/app/core/services/expense-fields.service.spec.ts +++ b/src/app/core/services/expense-fields.service.spec.ts @@ -19,6 +19,7 @@ import { SpenderPlatformV1ApiService } from './spender-platform-v1-api.service'; import { AuthService } from './auth.service'; import { ExpenseFieldsService } from './expense-fields.service'; +import { cloneDeep } from 'lodash'; describe('ExpenseFieldsService', () => { let expenseFieldsService: ExpenseFieldsService; @@ -84,8 +85,9 @@ describe('ExpenseFieldsService', () => { it('filterbyCategory(): should filter expense fields by category', (done) => { const fields = ['purpose', 'txn_dt', 'vendor_id', 'org_category_id']; + const mockExpenseFieldsMapResponse = cloneDeep(expenseFieldsMapResponse); expenseFieldsService - .filterByOrgCategoryId(expenseFieldsMapResponse, fields, orgCategoryData) + .filterByOrgCategoryId(mockExpenseFieldsMapResponse, fields, orgCategoryData) .subscribe((expenseFields) => { expect(expenseFields).toEqual(expenseFieldObjData); done(); diff --git a/src/app/core/services/location.service.spec.ts b/src/app/core/services/location.service.spec.ts index fee47c6bcd..74bdd84cf3 100644 --- a/src/app/core/services/location.service.spec.ts +++ b/src/app/core/services/location.service.spec.ts @@ -4,6 +4,7 @@ import { of, delay } from 'rxjs'; import { LocationService } from './location.service'; import { locationData1, locationData2, locationData4, predictedLocation1 } from '../mock-data/location.data'; import { HttpParams } from '@angular/common/http'; +import { cloneDeep } from 'lodash'; describe('LocationService', () => { let locationService: LocationService; @@ -101,7 +102,7 @@ describe('LocationService', () => { it('should return location details with display name if displayName is provided', () => { const placeId = 'pLcId123'; const displayName = 'Tollygunge, Kolkata, West Bengal, India'; - const locationDetails = locationData1; + const locationDetails = cloneDeep(locationData1); locationService.getGeocode(placeId, displayName).subscribe((result) => { expect(result).toEqual(locationDetails); }); @@ -114,7 +115,7 @@ describe('LocationService', () => { it('should not add the displayName to locationDetails when displayName is not provided', () => { const placeId = '12345'; const displayName = ''; - const locationDetails = locationData4; + const locationDetails = cloneDeep(locationData4); locationService.getGeocode(placeId, displayName).subscribe((result) => { expect(result).toEqual(locationDetails); }); diff --git a/src/app/core/services/merge-expenses.service.spec.ts b/src/app/core/services/merge-expenses.service.spec.ts index c44b0de4b4..38f2b9a759 100644 --- a/src/app/core/services/merge-expenses.service.spec.ts +++ b/src/app/core/services/merge-expenses.service.spec.ts @@ -1020,7 +1020,7 @@ describe('MergeExpensesService', () => { }); it('should return the formatted category option', (done) => { - const mockOptions = mergeExpensesOptionData4[0]; + const mockOptions = cloneDeep(mergeExpensesOptionData4[0]); // @ts-ignore mergeExpensesService.formatCategoryOption(mockOptions).subscribe((res) => { expect(res).toEqual(mockOptions); @@ -1031,8 +1031,9 @@ describe('MergeExpensesService', () => { }); it('should return the formatted category option with label as Unspecified if id does not matches with options', (done) => { + const mockOptions = cloneDeep({ ...mergeExpensesOptionData4[0], value: 201951 }); // @ts-ignore - mergeExpensesService.formatCategoryOption({ ...mergeExpensesOptionData4[0], value: 201951 }).subscribe((res) => { + mergeExpensesService.formatCategoryOption(mockOptions).subscribe((res) => { expect(res).toEqual({ label: 'Unspecified', value: 201951, diff --git a/src/app/core/services/org-settings.service.spec.ts b/src/app/core/services/org-settings.service.spec.ts index ee72ec870c..efc7e942f5 100644 --- a/src/app/core/services/org-settings.service.spec.ts +++ b/src/app/core/services/org-settings.service.spec.ts @@ -26,6 +26,7 @@ import { } from '../test-data/org-settings.service.spec.data'; import { OrgSettingsService } from './org-settings.service'; +import { cloneDeep } from 'lodash'; const getApiData: OrgSettings = orgSettingsGetData; const postApiData: OrgSettingsResponse = orgSettingsPostData; @@ -68,7 +69,8 @@ describe('OrgSettingsService', () => { }); it('should be able to get the org settings properly', (done) => { - apiService.get.and.returnValue(of(postApiData)); + const mockApiResponse = cloneDeep(postApiData); + apiService.get.and.returnValue(of(mockApiResponse)); orgSettingsService.get().subscribe((res) => { expect(res).toEqual(getApiData); done(); @@ -84,9 +86,8 @@ describe('OrgSettingsService', () => { }); it('should be able to get incoming tally account object', () => { - expect(orgSettingsService.getIncomingAccountingObject(outgoingTallyAccountObject)).toEqual( - incomingTallyAccountObject - ); + const mockAccountingObject = cloneDeep(outgoingTallyAccountObject); + expect(orgSettingsService.getIncomingAccountingObject(mockAccountingObject)).toEqual(incomingTallyAccountObject); }); it('should be able to set outgoing tally account object', () => { @@ -96,7 +97,8 @@ describe('OrgSettingsService', () => { }); it('should be able to get incoming quick books account object', () => { - expect(orgSettingsService.getIncomingAccountingObject(outgoingQuickbooksAccountObject)).toEqual( + const mockAccountingObject = cloneDeep(outgoingQuickbooksAccountObject); + expect(orgSettingsService.getIncomingAccountingObject(mockAccountingObject)).toEqual( incomingQuickBooksAccountObject ); }); diff --git a/src/app/core/services/recent-local-storage-items.service.spec.ts b/src/app/core/services/recent-local-storage-items.service.spec.ts index ae6f6d1f98..bff4c7fb2c 100644 --- a/src/app/core/services/recent-local-storage-items.service.spec.ts +++ b/src/app/core/services/recent-local-storage-items.service.spec.ts @@ -9,6 +9,7 @@ import { postRecentItemsRes, } from '../mock-data/recent-local-storage-items.data'; import * as dayjs from 'dayjs'; +import { cloneDeep } from 'lodash'; describe('RecentLocalStorageItemsService', () => { let recentLocalStorageItemsService: RecentLocalStorageItemsService; @@ -71,7 +72,7 @@ describe('RecentLocalStorageItemsService', () => { updatedAt: dayjs().toISOString(), recentItems, }; - storageService.get.and.returnValue(Promise.resolve(cache)); + storageService.get.and.resolveTo(cache); const result = await recentLocalStorageItemsService.get(cacheName); expect(storageService.get).toHaveBeenCalledOnceWith(cacheName); @@ -84,7 +85,7 @@ describe('RecentLocalStorageItemsService', () => { updatedAt: dayjs().diff(5, 'minute').toString(), recentItems: recentLocalStorageItemsRes, }; - storageService.get.and.returnValue(Promise.resolve(outdatedCache)); + storageService.get.and.resolveTo(outdatedCache); const result = await recentLocalStorageItemsService.get(cacheName); expect(storageService.get).toHaveBeenCalledOnceWith(cacheName); expect(result).toEqual([]); @@ -115,40 +116,42 @@ describe('RecentLocalStorageItemsService', () => { describe('post():', () => { it('should maintain and update a cache of recent items in the local storage', async () => { const cacheName = 'mileageSubCategoryName'; - const recentItems = postRecentItemsRes; + const mockPostRecentItemsRes = cloneDeep(postRecentItemsRes); + const recentItems = mockPostRecentItemsRes; const cache = { recentItems, updatedAt: jasmine.any(Date), }; const indexOfItemSpy = spyOn(recentLocalStorageItemsService, 'indexOfItem'); - const getSpy = spyOn(recentLocalStorageItemsService, 'get').and.returnValue(Promise.resolve(postRecentItemsRes)); + const getSpy = spyOn(recentLocalStorageItemsService, 'get').and.resolveTo(mockPostRecentItemsRes); await recentLocalStorageItemsService.post(cacheName, itemsRes, propertyRes); - storageService.set.and.returnValue(Promise.resolve()); + storageService.set.and.resolveTo(); expect(indexOfItemSpy).toHaveBeenCalledOnceWith(recentItems, itemsRes, propertyRes); expect(getSpy).toHaveBeenCalledOnceWith(cacheName); recentLocalStorageItemsService.post(cacheName, itemsRes, propertyRes).then((res) => { - expect(res).toEqual(postRecentItemsRes); + expect(res).toEqual(mockPostRecentItemsRes); }); expect(storageService.set).toHaveBeenCalledOnceWith(cacheName, cache); }); it('should find the index of an item without the property argument', async () => { const cacheName = 'mileageSubCategoryName'; - const recentItems = postRecentItemsRes; + const mockPostRecentItemsRes = cloneDeep(postRecentItemsRes); + const recentItems = mockPostRecentItemsRes; const cache = { recentItems, updatedAt: jasmine.any(Date), }; - const getSpy = spyOn(recentLocalStorageItemsService, 'get').and.returnValue(Promise.resolve(postRecentItemsRes)); + const getSpy = spyOn(recentLocalStorageItemsService, 'get').and.resolveTo(mockPostRecentItemsRes); await recentLocalStorageItemsService.post(cacheName, itemsRes); - storageService.set.and.returnValue(Promise.resolve()); + storageService.set.and.resolveTo(); expect(getSpy).toHaveBeenCalledOnceWith(cacheName); recentLocalStorageItemsService.post(cacheName, itemsRes).then((res) => { - expect(res).toEqual(postRecentItemsRes); + expect(res).toEqual(mockPostRecentItemsRes); }); expect(storageService.set).toHaveBeenCalledOnceWith(cacheName, cache); }); diff --git a/src/app/core/services/status.service.spec.ts b/src/app/core/services/status.service.spec.ts index cd8c87ac73..aaa84be579 100644 --- a/src/app/core/services/status.service.spec.ts +++ b/src/app/core/services/status.service.spec.ts @@ -8,6 +8,7 @@ import { getApiResponse, updateReponseWithFlattenedEStatus, } from '../test-data/status.service.spec.data'; +import { cloneDeep } from 'lodash'; describe('StatusService', () => { let statusService: StatusService; @@ -37,7 +38,8 @@ describe('StatusService', () => { }); it('should find all estatuses', (done) => { - apiService.get.and.returnValue(of(getApiResponse)); + const mockGetApiResponse = cloneDeep(getApiResponse); + apiService.get.and.returnValue(of(mockGetApiResponse)); statusService.find(type, id).subscribe((res) => { expect(res).toEqual(getEstatusApiResponse); @@ -49,18 +51,20 @@ describe('StatusService', () => { apiService.get.and.returnValue(of(null)); statusService.find(type, id).subscribe((res) => { - expect(res).toEqual(undefined); + expect(res).toBeUndefined(); done(); }); }); it('should use status map and update the comments accordingly by adding statuses', () => { - const result = statusService.createStatusMap(apiCommentsResponse, 'reports'); + const mockApiCommentsResponse = cloneDeep(apiCommentsResponse); + const result = statusService.createStatusMap(mockApiCommentsResponse, 'reports'); expect(result).toEqual(updateReponseWithFlattenedEStatus); }); it('should find and return the latest comment', (done) => { - apiService.get.and.returnValue(of(getApiResponse)); + const mockGetApiResponse = cloneDeep(getApiResponse); + apiService.get.and.returnValue(of(mockGetApiResponse)); const result = statusService.findLatestComment(id, type, 'POLICY'); result.subscribe((res) => { diff --git a/src/app/core/services/transaction.service.spec.ts b/src/app/core/services/transaction.service.spec.ts index 92c60e12f2..06308a10f4 100644 --- a/src/app/core/services/transaction.service.spec.ts +++ b/src/app/core/services/transaction.service.spec.ts @@ -58,6 +58,7 @@ import { matchCCCExpenseResponseData, unmatchCCCExpenseResponseData, } from '../mock-data/corporate-card-transaction-response.data'; +import { cloneDeep } from 'lodash'; describe('TransactionService', () => { let transactionService: TransactionService; @@ -249,7 +250,7 @@ describe('TransactionService', () => { it('getDefaultVehicleType(): should get default vehicle type', (done) => { const defaultVehicleType = 'two_wheeler'; - storageService.get.and.returnValue(Promise.resolve(defaultVehicleType)); + storageService.get.and.resolveTo(defaultVehicleType); transactionService.getDefaultVehicleType().subscribe((res) => { expect(res).toEqual(defaultVehicleType); expect(storageService.get).toHaveBeenCalledTimes(1); @@ -317,6 +318,7 @@ describe('TransactionService', () => { beforeEach(() => { spyOn(lodash, 'cloneDeep').and.returnValue(params); }); + it('should return receipt attached params if receipt attached is YES', () => { const filters = { receiptsAttached: 'YES' }; const receiptsAttachedParams = { or: [], tx_num_files: 'gt.0' }; @@ -412,8 +414,9 @@ describe('TransactionService', () => { }); it('fixDates(): should fix dates', () => { + const mockExpenseData = cloneDeep(expenseDataWithDateString); // @ts-ignore - expect(transactionService.fixDates(expenseDataWithDateString)).toEqual(expenseData1); + expect(transactionService.fixDates(mockExpenseData)).toEqual(expenseData1); }); it('getPaymentModeforEtxn(): should return payment mode for etxn', () => { @@ -858,7 +861,7 @@ describe('TransactionService', () => { }); it('getMyExpenses(): should return my expenses with order', (done) => { - authService.getEou.and.returnValue(Promise.resolve(eouRes2)); + authService.getEou.and.resolveTo(eouRes2); apiV2Service.get.and.returnValue(of(expenseV2Data)); dateService.fixDatesV2.and.returnValue(expenseV2Data.data[0]); @@ -891,7 +894,7 @@ describe('TransactionService', () => { }); it('getMyExpenses(): should return my expenses without order using default date order', (done) => { - authService.getEou.and.returnValue(Promise.resolve(eouRes2)); + authService.getEou.and.resolveTo(eouRes2); apiV2Service.get.and.returnValue(of(expenseV2Data)); dateService.fixDatesV2.and.returnValue(expenseV2Data.data[0]); @@ -1201,7 +1204,7 @@ describe('TransactionService', () => { spyOn(transactionService, 'getIsCriticalPolicyViolated').and.returnValue(false); spyOn(transactionService, 'getIsDraft').and.returnValue(false); - expect(transactionService.getReportableExpenses(null)).toEqual(undefined); + expect(transactionService.getReportableExpenses(null)).toBeUndefined(); expect(transactionService.getIsCriticalPolicyViolated).not.toHaveBeenCalled(); expect(transactionService.getIsDraft).not.toHaveBeenCalled(); }); @@ -1231,10 +1234,11 @@ describe('TransactionService', () => { orgUserSettingsService.get.and.returnValue(of(orgUserSettingsData2)); spenderPlatformV1ApiService.post.and.returnValue(of(expensePolicyData)); - transactionService.checkPolicy(platformPolicyExpenseData1).subscribe((res) => { + const mockPlatformExpense = cloneDeep(platformPolicyExpenseData1); + transactionService.checkPolicy(mockPlatformExpense).subscribe((res) => { expect(res).toEqual(expensePolicyData); expect(spenderPlatformV1ApiService.post).toHaveBeenCalledOnceWith('/expenses/check_policies', { - data: platformPolicyExpenseData1, + data: mockPlatformExpense, }); expect(orgUserSettingsService.get).toHaveBeenCalledTimes(1); done(); @@ -1245,7 +1249,8 @@ describe('TransactionService', () => { spyOn(transactionService, 'upsert').and.returnValue(of(txnData2)); fileService.post.and.returnValue(of(fileObjectData2)); - transactionService.createTxnWithFiles(txnData, of(fileObjectData1)).subscribe((res) => { + const mockFileObject = cloneDeep(fileObjectData1); + transactionService.createTxnWithFiles(txnData, of(mockFileObject)).subscribe((res) => { expect(res).toEqual(txnData2); expect(transactionService.upsert).toHaveBeenCalledOnceWith(txnData); expect(fileService.post).toHaveBeenCalledOnceWith(fileObjectData2); @@ -1262,7 +1267,8 @@ describe('TransactionService', () => { apiService.post.and.returnValue(of(txnData4)); utilityService.discardRedundantCharacters.and.returnValue(txnDataPayload); - transactionService.upsert(upsertTxnParam).subscribe((res) => { + const mockUpsertTxnParam = cloneDeep(upsertTxnParam); + transactionService.upsert(mockUpsertTxnParam).subscribe((res) => { expect(res).toEqual(txnData4); expect(apiService.post).toHaveBeenCalledOnceWith('/transactions', txnDataPayload); expect(orgUserSettingsService.get).toHaveBeenCalledTimes(1); diff --git a/src/app/core/services/utility.service.spec.ts b/src/app/core/services/utility.service.spec.ts index fb6be14085..459a591973 100644 --- a/src/app/core/services/utility.service.spec.ts +++ b/src/app/core/services/utility.service.spec.ts @@ -37,13 +37,14 @@ describe('UtilityService', () => { describe('refineNestedObject():', () => { it('should return the nested object when the custom field type is number, string etc', () => { - expect(utilityService.refineNestedObject(customFieldData1)).toEqual(customFieldData1); + const mockCustomField = cloneDeep(customFieldData1); + expect(utilityService.refineNestedObject(mockCustomField)).toEqual(customFieldData1); }); it('should return the nested object when the custom field type is select', () => { spyOn(utilityService, 'discardNullChar').and.returnValue('select-1'); const mockCustomFieldData = cloneDeep(customFieldData2); - expect(utilityService.refineNestedObject(customFieldData2)).toEqual(customFieldData2); + expect(utilityService.refineNestedObject(mockCustomFieldData)).toEqual(customFieldData2); expect(utilityService.discardNullChar).toHaveBeenCalledOnceWith('select-1'); }); }); diff --git a/src/app/core/services/virtual-cards.service.spec.ts b/src/app/core/services/virtual-cards.service.spec.ts index 92f1512845..d84591a7e0 100644 --- a/src/app/core/services/virtual-cards.service.spec.ts +++ b/src/app/core/services/virtual-cards.service.spec.ts @@ -13,6 +13,7 @@ import { virtualCardResponse, virtualCardUndefinedResponse } from '../mock-data/ import { VirtualCardsCombinedRequest } from '../models/virtual-cards-combined-request.model'; import { cardDetailsRes } from '../mock-data/platform-corporate-card-detail.data'; import { virtualCardCombinedRequest } from '../mock-data/virtual-cards-combined-request.data'; +import { cloneDeep } from 'lodash'; describe('VirtualCardsService', () => { let virtualCardsService: VirtualCardsService; @@ -48,9 +49,9 @@ describe('VirtualCardsService', () => { const virtualCardsRequest: VirtualCardsRequest = { id: 'vc1234', }; - const expectedResponse: { data: CardDetailsResponse } = virtualCardDetailsResponse; + const expectedResponse: { data: CardDetailsResponse } = cloneDeep(virtualCardDetailsResponse); expectedResponse.data.expiry_date = new Date(expectedResponse.data.expiry_date); - spenderPlatformV1ApiService.post.and.returnValue(of(virtualCardDetailsResponse)); + spenderPlatformV1ApiService.post.and.returnValue(of(expectedResponse)); virtualCardsService.getCardDetails(virtualCardsRequest).subscribe((res) => { expect(res).toEqual(expectedResponse.data); @@ -108,7 +109,7 @@ describe('VirtualCardsService', () => { spenderPlatformV1ApiService.get.and.returnValue(of(virtualCardUndefinedResponse)); virtualCardsService.getVirtualCard(virtualCardsRequest).subscribe((res) => { - expect(res).toEqual(undefined); + expect(res).toBeUndefined(); done(); }); }); diff --git a/src/app/fyle/add-edit-mileage/add-edit-mileage-1.spec.ts b/src/app/fyle/add-edit-mileage/add-edit-mileage-1.spec.ts index 4af092b537..3df2e2eb22 100644 --- a/src/app/fyle/add-edit-mileage/add-edit-mileage-1.spec.ts +++ b/src/app/fyle/add-edit-mileage/add-edit-mileage-1.spec.ts @@ -925,7 +925,7 @@ export function TestCases1(getTestBed) { it('should return an error object when the date is after the upper bound of the valid range', () => { const tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 2); + tomorrow.setDate(tomorrow.getDate() + 3); const control = new FormControl(tomorrow.toDateString()); const result = component.customDateValidator(control); expect(result).toEqual({ invalidDateSelection: true }); diff --git a/src/app/fyle/my-create-report/my-create-report.page.spec.ts b/src/app/fyle/my-create-report/my-create-report.page.spec.ts index 90d3999c9b..e965d77d56 100644 --- a/src/app/fyle/my-create-report/my-create-report.page.spec.ts +++ b/src/app/fyle/my-create-report/my-create-report.page.spec.ts @@ -375,9 +375,10 @@ describe('MyCreateReportPage', () => { it('toggleTransaction(): should toggle selected transaction to unselected', () => { spyOn(component, 'getReportTitle'); - component.toggleTransaction(selectedExpense1); + const mockSelectedExpense = cloneDeep(selectedExpense1); + component.toggleTransaction(mockSelectedExpense); - expect(selectedExpense1.isSelected).toBeFalse(); + expect(mockSelectedExpense.isSelected).toBeFalse(); expect(component.getReportTitle).toHaveBeenCalledTimes(1); }); diff --git a/src/app/fyle/my-profile/employee-details-card/employee-details-card.component.spec.ts b/src/app/fyle/my-profile/employee-details-card/employee-details-card.component.spec.ts index 450ebd62a8..55d6269fb4 100644 --- a/src/app/fyle/my-profile/employee-details-card/employee-details-card.component.spec.ts +++ b/src/app/fyle/my-profile/employee-details-card/employee-details-card.component.spec.ts @@ -6,6 +6,7 @@ import { apiEouRes } from 'src/app/core/mock-data/extended-org-user.data'; import { getTextContent } from 'src/app/core/dom-helpers'; import { getElementBySelector } from 'src/app/core/dom-helpers'; import { click } from 'src/app/core/dom-helpers'; +import { cloneDeep } from 'lodash'; describe('EmployeeDetailsCardComponent', () => { let component: EmployeeDetailsCardComponent; @@ -20,7 +21,8 @@ describe('EmployeeDetailsCardComponent', () => { fixture = TestBed.createComponent(EmployeeDetailsCardComponent); component = fixture.componentInstance; - component.eou = apiEouRes; + const mockApiEouRes = cloneDeep(apiEouRes); + component.eou = mockApiEouRes; fixture.detectChanges(); })); diff --git a/src/app/fyle/my-reports/my-reports.page.spec.ts b/src/app/fyle/my-reports/my-reports.page.spec.ts index 89afdd819f..558b18df87 100644 --- a/src/app/fyle/my-reports/my-reports.page.spec.ts +++ b/src/app/fyle/my-reports/my-reports.page.spec.ts @@ -1237,7 +1237,8 @@ describe('MyReportsPage', () => { }; const expectedAndQuery = `(rp_created_at.gte.${thisMonthRange.from.toISOString()},rp_created_at.lt.${thisMonthRange.to.toISOString()})`; dateService.getThisMonthRange.and.returnValue(thisMonthRange); - component.filters = filter8; + const mockFilter = cloneDeep(filter8); + component.filters = mockFilter; component.generateDateParams(newQueryParams); @@ -1254,7 +1255,8 @@ describe('MyReportsPage', () => { }; const expectedAndQuery = `(rp_created_at.gte.${thisWeekRange.from.toISOString()},rp_created_at.lt.${thisWeekRange.to.toISOString()})`; dateService.getThisWeekRange.and.returnValue(thisWeekRange); - component.filters = filter9; + const mockFilter = cloneDeep(filter9); + component.filters = mockFilter; component.generateDateParams(newQueryParams); @@ -1271,7 +1273,8 @@ describe('MyReportsPage', () => { }; const expectedAndQuery = `(rp_created_at.gte.${lastMonthRange.from.toISOString()},rp_created_at.lt.${lastMonthRange.to.toISOString()})`; dateService.getLastMonthRange.and.returnValue(lastMonthRange); - component.filters = filter10; + const mockFilter = cloneDeep(filter10); + component.filters = mockFilter; component.generateDateParams(newQueryParams); @@ -1282,7 +1285,8 @@ describe('MyReportsPage', () => { it('should not generate date params when date filter is not set', () => { spyOn(component, 'generateCustomDateParams'); const newQueryParams: { or: string[]; and?: string } = { or: [] }; - component.filters = filter11; + const mockFilter = cloneDeep(filter11); + component.filters = mockFilter; component.generateDateParams(newQueryParams); @@ -1292,7 +1296,8 @@ describe('MyReportsPage', () => { it('should convert customDateStart and customDateEnd string to date', () => { spyOn(component, 'generateCustomDateParams'); - component.filters = filter12; + const mockFilter = cloneDeep(filter12); + component.filters = mockFilter; const newQueryParams: { or: string[]; and?: string } = { or: [] }; component.generateDateParams(newQueryParams); @@ -1448,7 +1453,7 @@ describe('MyReportsPage', () => { 'present', 'onWillDismiss', ]); - popoverController.create.and.returnValue(Promise.resolve(cannotDeleteReportPopOverSpy)); + popoverController.create.and.resolveTo(cannotDeleteReportPopOverSpy); const mockErpt = cloneDeep({ ...apiExtendedReportRes[0], rp_state: 'APPROVED' }); component.onDeleteReportClick(mockErpt); @@ -1460,7 +1465,7 @@ describe('MyReportsPage', () => { it('should call the deleteReport and do a refresh if rp_state consist any of DRAFT, APPROVER_PENDING, APPROVER_INQUIRY', fakeAsync(() => { const deleteReportPopoverSpy = jasmine.createSpyObj('deleteReportPopover', ['present', 'onDidDismiss']); deleteReportPopoverSpy.onDidDismiss.and.resolveTo({ data: { status: 'success' } }); - popoverController.create.and.returnValue(Promise.resolve(deleteReportPopoverSpy)); + popoverController.create.and.resolveTo(deleteReportPopoverSpy); spyOn(component, 'doRefresh'); spyOn(component, 'getDeleteReportPopoverParams').and.returnValue(deletePopoverParamsRes); reportService.delete.and.returnValue(of(null)); @@ -1526,7 +1531,7 @@ describe('MyReportsPage', () => { expect(component.simpleSearchText).toEqual(''); expect(inputElement.value).toEqual(''); expect(dispatchEventSpy).toHaveBeenCalledOnceWith(new Event('keyup')); - expect(component.isSearchBarFocused).toEqual(true); + expect(component.isSearchBarFocused).toBeTrue(); }); it('should clear the search text, input value, dispatch keyup event, and toggle search bar focus when called from onSimpleSearchCancel', () => { @@ -1542,7 +1547,7 @@ describe('MyReportsPage', () => { expect(component.simpleSearchText).toEqual(''); expect(inputElement.value).toEqual(''); expect(dispatchEventSpy).toHaveBeenCalledOnceWith(new Event('keyup')); - expect(component.isSearchBarFocused).toEqual(false); + expect(component.isSearchBarFocused).toBeFalse(); }); }); @@ -1562,7 +1567,7 @@ describe('MyReportsPage', () => { inputElement.dispatchEvent(new Event('focus')); - expect(component.isSearchBarFocused).toEqual(true); + expect(component.isSearchBarFocused).toBeTrue(); }); it('onFilterPillsClearAll(): should call clearFilters', () => { @@ -1937,6 +1942,7 @@ describe('MyReportsPage', () => { beforeEach(() => { spyOn(component, 'convertSelectedSortFitlersToFilters'); }); + it('should convert selected filters to corresponding Filters object', () => { const selectedFilters = selectedFilters3; @@ -2408,7 +2414,7 @@ describe('MyReportsPage', () => { ]); spyOn(component, 'generateSelectedFilters').and.returnValue([{ name: 'state', value: 'PENDING' }]); filterPopoverSpy.onWillDismiss.and.resolveTo({ data: selectedFilters1 }); - modalController.create.and.returnValue(Promise.resolve(filterPopoverSpy)); + modalController.create.and.resolveTo(filterPopoverSpy); component.openFilters('State'); tick(200); diff --git a/src/app/fyle/my-view-report/my-view-report.page.spec.ts b/src/app/fyle/my-view-report/my-view-report.page.spec.ts index 6b1120699b..5483771a80 100644 --- a/src/app/fyle/my-view-report/my-view-report.page.spec.ts +++ b/src/app/fyle/my-view-report/my-view-report.page.spec.ts @@ -308,7 +308,8 @@ describe('MyViewReportPage', () => { loaderService.showLoader.and.resolveTo(); reportService.getReport.and.returnValue(of(erpt)); authService.getEou.and.resolveTo(apiEouRes); - statusService.find.and.returnValue(of(newEstatusData1)); + const mockStatusData = cloneDeep(newEstatusData1); + statusService.find.and.returnValue(of(mockStatusData)); statusService.createStatusMap.and.returnValue(systemCommentsWithSt); reportService.getApproversByReportId.and.returnValue(of(approversData1)); expensesService.getReportExpenses.and.returnValue(of(expenseResponseData2)); @@ -401,7 +402,8 @@ describe('MyViewReportPage', () => { loaderService.showLoader.and.resolveTo(); reportService.getReport.and.returnValue(of(null)); authService.getEou.and.resolveTo(apiEouRes); - statusService.find.and.returnValue(of(newEstatusData1)); + const mockStatusData = cloneDeep(newEstatusData1); + statusService.find.and.returnValue(of(mockStatusData)); statusService.createStatusMap.and.returnValue(systemCommentsWithSt); reportService.getApproversByReportId.and.returnValue(of(approversData1)); expensesService.getReportExpenses.and.returnValue(of(expenseResponseData2)); @@ -486,13 +488,14 @@ describe('MyViewReportPage', () => { }); it('updateReportName(): should update report name', () => { - component.erpt$ = of(newReportParam); + const mockErpt = cloneDeep(newReportParam); + component.erpt$ = of(mockErpt); fixture.detectChanges(); reportService.updateReportPurpose.and.returnValue(of(platformReportData)); spyOn(component.loadReportDetails$, 'next'); component.updateReportName('#3: Jul 2023 - Office expense'); - expect(reportService.updateReportPurpose).toHaveBeenCalledOnceWith(newReportParam); + expect(reportService.updateReportPurpose).toHaveBeenCalledOnceWith(mockErpt); expect(component.loadReportDetails$.next).toHaveBeenCalledTimes(1); }); @@ -507,7 +510,7 @@ describe('MyViewReportPage', () => { const editReportNamePopoverSpy = jasmine.createSpyObj('editReportNamePopover', ['present', 'onWillDismiss']); editReportNamePopoverSpy.onWillDismiss.and.resolveTo({ data: { reportName: 'new name' } }); - popoverController.create.and.returnValue(Promise.resolve(editReportNamePopoverSpy)); + popoverController.create.and.resolveTo(editReportNamePopoverSpy); const editReportButton = getElementBySelector(fixture, '.view-reports--card-header__icon') as HTMLElement; click(editReportButton); @@ -533,7 +536,7 @@ describe('MyViewReportPage', () => { const editReportNamePopoverSpy = jasmine.createSpyObj('editReportNamePopover', ['present', 'onWillDismiss']); editReportNamePopoverSpy.onWillDismiss.and.resolveTo(); - popoverController.create.and.returnValue(Promise.resolve(editReportNamePopoverSpy)); + popoverController.create.and.resolveTo(editReportNamePopoverSpy); const editReportButton = getElementBySelector(fixture, '.view-reports--card-header__icon') as HTMLElement; click(editReportButton); @@ -590,7 +593,7 @@ describe('MyViewReportPage', () => { const deleteReportPopoverSpy = jasmine.createSpyObj('deleteReportPopover', ['present', 'onDidDismiss']); deleteReportPopoverSpy.onDidDismiss.and.resolveTo({ data: { status: 'success' } }); - popoverController.create.and.returnValue(Promise.resolve(deleteReportPopoverSpy)); + popoverController.create.and.resolveTo(deleteReportPopoverSpy); component.deleteReportPopup(expectedAllReports[0]); tick(2000); @@ -700,6 +703,7 @@ describe('MyViewReportPage', () => { }, ]); }); + it('should go to edit expense page if canEdit is true', () => { component.canEdit$ = of(true); component.erpt$ = of(expectedAllReports[0]); @@ -828,7 +832,7 @@ describe('MyViewReportPage', () => { email: 'aj@fyle.com', }, }); - modalController.create.and.returnValue(Promise.resolve(shareReportModalSpy)); + modalController.create.and.resolveTo(shareReportModalSpy); reportService.downloadSummaryPdfUrl.and.returnValue(of(null)); matSnackBar.openFromComponent.and.callThrough(); modalProperties.getModalDefaultProperties.and.returnValue(shareReportModalProperties); @@ -863,7 +867,7 @@ describe('MyViewReportPage', () => { const viewInfoModalSpy = jasmine.createSpyObj('viewInfoModal', ['onWillDismiss', 'present']); viewInfoModalSpy.onWillDismiss.and.resolveTo(); - modalController.create.and.returnValue(Promise.resolve(viewInfoModalSpy)); + modalController.create.and.resolveTo(viewInfoModalSpy); modalProperties.getModalDefaultProperties.and.returnValue(fyModalProperties); await component.openViewReportInfoModal(); @@ -964,7 +968,7 @@ describe('MyViewReportPage', () => { }, }); - modalController.create.and.returnValue(Promise.resolve(addExpensesToReportModalSpy)); + modalController.create.and.resolveTo(addExpensesToReportModalSpy); modalProperties.getModalDefaultProperties.and.returnValue(fyModalProperties); spyOn(component, 'addExpensesToReport').and.returnValue(null); @@ -997,7 +1001,7 @@ describe('MyViewReportPage', () => { ]); addExpensesToReportModalSpy.onWillDismiss.and.resolveTo(null); - modalController.create.and.returnValue(Promise.resolve(addExpensesToReportModalSpy)); + modalController.create.and.resolveTo(addExpensesToReportModalSpy); modalProperties.getModalDefaultProperties.and.returnValue(fyModalProperties); spyOn(component, 'addExpensesToReport').and.returnValue(null); diff --git a/src/app/fyle/notifications/notifications.page.spec.ts b/src/app/fyle/notifications/notifications.page.spec.ts index 8a3f6810d9..5170b97d74 100644 --- a/src/app/fyle/notifications/notifications.page.spec.ts +++ b/src/app/fyle/notifications/notifications.page.spec.ts @@ -182,7 +182,8 @@ describe('NotificationsPage', () => { it('removeAdminUnsbscribedEvents(): should remove admin unsubscribe events', fakeAsync(() => { component.orgSettings$ = of(orgSettingsWithUnsubscribeEvent); component.orgSettings = orgSettingsWithUnsubscribeEvent; - component.notificationEvents = cloneDeep(notificationEventsData2); + const mockNotificationEvents = cloneDeep(notificationEventsData2); + component.notificationEvents = cloneDeep(mockNotificationEvents); component.removeAdminUnsbscribedEvents(); tick(500); @@ -191,17 +192,19 @@ describe('NotificationsPage', () => { })); it('updateAdvanceRequestFeatures(): should update advance request features', () => { - component.notificationEvents = notificationEventsData; + const mockNotificationEvents = cloneDeep(notificationEventsData); + component.notificationEvents = mockNotificationEvents; component.orgSettings$ = of(orgSettingsData); component.updateAdvanceRequestFeatures(); - expect(Object.keys(notificationEventsData.features).includes('advances')).toBeFalse(); + expect(Object.keys(mockNotificationEvents.features).includes('advances')).toBeFalse(); }); describe('updateDelegateeNotifyPreference():', () => { it('should set settings to notify delegatee', () => { - component.orgUserSettings = orgUserSettingsData; + const mockOrgUserSettings = cloneDeep(orgUserSettingsData); + component.orgUserSettings = mockOrgUserSettings; component.updateDelegateeNotifyPreference({ value: 'Notify my delegate', @@ -212,7 +215,8 @@ describe('NotificationsPage', () => { }); it('should set settings to notify delegatee and user', () => { - component.orgUserSettings = orgUserSettingsData; + const mockOrgUserSettings = cloneDeep(orgUserSettingsData); + component.orgUserSettings = mockOrgUserSettings; component.updateDelegateeNotifyPreference({ value: 'Notify me and my delegate', @@ -223,7 +227,8 @@ describe('NotificationsPage', () => { }); it('should set settings to notify user', () => { - component.orgUserSettings = orgUserSettingsData; + const mockOrgUserSettings = cloneDeep(orgUserSettingsData); + component.orgUserSettings = mockOrgUserSettings; component.updateDelegateeNotifyPreference({ value: 'Notify me only', diff --git a/src/app/fyle/split-expense/split-expense.page.spec.ts b/src/app/fyle/split-expense/split-expense.page.spec.ts index 5a14efea57..97067e7893 100644 --- a/src/app/fyle/split-expense/split-expense.page.spec.ts +++ b/src/app/fyle/split-expense/split-expense.page.spec.ts @@ -605,12 +605,14 @@ describe('SplitExpensePage', () => { describe('uploadNewFiles(): ', () => { it('should upload new files when the type is an image', (done) => { + const mockFileObjectAdv = cloneDeep(fileObjectData5); const mockFileObject = { - ...fileObjectData5, + ...mockFileObjectAdv, name: '000.jpeg', }; - const files = fileObjectAdv; - const dataUrl = fileObjectAdv[0].url; + const mockFile = cloneDeep(fileObjectAdv); + const files = mockFile; + const dataUrl = mockFile[0].url; const attachmentType = 'image'; transactionsOutboxService.fileUpload.and.resolveTo(mockFileObject); @@ -622,12 +624,13 @@ describe('SplitExpensePage', () => { }); it('should upload new files when the type is a png', (done) => { + const mockFileObjectAdv = cloneDeep(fileObjectAdv); const mockFile = { - ...fileObjectAdv[0], + ...mockFileObjectAdv[0], type: 'png', }; const files = [mockFile]; - const dataUrl = fileObjectAdv[0].url; + const dataUrl = mockFileObjectAdv[0].url; const attachmentType = 'image'; transactionsOutboxService.fileUpload.and.resolveTo(fileObjectData5); @@ -639,12 +642,13 @@ describe('SplitExpensePage', () => { }); it('should upload new files when the type is a pdf', (done) => { - const files = [fileObjectAdv1]; + const files = [cloneDeep(fileObjectAdv1)]; + const mockFileObjectAdv = cloneDeep(fileObjectData5); const mockFileObject = { - ...fileObjectData5, + ...mockFileObjectAdv, name: '000.pdf', }; - const dataUrl = fileObjectAdv1.url; + const dataUrl = files[0].url; const attachmentType = 'pdf'; transactionsOutboxService.fileUpload.and.resolveTo(mockFileObject); component.uploadNewFiles(files).subscribe((result) => { @@ -1499,8 +1503,6 @@ describe('SplitExpensePage', () => { const txnDateRes = component.setTransactionDate(mockSplitExpenseForm, '-05:00:00'); expect(txnDateRes).toEqual(mockUTCDate); - const today = new Date(); - expect(dateService.getUTCDate).toHaveBeenCalledOnceWith(today); expect(timezoneService.convertToUtc).toHaveBeenCalledOnceWith(mockDate, '-05:00:00'); }); }); @@ -2073,12 +2075,10 @@ describe('SplitExpensePage', () => { component.unspecifiedCategory = unspecifiedCategory; component.expenseFields = expenseFieldResponse; const splitEtxns = cloneDeep(txnList); - spyOn(component, 'showSplitExpensePolicyViolationsAndMissingFields').and.returnValue( - Promise.resolve({ - action: 'continue', - comments: { '0': 'test comment' }, - }) - ); + spyOn(component, 'showSplitExpensePolicyViolationsAndMissingFields').and.resolveTo({ + action: 'continue', + comments: { '0': 'test comment' }, + }); policyService.checkIfViolationsExist.and.returnValue(true); splitExpenseService.checkIfMissingFieldsExist.and.returnValue(true); splitExpenseService.handlePolicyAndMissingFieldsCheck.and.returnValue( diff --git a/src/app/fyle/team-reports/team-reports-1.page.spec.ts b/src/app/fyle/team-reports/team-reports-1.page.spec.ts index 60b551bf90..69f3d241e9 100644 --- a/src/app/fyle/team-reports/team-reports-1.page.spec.ts +++ b/src/app/fyle/team-reports/team-reports-1.page.spec.ts @@ -104,7 +104,8 @@ export function TestCases1(getTestBed) { reportService.getTeamReports.and.returnValue(of(paginatedPipeValue)); reportService.getTeamReportsCount.and.returnValue(of(20)); mockAddNewFiltersToParams = spyOn(component, 'addNewFiltersToParams'); - mockAddNewFiltersToParams.and.returnValue(tasksQueryParamsWithFiltersData); + const mockTasksQuery = cloneDeep(tasksQueryParamsWithFiltersData); + mockAddNewFiltersToParams.and.returnValue(mockTasksQuery); spyOn(component, 'generateFilterPills').and.returnValue(creditTxnFilterPill); spyOn(component, 'clearFilters'); }); diff --git a/src/app/fyle/view-team-report/view-team-report.page.spec.ts b/src/app/fyle/view-team-report/view-team-report.page.spec.ts index 454df1552d..0772b9eb9f 100644 --- a/src/app/fyle/view-team-report/view-team-report.page.spec.ts +++ b/src/app/fyle/view-team-report/view-team-report.page.spec.ts @@ -240,9 +240,9 @@ describe('ViewTeamReportPageV2', () => { }); it('loadReports(): should load reports', (done) => { - loaderService.showLoader.and.returnValue(Promise.resolve()); + loaderService.showLoader.and.resolveTo(); reportService.getReport.and.returnValue(of(expectedAllReports[0])); - loaderService.hideLoader.and.returnValue(Promise.resolve()); + loaderService.hideLoader.and.resolveTo(); component .loadReports() @@ -304,17 +304,19 @@ describe('ViewTeamReportPageV2', () => { spyOn(component, 'getApprovalSettings').and.returnValue(true); spyOn(component, 'getReportClosureSettings').and.returnValue(true); spyOn(component, 'isUserActiveInCurrentSeqApprovalQueue').and.returnValue(null); - loaderService.showLoader.and.returnValue(Promise.resolve()); + loaderService.showLoader.and.resolveTo(); spyOn(component, 'loadReports').and.returnValue(of(expectedAllReports[0])); - loaderService.hideLoader.and.returnValue(Promise.resolve()); - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - statusService.find.and.returnValue(of(newEstatusData1)); + loaderService.hideLoader.and.resolveTo(); + authService.getEou.and.resolveTo(apiEouRes); + const mockStatus = cloneDeep(newEstatusData1); + statusService.find.and.returnValue(of(mockStatus)); orgSettingsService.get.and.returnValue(of(orgSettingsData)); statusService.createStatusMap.and.returnValue(systemCommentsWithSt); reportService.getTeamReport.and.returnValue(of(expectedAllReports[0])); + const mockPdfExportData = cloneDeep(pdfExportData1); reportService.getExports.and.returnValue( of({ - results: pdfExportData1, + results: mockPdfExportData, }) ); reportService.getApproversByReportId.and.returnValue(of(approversData1)); @@ -415,17 +417,19 @@ describe('ViewTeamReportPageV2', () => { spyOn(component, 'getApprovalSettings').and.returnValue(false); spyOn(component, 'getReportClosureSettings').and.returnValue(true); spyOn(component, 'isUserActiveInCurrentSeqApprovalQueue').and.returnValue(null); - loaderService.showLoader.and.returnValue(Promise.resolve()); + loaderService.showLoader.and.resolveTo(); spyOn(component, 'loadReports').and.returnValue(of(expectedAllReports[0])); - loaderService.hideLoader.and.returnValue(Promise.resolve()); - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); - statusService.find.and.returnValue(of(newEstatusData1)); + loaderService.hideLoader.and.resolveTo(); + authService.getEou.and.resolveTo(apiEouRes); + const mockStatus = cloneDeep(newEstatusData1); + statusService.find.and.returnValue(of(mockStatus)); orgSettingsService.get.and.returnValue(of(orgSettingsData)); statusService.createStatusMap.and.returnValue(systemCommentsWithSt); reportService.getTeamReport.and.returnValue(of(expectedAllReports[0])); + const mockPdfExportData = cloneDeep(pdfExportData2); reportService.getExports.and.returnValue( of({ - results: pdfExportData2, + results: mockPdfExportData, }) ); reportService.getApproversByReportId.and.returnValue(of(approversData1)); @@ -570,10 +574,10 @@ describe('ViewTeamReportPageV2', () => { }); it('deleteReport(): should delete report', async () => { - popupService.showPopup.and.returnValue(Promise.resolve('primary')); - loaderService.showLoader.and.returnValue(Promise.resolve()); + popupService.showPopup.and.resolveTo('primary'); + loaderService.showLoader.and.resolveTo(); reportService.delete.and.returnValue(of(undefined)); - loaderService.hideLoader.and.returnValue(Promise.resolve()); + loaderService.hideLoader.and.resolveTo(); await component.deleteReport(); @@ -601,15 +605,13 @@ describe('ViewTeamReportPageV2', () => { it('should open the modal and approve the report', async () => { humanizeCurrency.transform.and.callThrough(); const popoverSpy = jasmine.createSpyObj('popover', ['present', 'onWillDismiss']); - popoverSpy.onWillDismiss.and.returnValue( - Promise.resolve({ - data: { - action: 'approve', - }, - }) - ); + popoverSpy.onWillDismiss.and.resolveTo({ + data: { + action: 'approve', + }, + }); - popoverController.create.and.returnValue(Promise.resolve(popoverSpy)); + popoverController.create.and.resolveTo(popoverSpy); reportService.approve.and.returnValue(of(undefined)); refinerService.startSurvey.and.returnValue(null); @@ -745,14 +747,12 @@ describe('ViewTeamReportPageV2', () => { it('shareReport(): should open share report modal', async () => { const popoverSpy = jasmine.createSpyObj('popover', ['present', 'onWillDismiss']); - popoverSpy.onWillDismiss.and.returnValue( - Promise.resolve({ - data: { - email: 'ajn@fyle.in', - }, - }) - ); - popoverController.create.and.returnValue(Promise.resolve(popoverSpy)); + popoverSpy.onWillDismiss.and.resolveTo({ + data: { + email: 'ajn@fyle.in', + }, + }); + popoverController.create.and.resolveTo(popoverSpy); reportService.downloadSummaryPdfUrl.and.returnValue(of({ report_url: 'encodedcontent' })); @@ -780,15 +780,13 @@ describe('ViewTeamReportPageV2', () => { duration: 3000, }; const popoverSpy = jasmine.createSpyObj('popover', ['present', 'onWillDismiss']); - popoverSpy.onWillDismiss.and.returnValue( - Promise.resolve({ - data: { - comment: 'comment', - }, - }) - ); + popoverSpy.onWillDismiss.and.resolveTo({ + data: { + comment: 'comment', + }, + }); - popoverController.create.and.returnValue(Promise.resolve(popoverSpy)); + popoverController.create.and.resolveTo(popoverSpy); reportService.inquire.and.returnValue(of(undefined)); snackbarProperties.setSnackbarProperties.and.returnValue(properties); @@ -823,7 +821,7 @@ describe('ViewTeamReportPageV2', () => { it('openViewReportInfoModal(): should open report info modal', async () => { const viewInfoModalSpy = jasmine.createSpyObj('viewInfoModal', ['onWillDismiss', 'present']); - viewInfoModalSpy.onWillDismiss.and.returnValue(Promise.resolve()); + viewInfoModalSpy.onWillDismiss.and.resolveTo(); const properties = { cssClass: 'fy-modal', @@ -836,7 +834,7 @@ describe('ViewTeamReportPageV2', () => { handle: false, }; - modalController.create.and.returnValue(Promise.resolve(viewInfoModalSpy)); + modalController.create.and.resolveTo(viewInfoModalSpy); modalProperties.getModalDefaultProperties.and.returnValue(properties); await component.openViewReportInfoModal(); @@ -981,13 +979,14 @@ describe('ViewTeamReportPageV2', () => { }); it('updateReportName(): should update report name', () => { - component.erpt$ = of(newReportParam); + const mockErpt = cloneDeep(newReportParam); + component.erpt$ = of(mockErpt); fixture.detectChanges(); reportService.approverUpdateReportPurpose.and.returnValue(of(platformReportData)); spyOn(component.loadReportDetails$, 'next'); component.updateReportName('#3: Jul 2023 - Office expense'); - expect(reportService.approverUpdateReportPurpose).toHaveBeenCalledOnceWith(newReportParam); + expect(reportService.approverUpdateReportPurpose).toHaveBeenCalledOnceWith(mockErpt); expect(component.loadReportDetails$.next).toHaveBeenCalledTimes(1); }); @@ -1000,7 +999,7 @@ describe('ViewTeamReportPageV2', () => { it('should edit report name', fakeAsync(() => { const editReportNamePopoverSpy = jasmine.createSpyObj('editReportNamePopover', ['present', 'onWillDismiss']); editReportNamePopoverSpy.onWillDismiss.and.resolveTo({ data: { reportName: 'new name' } }); - popoverController.create.and.returnValue(Promise.resolve(editReportNamePopoverSpy)); + popoverController.create.and.resolveTo(editReportNamePopoverSpy); component.editReportName(); tick(100); @@ -1018,7 +1017,7 @@ describe('ViewTeamReportPageV2', () => { it('should not edit report name if data does not contain name', fakeAsync(() => { const editReportNamePopoverSpy = jasmine.createSpyObj('editReportNamePopover', ['present', 'onWillDismiss']); editReportNamePopoverSpy.onWillDismiss.and.resolveTo(); - popoverController.create.and.returnValue(Promise.resolve(editReportNamePopoverSpy)); + popoverController.create.and.resolveTo(editReportNamePopoverSpy); component.editReportName(); tick(100); diff --git a/src/app/post-verification/setup-account/setup-account.page.spec.ts b/src/app/post-verification/setup-account/setup-account.page.spec.ts index 71e83a29bc..7f4b8b8fe2 100644 --- a/src/app/post-verification/setup-account/setup-account.page.spec.ts +++ b/src/app/post-verification/setup-account/setup-account.page.spec.ts @@ -96,7 +96,7 @@ describe('SetupAccountPage', () => { networkService.connectivityWatcher.and.returnValue(new EventEmitter()); networkService.isOnline.and.returnValue(of(true)); - authService.getEou.and.returnValue(Promise.resolve(apiEouRes)); + authService.getEou.and.resolveTo(apiEouRes); orgService.getCurrentOrg.and.returnValue(of(orgData1[0])); orgSettingsService.get.and.returnValue(of(orgSettingsRes)); orgService.setCurrencyBasedOnIp.and.returnValue(of(orgData1[0])); @@ -115,14 +115,14 @@ describe('SetupAccountPage', () => { component.setupNetworkWatcher(); component.isConnected$.pipe(take(1)).subscribe((connectionStatus) => { - expect(connectionStatus).toEqual(true); + expect(connectionStatus).toBeTrue(); }); })); it('openCurrenySelectionModal(): should open the currency select modal', fakeAsync(() => { const modalSpy = jasmine.createSpyObj('Modal', ['present', 'onWillDismiss']); - modalController.create.and.returnValue(Promise.resolve(modalSpy)); - modalSpy.onWillDismiss.and.returnValue(Promise.resolve({ data: { currency: { shortCode: 'USD' } } })); + modalController.create.and.resolveTo(modalSpy); + modalSpy.onWillDismiss.and.resolveTo({ data: { currency: { shortCode: 'USD' } } }); component.openCurrenySelectionModal(); fixture.detectChanges(); @@ -136,7 +136,8 @@ describe('SetupAccountPage', () => { it('postUser(): should update the password of the user', fakeAsync(() => { orgUserService.postUser.and.returnValue(of(postUserResponse)); - component.eou$ = of(currentEouRes); + const mockEou = cloneDeep(currentEouRes); + component.eou$ = of(mockEou); component.fg.controls.password.setValue('qwerty@123456'); const updatedEou = { id: 'usvKA4X8Ugcr', @@ -149,7 +150,7 @@ describe('SetupAccountPage', () => { }; component.postUser().subscribe(() => { expect(orgUserService.postUser).toHaveBeenCalledOnceWith(updatedEou); - expect(currentEouRes.us).toEqual(updatedEou); + expect(mockEou.us).toEqual(updatedEou); }); })); @@ -173,20 +174,22 @@ describe('SetupAccountPage', () => { describe('saveGuessedMileage():', () => { it('should set the desired mileage value if the org currency is USD', fakeAsync(() => { - orgSettingsService.get.and.returnValue(of(orgSettingsRes)); + const mockOrgSettings = cloneDeep(orgSettingsRes); + orgSettingsService.get.and.returnValue(of(mockOrgSettings)); component.org$ = of(orgData1[0]); orgSettingsService.post.and.returnValue(of(orgSettingsPostData)); component.saveGuessedMileage().subscribe(() => { - expect(orgSettingsRes.mileage.four_wheeler).toBe(0.58); - expect(orgSettingsRes.mileage.unit).toBe('MILES'); - expect(orgSettingsRes.mileage.enabled).toBe(true); - expect(orgSettingsRes.mileage.two_wheeler).toBe(0.58); + expect(mockOrgSettings.mileage.four_wheeler).toBe(0.58); + expect(mockOrgSettings.mileage.unit).toBe('MILES'); + expect(mockOrgSettings.mileage.enabled).toBeTrue(); + expect(mockOrgSettings.mileage.two_wheeler).toBe(0.58); }); - expect(orgSettingsService.post).toHaveBeenCalledOnceWith(orgSettingsRes); + expect(orgSettingsService.post).toHaveBeenCalledOnceWith(mockOrgSettings); })); it('should set the desired mileage value if the org currency is not USD', fakeAsync(() => { - orgSettingsService.get.and.returnValue(of(orgSettingsRes)); + const mockOrgSettings = cloneDeep(orgSettingsRes); + orgSettingsService.get.and.returnValue(of(mockOrgSettings)); const orgData12 = { ...orgData1[0], currency: 'INR', @@ -195,13 +198,13 @@ describe('SetupAccountPage', () => { orgSettingsService.post.and.returnValue(of(orgSettingsPostData)); component.saveGuessedMileage().subscribe(() => { fixture.detectChanges(); - expect(orgSettingsRes.mileage.four_wheeler).toBe(8.0); - expect(orgSettingsRes.mileage.unit).toBe('KM'); - expect(orgSettingsRes.mileage.enabled).toBe(true); - expect(orgSettingsRes.mileage.two_wheeler).toBe(6.0); + expect(mockOrgSettings.mileage.four_wheeler).toBe(8.0); + expect(mockOrgSettings.mileage.unit).toBe('KM'); + expect(mockOrgSettings.mileage.enabled).toBeTrue(); + expect(mockOrgSettings.mileage.two_wheeler).toBe(6.0); }); tick(500); - expect(orgSettingsService.post).toHaveBeenCalledOnceWith(orgSettingsRes); + expect(orgSettingsService.post).toHaveBeenCalledOnceWith(mockOrgSettings); })); }); @@ -211,8 +214,8 @@ describe('SetupAccountPage', () => { spyOn(component, 'postUser').and.returnValue(of(postUserResponse)); spyOn(component, 'postOrg').and.returnValue(of(orgData1[0])); spyOn(component, 'saveGuessedMileage').and.returnValue(of(orgSettingsRes)); - loaderService.showLoader.and.returnValue(Promise.resolve()); - loaderService.hideLoader.and.returnValue(Promise.resolve()); + loaderService.showLoader.and.resolveTo(); + loaderService.hideLoader.and.resolveTo(); authService.refreshEou.and.returnValue(of(eouRes3)); component.fg.setValue({ companyName: 'Acme Inc.', @@ -223,7 +226,7 @@ describe('SetupAccountPage', () => { fixture.detectChanges(); tick(500); expect(component.fg.markAllAsTouched).toHaveBeenCalledTimes(1); - expect(component.fg.valid).toBe(true); + expect(component.fg.valid).toBeTrue(); expect(loaderService.showLoader).toHaveBeenCalledTimes(1); expect(component.postUser).toHaveBeenCalledTimes(1); expect(component.postOrg).toHaveBeenCalledTimes(1); @@ -244,13 +247,13 @@ describe('SetupAccountPage', () => { }); const toastSpy = jasmine.createSpyObj('HTMLIonToastElement', ['present']); - toastSpy.present.and.returnValue(Promise.resolve()); - toastController.create.and.returnValue(Promise.resolve(toastSpy)); + toastSpy.present.and.resolveTo(); + toastController.create.and.resolveTo(toastSpy); component.saveData(); fixture.detectChanges(); tick(500); expect(component.fg.markAllAsTouched).toHaveBeenCalledTimes(1); - expect(component.fg.valid).toBe(false); + expect(component.fg.valid).toBeFalse(); expect(toastController.create).toHaveBeenCalledOnceWith({ message: 'Please fill all required fields to proceed', color: 'danger', diff --git a/src/app/shared/components/comments-history/view-comment/view-comment.component.spec.ts b/src/app/shared/components/comments-history/view-comment/view-comment.component.spec.ts index 9cff6cc667..50362b72ab 100644 --- a/src/app/shared/components/comments-history/view-comment/view-comment.component.spec.ts +++ b/src/app/shared/components/comments-history/view-comment/view-comment.component.spec.ts @@ -64,7 +64,8 @@ describe('ViewCommentComponent', () => { authService.getEou.and.resolveTo(apiEouRes); const mockCommentResponse = cloneDeep(apiCommentsResponse); statusService.find.and.returnValue(of(mockCommentResponse)); - statusService.createStatusMap.and.returnValue(updateReponseWithFlattenedEStatus); + const mockStatusMap = cloneDeep(updateReponseWithFlattenedEStatus); + statusService.createStatusMap.and.returnValue(mockStatusMap); fixture = TestBed.createComponent(ViewCommentComponent); component = fixture.componentInstance; @@ -72,7 +73,6 @@ describe('ViewCommentComponent', () => { component.objectType = 'transactions'; component.objectId = 'tx1oTNwgRdRq'; component.newComment = 'This is a new comment'; - fixture.detectChanges(); })); it('should create', () => { @@ -84,6 +84,7 @@ describe('ViewCommentComponent', () => { const data = { comment: newComment }; component.newComment = newComment; statusService.post.and.returnValue(of(null)); + fixture.detectChanges(); const focusSpy = spyOn(component.commentInput.nativeElement, 'focus'); component.addComment(); @@ -215,6 +216,7 @@ describe('ViewCommentComponent', () => { st_org_user_id: 'POLICY', })); + spyOn(component, 'setContentScrollToBottom'); const totalCommentsCount = 33; authService.getEou.and.resolveTo(apiEouRes); statusService.find.and.returnValue(of(updatedApiCommentsResponse)); @@ -238,6 +240,7 @@ describe('ViewCommentComponent', () => { })); it('should set type correctly for a given objectType', fakeAsync(() => { + spyOn(component, 'setContentScrollToBottom'); component.objectType = 'Expenses'; component.ngOnInit(); tick(500); diff --git a/src/app/shared/components/comments-history/view-comment/view-comment.component.ts b/src/app/shared/components/comments-history/view-comment/view-comment.component.ts index 7a43d405f2..44d45ba278 100644 --- a/src/app/shared/components/comments-history/view-comment/view-comment.component.ts +++ b/src/app/shared/components/comments-history/view-comment/view-comment.component.ts @@ -60,6 +60,10 @@ export class ViewCommentComponent implements OnInit { public platform: Platform ) {} + setContentScrollToBottom(): void { + this.content.scrollToBottom(500); + } + addComment() { if (this.newComment) { const data = { @@ -170,7 +174,7 @@ export class ViewCommentComponent implements OnInit { map((res) => res.sort((a, b) => a.st_created_at.valueOf() - b.st_created_at.valueOf())), finalize(() => { setTimeout(() => { - this.content.scrollToBottom(500); + this.setContentScrollToBottom(); }, 500); }) ) diff --git a/src/app/shared/components/route-selector/route-selector.component.spec.ts b/src/app/shared/components/route-selector/route-selector.component.spec.ts index 851a46d397..c76bc2f508 100644 --- a/src/app/shared/components/route-selector/route-selector.component.spec.ts +++ b/src/app/shared/components/route-selector/route-selector.component.spec.ts @@ -14,6 +14,7 @@ import { MatIconTestingModule } from '@angular/material/icon/testing'; import { MatIconModule } from '@angular/material/icon'; import { click, getElementBySelector, getTextContent } from 'src/app/core/dom-helpers'; import { By } from '@angular/platform-browser'; +import { cloneDeep } from 'lodash'; describe('RouteSelectorComponent', () => { let component: RouteSelectorComponent; @@ -44,7 +45,8 @@ describe('RouteSelectorComponent', () => { component = fixture.componentInstance; fb = TestBed.inject(FormBuilder) as jasmine.SpyObj; modalController = TestBed.inject(ModalController) as jasmine.SpyObj; - component.mileageConfig = orgSettingsRes.mileage; + const mockOrgSettings = cloneDeep(orgSettingsRes); + component.mileageConfig = mockOrgSettings.mileage; component.formInitialized = true; component.onChangeSub = of(null).subscribe(); component.form = fb.group({ @@ -92,7 +94,7 @@ describe('RouteSelectorComponent', () => { }); expect(component.mileageLocations.length).toEqual(mileageLocationData1.length); expect(component.form.controls.distance.value).toEqual(20.0); - expect(component.form.controls.roundTrip.value).toEqual(true); + expect(component.form.controls.roundTrip.value).toBeTrue(); }); it('writeValue(): should write value to the form group', () => { @@ -261,7 +263,8 @@ describe('RouteSelectorComponent', () => { describe('onTxnFieldsChange():', () => { beforeEach(() => { spyOn(component, 'ngOnChanges'); - component.txnFields = expenseFieldsMapResponse3; + const mockExpenseFieldsMapResponse = cloneDeep(expenseFieldsMapResponse3); + component.txnFields = mockExpenseFieldsMapResponse; }); it('should update form validators', () => { diff --git a/src/app/shared/components/sidemenu/sidemenu-content/sidemenu-content.component.spec.ts b/src/app/shared/components/sidemenu/sidemenu-content/sidemenu-content.component.spec.ts index c92db1adcb..08ff944861 100644 --- a/src/app/shared/components/sidemenu/sidemenu-content/sidemenu-content.component.spec.ts +++ b/src/app/shared/components/sidemenu/sidemenu-content/sidemenu-content.component.spec.ts @@ -14,6 +14,7 @@ import { sidemenuItemData4, } from 'src/app/core/mock-data/sidemenu-item.data'; import { globalCacheBusterNotifier } from 'ts-cacheable'; +import { cloneDeep } from 'lodash'; describe('SidemenuContentComponent', () => { let component: SidemenuContentComponent; @@ -68,23 +69,25 @@ describe('SidemenuContentComponent', () => { describe('goToRoute():', () => { it('should call trackingService.menuItemClicked with correct argument', () => { - component.goToRoute(sidemenuItemData1); + const mockSideMenuItemData = cloneDeep(sidemenuItemData1); + component.goToRoute(mockSideMenuItemData); fixture.detectChanges(); - expect(trackingService.menuItemClicked).toHaveBeenCalledOnceWith({ option: sidemenuItemData1.title }); + expect(trackingService.menuItemClicked).toHaveBeenCalledOnceWith({ option: mockSideMenuItemData.title }); }); it('should toggle isDropdownOpen property when sidemenu item has dropdown options', () => { - component.goToRoute(sidemenuItemData2); + const mockSideMenuItemData = cloneDeep(sidemenuItemData2); + component.goToRoute(mockSideMenuItemData); fixture.detectChanges(); - expect(sidemenuItemData2.isDropdownOpen).toBe(true); // initial click should open dropdown - component.goToRoute(sidemenuItemData2); + expect(mockSideMenuItemData.isDropdownOpen).toBeTrue(); // initial click should open dropdown + component.goToRoute(mockSideMenuItemData); fixture.detectChanges(); - expect(sidemenuItemData2.isDropdownOpen).toBe(false); // second click should close dropdown + expect(mockSideMenuItemData.isDropdownOpen).toBeFalse(); // second click should close dropdown }); it('should close the menucontroller when sidemenu item does not have dropdown options', () => { component.goToRoute(sidemenuItemData1); - expect(sidemenuItemData2.isDropdownOpen).toBe(false); + expect(sidemenuItemData2.isDropdownOpen).toBeFalse(); expect(menuController.close).toHaveBeenCalledTimes(1); }); diff --git a/src/app/shared/components/virtual-select/virtual-select-modal/virtual-select-modal.component.spec.ts b/src/app/shared/components/virtual-select/virtual-select-modal/virtual-select-modal.component.spec.ts index a529b49459..d5f808a238 100644 --- a/src/app/shared/components/virtual-select/virtual-select-modal/virtual-select-modal.component.spec.ts +++ b/src/app/shared/components/virtual-select/virtual-select-modal/virtual-select-modal.component.spec.ts @@ -197,7 +197,7 @@ describe('VirtualSelectModalComponent', () => { it('onElementSelect(): should call recentlocalstorage service and dismiss the modal', () => { component.cacheName = 'cache1'; - const option = virtualSelectOptionData4[1]; + const option = cloneDeep(virtualSelectOptionData4[1]); component.onElementSelect(option); expect(recentLocalStorageItemsService.post).toHaveBeenCalledOnceWith('cache1', option, 'label'); expect(modalController.dismiss).toHaveBeenCalledOnceWith(option);