From 154f318445f9a44d6e03ca4a5b090d849ad1734f Mon Sep 17 00:00:00 2001 From: KJ21-ENG <140263938+KJ21-ENG@users.noreply.github.com> Date: Tue, 11 Aug 2026 01:38:46 +0530 Subject: [PATCH] Resolve cleanup conflicts on current main --- tests/actions/IOU/PerDiemTest.ts | 41 ++++++------ tests/actions/IOUTest/PayMoneyRequestTest.ts | 17 ++--- tests/actions/MergeTransactionTest.ts | 49 +++++--------- tests/actions/connections/NetSuite.ts | 63 +++++++++++++----- tests/ui/ParentNavigationSubtitleTest.tsx | 13 ++-- tests/unit/Search/SearchQueryUtilsTest.ts | 26 ++++---- tests/unit/TransactionPreviewUtils.test.ts | 35 +++++----- tests/unit/TryNewDotUtilsTest.ts | 35 ++++++---- tests/unit/WorkflowUtilsTest.ts | 41 ++++++------ tests/unit/submitDismissStrategiesTest.ts | 68 +++++++++++++++----- 10 files changed, 227 insertions(+), 161 deletions(-) diff --git a/tests/actions/IOU/PerDiemTest.ts b/tests/actions/IOU/PerDiemTest.ts index da386e2fe0fb..a7616744cd57 100644 --- a/tests/actions/IOU/PerDiemTest.ts +++ b/tests/actions/IOU/PerDiemTest.ts @@ -29,6 +29,7 @@ import createRandomPolicy from '../../utils/collections/policies'; import createRandomPolicyCategories from '../../utils/collections/policyCategory'; import createRandomPolicyTags from '../../utils/collections/policyTags'; import createRandomTransaction from '../../utils/collections/transaction'; +import createMock from '../../utils/createMock'; import getOnyxValue from '../../utils/getOnyxValue'; import {formatPhoneNumber, getCurrencyDecimalsLocal, getGlobalFetchMock} from '../../utils/TestHelper'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; @@ -321,10 +322,10 @@ describe('PerDiem', () => { accountID: 123, login: 'payee@example.com', }, - }; + } satisfies RequestMoneyParticipantParams; - const parentChatReport = {} as OnyxEntry; - const participantParams = mockParticipantParams as unknown as RequestMoneyParticipantParams; + const parentChatReport = createMock>({}); + const participantParams = mockParticipantParams; const earlyPolicyID = getPerDiemExpensePolicyID({ report: parentChatReport, @@ -429,7 +430,7 @@ describe('PerDiem', () => { }; // When: Call getPerDiemExpenseInformation - const parentChatReport = {} as OnyxEntry; + const parentChatReport = createMock>({}); const earlyPolicyID = getPerDiemExpensePolicyID({ report: parentChatReport, @@ -632,7 +633,7 @@ describe('PerDiem', () => { role: CONST.REPORT.ROLE.MEMBER, }; - const mockTransactionParams = { + const mockTransactionParams = createMock({ comment: 'Conference per diem', currency: 'USD', created: '2024-01-20', @@ -642,17 +643,17 @@ describe('PerDiem', () => { billable: false, attendees: [], reimbursable: true, - }; + }); - const mockParticipantParams = { + const mockParticipantParams = createMock({ payeeAccountID: 456, payeeEmail: 'payee@example.com', participant: mockParticipant, - }; + }); // When: Call getPerDiemExpenseInformation with existing chat report - const parentChatReport = existingChatReport as OnyxEntry; - const participantParams = mockParticipantParams as RequestMoneyParticipantParams; + const parentChatReport = createMock>(existingChatReport); + const participantParams = mockParticipantParams; const earlyPolicyID = getPerDiemExpensePolicyID({ report: parentChatReport, @@ -667,7 +668,7 @@ describe('PerDiem', () => { const result = getPerDiemExpenseInformation({ parentChatReport, getCurrencyDecimals: getCurrencyDecimalsLocal, - transactionParams: mockTransactionParams as PerDiemExpenseTransactionParams, + transactionParams: mockTransactionParams, participantParams, recentlyUsedParams: {}, policyTags, @@ -733,7 +734,7 @@ describe('PerDiem', () => { quantity: 1, }; - const mockTransactionParams = { + const mockTransactionParams = createMock({ comment: 'Policy per diem', currency: 'USD', created: '2024-01-25', @@ -743,21 +744,21 @@ describe('PerDiem', () => { billable: true, attendees: [], reimbursable: true, - }; + }); - const mockParticipantParams = { + const mockParticipantParams = createMock({ payeeAccountID: 456, payeeEmail: 'payee@example.com', participant: mockParticipant, - }; + }); const mockPolicyParams = { policy: createRandomPolicy(2), }; // When: Call getPerDiemExpenseInformation for policy expense chat - const parentChatReport = {} as OnyxEntry; - const participantParams = mockParticipantParams as RequestMoneyParticipantParams; + const parentChatReport = createMock>({}); + const participantParams = mockParticipantParams; const earlyPolicyID = getPerDiemExpensePolicyID({ report: parentChatReport, @@ -772,7 +773,7 @@ describe('PerDiem', () => { const result = getPerDiemExpenseInformation({ parentChatReport, getCurrencyDecimals: getCurrencyDecimalsLocal, - transactionParams: mockTransactionParams as PerDiemExpenseTransactionParams, + transactionParams: mockTransactionParams, participantParams, policyParams: mockPolicyParams, recentlyUsedParams: {}, @@ -1022,7 +1023,7 @@ describe('PerDiem', () => { }; // When calling getPerDiemExpenseInformation with personalDetails - const parentChatReport = {} as OnyxEntry; + const parentChatReport = createMock>({}); const participantParams = { payeeAccountID: RORY_ACCOUNT_ID, payeeEmail: RORY_EMAIL, @@ -1030,7 +1031,7 @@ describe('PerDiem', () => { accountID: RORY_ACCOUNT_ID, login: RORY_EMAIL, }, - } as unknown as RequestMoneyParticipantParams; + } satisfies RequestMoneyParticipantParams; const earlyPolicyID = getPerDiemExpensePolicyID({ report: parentChatReport, diff --git a/tests/actions/IOUTest/PayMoneyRequestTest.ts b/tests/actions/IOUTest/PayMoneyRequestTest.ts index a030fa24ef8f..6e04a77abb7d 100644 --- a/tests/actions/IOUTest/PayMoneyRequestTest.ts +++ b/tests/actions/IOUTest/PayMoneyRequestTest.ts @@ -34,8 +34,9 @@ import createRandomPolicy from '../../utils/collections/policies'; import createRandomReportAction from '../../utils/collections/reportActions'; import {createRandomReport} from '../../utils/collections/reports'; import createRandomTransaction from '../../utils/collections/transaction'; +import createMock from '../../utils/createMock'; import getOnyxValue from '../../utils/getOnyxValue'; -import {getCurrencyDecimalsLocal, getGlobalFetchMock, getOnyxData, translateLocal} from '../../utils/TestHelper'; +import {createGlobalFetchMock, getCurrencyDecimalsLocal, getOnyxData, translateLocal} from '../../utils/TestHelper'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; const topMostReportID = '23423423'; @@ -118,8 +119,8 @@ describe('actions/IOU/PayMoneyRequest', () => { let mockFetch: MockFetch; beforeEach(() => { jest.clearAllTimers(); - global.fetch = getGlobalFetchMock(); - mockFetch = fetch as MockFetch; + mockFetch = createGlobalFetchMock(); + global.fetch = mockFetch; return Onyx.clear().then(waitForBatchedUpdates); }); @@ -1226,7 +1227,7 @@ describe('actions/IOU/PayMoneyRequest', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, chatReport); await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`, iouReport); - (Navigation.navigate as jest.Mock).mockClear(); + jest.mocked(Navigation.navigate).mockClear(); payMoneyRequest({ conciergeChat: undefined, @@ -1296,7 +1297,7 @@ describe('actions/IOU/PayMoneyRequest', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, chatReport); await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`, iouReport); - (Navigation.navigate as jest.Mock).mockClear(); + jest.mocked(Navigation.navigate).mockClear(); payMoneyRequest({ conciergeChat: undefined, @@ -1356,7 +1357,7 @@ describe('actions/IOU/PayMoneyRequest', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, chatReport); await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`, iouReport); - (Navigation.navigate as jest.Mock).mockClear(); + jest.mocked(Navigation.navigate).mockClear(); payMoneyRequest({ conciergeChat: undefined, @@ -1554,7 +1555,7 @@ describe('actions/IOU/PayMoneyRequest', () => { .then(() => { if (chatReport && expenseReport) { // And when the payment is cancelled - cancelPayment(expenseReport, chatReport, {} as Policy, true, CARLOS_ACCOUNT_ID, CARLOS_EMAIL, true, false); + cancelPayment(expenseReport, chatReport, createMock({}), true, CARLOS_ACCOUNT_ID, CARLOS_EMAIL, true, false); } return waitForBatchedUpdates(); }) @@ -1659,7 +1660,7 @@ describe('actions/IOU/PayMoneyRequest', () => { if (chatReport && expenseReport) { mockFetch?.pause?.(); // And when the payment is cancelled - cancelPayment(expenseReport, chatReport, {} as Policy, true, CARLOS_ACCOUNT_ID, CARLOS_EMAIL, true, false); + cancelPayment(expenseReport, chatReport, createMock({}), true, CARLOS_ACCOUNT_ID, CARLOS_EMAIL, true, false); } await waitForBatchedUpdates(); diff --git a/tests/actions/MergeTransactionTest.ts b/tests/actions/MergeTransactionTest.ts index adbdada939f9..d4607f1d4543 100644 --- a/tests/actions/MergeTransactionTest.ts +++ b/tests/actions/MergeTransactionTest.ts @@ -1,9 +1,10 @@ import {getReportPreviewAction} from '@libs/actions/IOU/MoneyRequestBuilder'; import {areTransactionsEligibleForMerge, getTransactionsForMerging, mergeTransactionRequest, setMergeTransactionKey, setupMergeTransactionData} from '@libs/actions/MergeTransaction'; import {addComment, openReport} from '@libs/actions/Report'; +import * as API from '@libs/API'; import {WRITE_COMMANDS} from '@libs/API/types'; import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; -import {getOriginalMessage, getReportAction} from '@libs/ReportActionsUtils'; +import {getOriginalMessage, getReportAction, isActionOfType} from '@libs/ReportActionsUtils'; import {buildTransactionThread} from '@libs/ReportUtils'; import CONST from '@src/CONST'; @@ -227,8 +228,8 @@ describe('mergeTransactionRequest', () => { }); beforeEach(() => { - global.fetch = TestHelper.getGlobalFetchMock(); - mockFetch = fetch as MockFetch; + mockFetch = TestHelper.createGlobalFetchMock(); + global.fetch = mockFetch; return Onyx.clear().then(waitForBatchedUpdates); }); @@ -520,9 +521,7 @@ describe('mergeTransactionRequest', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, sourceTransaction); await Onyx.set(`${ONYXKEYS.COLLECTION.MERGE_TRANSACTION}${mergeTransactionID}`, mergeTransaction); - type ApiModule = {write: (...args: unknown[]) => unknown}; - const getApiModule = (): ApiModule => jest.requireActual('@libs/API'); - const writeSpy = jest.spyOn(getApiModule(), 'write'); + const writeSpy = jest.spyOn(API, 'write'); mockFetch?.pause?.(); @@ -557,21 +556,7 @@ describe('mergeTransactionRequest', () => { expect(writeSpy).toHaveBeenCalled(); const [firstCall] = writeSpy.mock.calls; const [calledCommand, rawParams] = firstCall; - const calledParams = rawParams as { - transactionID: string; - transactionIDList: string[]; - created: string; - merchant: string; - amount: number; - currency: string; - category: string; - billable?: boolean; - reimbursable?: boolean; - tag?: string; - receiptID?: string; - reportID: string; - comment: string; - }; + const calledParams = rawParams; expect(calledCommand).toBe(WRITE_COMMANDS.MERGE_TRANSACTION); expect(calledParams).toEqual( @@ -886,19 +871,17 @@ describe('mergeTransactionRequest', () => { // The source IOU action is no longer removed — only the target report's IOU action is handled in the cross-report branch expect(sourceReportActions?.[sourceIOUActionID]).toBeDefined(); - const newIOUAction = Object.values(sourceReportActions ?? {}).find((action) => { - const reportAction = action as OnyxEntry; - const originalMessage = getOriginalMessage(reportAction) as OriginalMessageIOU | undefined; - return ( - reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && - originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.CREATE && - originalMessage?.IOUTransactionID === targetTransaction.transactionID - ); - }) as OnyxEntry; + const newIOUAction = Object.values(sourceReportActions ?? {}).find((action): action is ReportAction => { + if (!isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.IOU)) { + return false; + } + const originalMessage = getOriginalMessage(action); + return originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.CREATE && originalMessage?.IOUTransactionID === targetTransaction.transactionID; + }); // Verify the new IOU action is created and points to the merged transaction expect(newIOUAction).toBeTruthy(); - expect((getOriginalMessage(newIOUAction) as OriginalMessageIOU | undefined)?.IOUTransactionID).toBe(targetTransaction.transactionID); + expect(getOriginalMessage(newIOUAction)?.IOUTransactionID).toBe(targetTransaction.transactionID); const updatedTargetTransactionThread = await new Promise((resolve) => { const connection = Onyx.connect({ @@ -1261,7 +1244,7 @@ describe('mergeTransactionRequest', () => { await waitForBatchedUpdates(); // Then we expect the reportPreview to update with new childVisibleActionCount - previewAction = getReportPreviewAction(chatReport.reportID, sourceReport.reportID) as OnyxEntry; + previewAction = getReportPreviewAction(chatReport.reportID, sourceReport.reportID) ?? undefined; expect(previewAction).toBeTruthy(); expect(previewAction?.childVisibleActionCount).toEqual(0); expect(previewAction?.childCommenterCount).toEqual(0); @@ -1283,7 +1266,7 @@ describe('mergeTransactionRequest', () => { await waitForBatchedUpdates(); // Then we expect the reportPreview to update with new childVisibleActionCount - previewAction = getReportPreviewAction(chatReport.reportID, sourceReport.reportID) as OnyxEntry; + previewAction = getReportPreviewAction(chatReport.reportID, sourceReport.reportID) ?? undefined; expect(previewAction).toBeTruthy(); expect(previewAction?.childVisibleActionCount).toEqual(0); expect(previewAction?.childCommenterCount).toEqual(0); diff --git a/tests/actions/connections/NetSuite.ts b/tests/actions/connections/NetSuite.ts index 4e5e31a32b36..8b9324685532 100644 --- a/tests/actions/connections/NetSuite.ts +++ b/tests/actions/connections/NetSuite.ts @@ -19,6 +19,7 @@ import type {OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; +import createMock from '../../utils/createMock'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; jest.mock('@libs/API'); @@ -42,7 +43,7 @@ function getFirstWriteCall(): {command: WriteCommand; onyxData?: AnyOnyxData} { } function createPolicy(options: {isAuthError?: boolean; verified?: boolean}): OnyxEntry { - return { + return createMock({ id: MOCK_POLICY_ID, connections: { netsuite: { @@ -52,7 +53,7 @@ function createPolicy(options: {isAuthError?: boolean; verified?: boolean}): Ony }, }, }, - } as unknown as Policy; + }); } describe('actions/connections/NetSuite', () => { @@ -194,9 +195,7 @@ describe('actions/connections/NetSuite', () => { const call = writeSpy.mock.calls.at(0); - const params = call?.[1] as {bankAccountID: string; policyID: string}; - expect(params.policyID).toBe(MOCK_POLICY_ID); - expect(params.bankAccountID).toBe('account-123'); + expect(call?.[1]).toEqual(expect.objectContaining({bankAccountID: 'account-123', policyID: MOCK_POLICY_ID})); }); it('merges travelInvoicingPayableAccountID optimistically onto the NetSuite options config', () => { @@ -206,8 +205,19 @@ describe('actions/connections/NetSuite', () => { const optimisticUpdate = onyxData?.optimisticData?.at(0); expect(optimisticUpdate?.key).toBe(`${ONYXKEYS.COLLECTION.POLICY}${MOCK_POLICY_ID}`); - const value = optimisticUpdate?.value as {connections: {netsuite: {options: {config: Record}}}}; - expect(value.connections.netsuite.options.config[CONST.NETSUITE_CONFIG.TRAVEL_INVOICING_PAYABLE_ACCOUNT]).toBe('account-123'); + expect(optimisticUpdate?.value).toEqual( + expect.objectContaining({ + connections: expect.objectContaining({ + netsuite: expect.objectContaining({ + options: expect.objectContaining({ + config: expect.objectContaining({ + [CONST.NETSUITE_CONFIG.TRAVEL_INVOICING_PAYABLE_ACCOUNT]: 'account-123', + }), + }), + }), + }), + }), + ); }); }); @@ -223,9 +233,12 @@ describe('actions/connections/NetSuite', () => { expect(command).toBe(WRITE_COMMANDS.UPDATE_NETSUITE_TRAVEL_INVOICING_JOURNAL_POSTING_PREFERENCE); const call = writeSpy.mock.calls.at(0); - const params = call?.[1] as {value: string; policyID: string}; - expect(params.policyID).toBe(MOCK_POLICY_ID); - expect(params.value).toBe(CONST.NETSUITE_JOURNAL_POSTING_PREFERENCE.JOURNALS_POSTING_INDIVIDUAL_LINE); + expect(call?.[1]).toEqual( + expect.objectContaining({ + policyID: MOCK_POLICY_ID, + value: CONST.NETSUITE_JOURNAL_POSTING_PREFERENCE.JOURNALS_POSTING_INDIVIDUAL_LINE, + }), + ); }); it('merges travelInvoicingJournalPostingPreference optimistically onto the NetSuite options config', () => { @@ -239,9 +252,18 @@ describe('actions/connections/NetSuite', () => { const optimisticUpdate = onyxData?.optimisticData?.at(0); expect(optimisticUpdate?.key).toBe(`${ONYXKEYS.COLLECTION.POLICY}${MOCK_POLICY_ID}`); - const value = optimisticUpdate?.value as {connections: {netsuite: {options: {config: Record}}}}; - expect(value.connections.netsuite.options.config[CONST.NETSUITE_CONFIG.TRAVEL_INVOICING_JOURNAL_POSTING_PREFERENCE]).toBe( - CONST.NETSUITE_JOURNAL_POSTING_PREFERENCE.JOURNALS_POSTING_INDIVIDUAL_LINE, + expect(optimisticUpdate?.value).toEqual( + expect.objectContaining({ + connections: expect.objectContaining({ + netsuite: expect.objectContaining({ + options: expect.objectContaining({ + config: expect.objectContaining({ + [CONST.NETSUITE_CONFIG.TRAVEL_INVOICING_JOURNAL_POSTING_PREFERENCE]: CONST.NETSUITE_JOURNAL_POSTING_PREFERENCE.JOURNALS_POSTING_INDIVIDUAL_LINE, + }), + }), + }), + }), + }), ); }); @@ -254,9 +276,18 @@ describe('actions/connections/NetSuite', () => { const {onyxData} = getFirstWriteCall(); const failureUpdate = onyxData?.failureData?.at(0); - const value = failureUpdate?.value as {connections: {netsuite: {options: {config: Record}}}}; - expect(value.connections.netsuite.options.config[CONST.NETSUITE_CONFIG.TRAVEL_INVOICING_JOURNAL_POSTING_PREFERENCE]).toBe( - CONST.NETSUITE_JOURNAL_POSTING_PREFERENCE.JOURNALS_POSTING_TOTAL_LINE, + expect(failureUpdate?.value).toEqual( + expect.objectContaining({ + connections: expect.objectContaining({ + netsuite: expect.objectContaining({ + options: expect.objectContaining({ + config: expect.objectContaining({ + [CONST.NETSUITE_CONFIG.TRAVEL_INVOICING_JOURNAL_POSTING_PREFERENCE]: CONST.NETSUITE_JOURNAL_POSTING_PREFERENCE.JOURNALS_POSTING_TOTAL_LINE, + }), + }), + }), + }), + }), ); }); }); diff --git a/tests/ui/ParentNavigationSubtitleTest.tsx b/tests/ui/ParentNavigationSubtitleTest.tsx index 6b4d957a8232..9c7fbff7370e 100644 --- a/tests/ui/ParentNavigationSubtitleTest.tsx +++ b/tests/ui/ParentNavigationSubtitleTest.tsx @@ -10,6 +10,7 @@ import React from 'react'; import ParentNavigationSubtitle from '../../src/components/ParentNavigationSubtitle'; import NAVIGATORS from '../../src/NAVIGATORS'; import SCREENS from '../../src/SCREENS'; +import createMock from '../utils/createMock'; jest.mock('@libs/Navigation/Navigation', () => ({ __esModule: true, @@ -101,7 +102,7 @@ describe('ParentNavigationSubtitle', () => { const reportName = 'Report Name'; const workspaceName = 'Workspace Name'; Navigation.getTopmostReportId = jest.fn(() => parentReportID); - mockUseRoute.mockReturnValue({name: 'SearchReport'} as AnyRoute); + mockUseRoute.mockReturnValue(createMock({name: 'SearchReport'})); mockUseRootNavigationState.mockImplementation((selector?: (state: unknown) => unknown) => { const mockRoute = {name: 'ReportsSplitNavigator'}; if (selector) { @@ -136,7 +137,7 @@ describe('ParentNavigationSubtitle', () => { const reportName = 'Report Name'; const workspaceName = 'Workspace Name'; Navigation.getTopmostReportId = jest.fn(() => parentReportID); - mockUseRoute.mockReturnValue({name: 'SearchReport'} as AnyRoute); + mockUseRoute.mockReturnValue(createMock({name: 'SearchReport'})); mockUseRootNavigationState.mockImplementation((selector?: (state: unknown) => unknown) => { const mockRoute = {name: 'SettingsSplitNavigator'}; if (selector) { @@ -167,7 +168,7 @@ describe('ParentNavigationSubtitle', () => { const reportName = 'Report Name'; const workspaceName = 'Workspace Name'; Navigation.getTopmostReportId = jest.fn(() => '999'); - mockUseRoute.mockReturnValue({name: 'SearchReport'} as AnyRoute); + mockUseRoute.mockReturnValue(createMock({name: 'SearchReport'})); mockUseRootNavigationState.mockImplementation((selector?: (state: unknown) => unknown) => { const mockRoute = {name: 'ReportsSplitNavigator'}; if (selector) { @@ -202,7 +203,7 @@ describe('ParentNavigationSubtitle', () => { const reportName = 'Parent chat'; const workspaceName = 'Workspace'; - mockUseRoute.mockReturnValue({name: SCREENS.REPORT} as AnyRoute); + mockUseRoute.mockReturnValue(createMock({name: SCREENS.REPORT})); mockUseRootNavigationState.mockImplementation((selector?: (state: unknown) => unknown) => { const mockState = getMockRootStateWithReportsSplitStack(parentReportID, expenseReportID); if (selector) { @@ -239,7 +240,7 @@ describe('ParentNavigationSubtitle', () => { jest.mocked(isReportActionVisible).mockReturnValue(true); - mockUseRoute.mockReturnValue({name: SCREENS.REPORT} as AnyRoute); + mockUseRoute.mockReturnValue(createMock({name: SCREENS.REPORT})); mockUseRootNavigationState.mockImplementation((selector?: (state: unknown) => unknown) => { const mockState = getMockRootStateWithReportsSplitStack(parentReportID, expenseReportID); if (selector) { @@ -274,7 +275,7 @@ describe('ParentNavigationSubtitle', () => { const reportName = 'Parent chat'; const workspaceName = 'Workspace'; - mockUseRoute.mockReturnValue({name: SCREENS.REPORT} as AnyRoute); + mockUseRoute.mockReturnValue(createMock({name: SCREENS.REPORT})); mockUseRootNavigationState.mockImplementation((selector?: (state: unknown) => unknown) => { const mockState = getMockRootStateWithReportsSplitStack('other-report', expenseReportID); if (selector) { diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index fcf960cfa13b..27cc69d75e71 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -987,9 +987,9 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); const policies: OnyxCollection = { - [`${ONYXKEYS.COLLECTION.POLICY}123`]: { + [`${ONYXKEYS.COLLECTION.POLICY}123`]: createMock({ name: 'Team Space', - } as OnyxTypes.Policy, + }), }; if (!queryJSON) { @@ -1559,7 +1559,7 @@ describe('SearchQueryUtils', () => { const queryJSON = buildSearchQueryJSON(queryString); const policyCategories = {}; - const policyTags = { + const policyTags = createMock>({ [`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`]: { Department: { name: 'Department', @@ -1570,7 +1570,7 @@ describe('SearchQueryUtils', () => { }, }, }, - } as unknown as OnyxCollection; + }); const currencyList = {}; const personalDetails = {}; const cardList = {}; @@ -1593,7 +1593,7 @@ describe('SearchQueryUtils', () => { const policyCategories = {}; const policyTags = {}; - const currencyList = {USD: {}, EUR: {}, GBP: {}} as unknown as OnyxTypes.CurrencyList; + const currencyList = createMock({USD: {}, EUR: {}, GBP: {}}); const personalDetails = {}; const cardList = {}; const reports = {}; @@ -2789,9 +2789,9 @@ describe('SearchQueryUtils', () => { it('should handle policyID filter by looking up policy name', () => { const policies: OnyxCollection = { - [`${ONYXKEYS.COLLECTION.POLICY}abc123`]: { + [`${ONYXKEYS.COLLECTION.POLICY}abc123`]: createMock({ name: 'My Workspace', - } as OnyxTypes.Policy, + }), }; const result = getFilterDisplayValue({ @@ -2827,13 +2827,13 @@ describe('SearchQueryUtils', () => { it('should format bankAccount filter as " xx" using bankAccountList', () => { const bankAccountList: OnyxTypes.BankAccountList = { - 42: { + 42: createMock({ accountData: { bankAccountID: 42, accountNumber: '123456789012', additionalData: {bankName: CONST.BANK_NAMES.CHASE}, }, - } as OnyxTypes.BankAccountList[string], + }), }; const result = getFilterDisplayValue({ @@ -3041,11 +3041,11 @@ describe('SearchQueryUtils', () => { it('should resolve a regular Expensify Card feed filter to its label', () => { const cardList: OnyxTypes.CardList = { - '111': { + '111': createMock({ cardID: 111, bank: CONST.EXPENSIFY_CARD.BANK, fundID: '12345', - } as OnyxTypes.Card, + }), }; const queryFilter = [{operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, value: `12345_${CONST.EXPENSIFY_CARD.BANK}`}]; @@ -3069,12 +3069,12 @@ describe('SearchQueryUtils', () => { it('should resolve a Travel Invoicing feed filter (3-segment key) to the translated label', () => { const cardList: OnyxTypes.CardList = { - '222': { + '222': createMock({ cardID: 222, bank: CONST.EXPENSIFY_CARD.BANK, fundID: '12345', nameValuePairs: {feedCountry: CONST.TRAVEL.PROGRAM_TRAVEL_US}, - } as OnyxTypes.Card, + }), }; const queryFilter = [{operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, value: `12345_${CONST.EXPENSIFY_CARD.BANK}_${CONST.TRAVEL.PROGRAM_TRAVEL_US}`}]; diff --git a/tests/unit/TransactionPreviewUtils.test.ts b/tests/unit/TransactionPreviewUtils.test.ts index b80f1d1f3fac..ab7c8268a594 100644 --- a/tests/unit/TransactionPreviewUtils.test.ts +++ b/tests/unit/TransactionPreviewUtils.test.ts @@ -18,6 +18,7 @@ import type {ReportActions, Transaction} from '@src/types/onyx'; import Onyx from 'react-native-onyx'; import createRandomPolicy from '../utils/collections/policies'; +import createMock from '../utils/createMock'; import {convertToDisplayString, getCurrencyDecimalsLocal} from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -133,16 +134,17 @@ describe('TransactionPreviewUtils', () => { }); it('returns missing amount message when amount is missing but merchant is present (expense report with field errors)', () => { - const functionArgs = { + const functionArgs: Parameters[0] = { ...basicProps, iouReport: {...basicProps.iouReport, type: CONST.REPORT.TYPE.IOU}, transaction: { ...basicProps.transaction, + // @ts-expect-error - This scenario deliberately passes a transaction without an amount to exercise the missing-amount branch. amount: undefined, modifiedAmount: undefined, merchant: 'Valid Merchant', created: '2024-01-01', - } as unknown as Transaction, + }, violations: [], originalTransaction: undefined, shouldShowRBR: true, @@ -212,7 +214,7 @@ describe('TransactionPreviewUtils', () => { transactionDetails: {amount: modifiedAmount / 2, currency}, transaction: {...basicProps.transaction, amount: modifiedAmount / 2, currency, comment: {originalTransactionID, source: CONST.IOU.TYPE.SPLIT}}, isBillSplit: true, - originalTransaction: { + originalTransaction: createMock({ reportID: CONST.REPORT.SPLIT_REPORT_ID, transactionID: originalTransactionID, comment: { @@ -224,7 +226,7 @@ describe('TransactionPreviewUtils', () => { modifiedAmount, amount: 0, currency, - } as Transaction, + }), }; const result = getTransactionPreviewTextAndTranslationPaths(functionArgs); expect(result.displayAmountText.text).toEqual(convertAmountToDisplayString(modifiedAmount, currency)); @@ -800,35 +802,38 @@ describe('TransactionPreviewUtils', () => { }); test('returns unique error messages from report actions', () => { - const actions = { + const actions = createMock({ /* eslint-disable @typescript-eslint/naming-convention */ 1: {errors: {a: 'Error A', b: 'Error B'}}, 2: {errors: {c: 'Error C', a: 'Error A2'}}, 3: {errors: {a: 'Error A', d: 'Error D'}}, /* eslint-enable @typescript-eslint/naming-convention */ - } as unknown as ReportActions; + }); const expectedErrors = ['Error B', 'Error C', 'Error D']; expect(getUniqueActionErrorsForTransaction(actions, undefined).sort()).toEqual(expectedErrors.sort()); }); test('returns the latest error message if multiple errors exist under a single action', () => { - const actions = { + const actions = createMock({ /* eslint-disable @typescript-eslint/naming-convention */ 1: {errors: {z: 'Error Z2', a: 'Error A', f: 'Error Z'}}, /* eslint-enable @typescript-eslint/naming-convention */ - } as unknown as ReportActions; + }); expect(getUniqueActionErrorsForTransaction(actions, undefined)).toEqual(['Error Z2']); }); test('filters out non-string error messages', () => { - const actions = { + const actions = createMock({ /* eslint-disable @typescript-eslint/naming-convention */ - 1: {errors: {a: 404, b: 'Error B'}}, + 1: { + // @ts-expect-error - This deliberately malformed error value tests filtering non-string messages. + errors: {a: 404, b: 'Error B'}, + }, 2: {errors: {c: null, d: 'Error D'}}, /* eslint-enable @typescript-eslint/naming-convention */ - } as unknown as ReportActions; + }); expect(getUniqueActionErrorsForTransaction(actions, undefined)).toEqual(['Error B', 'Error D']); }); @@ -956,7 +961,7 @@ describe('TransactionPreviewUtils', () => { }); it('should return true when there are report action errors for the transaction', () => { - const reportActionsWithErrors = { + const reportActionsWithErrors = createMock({ action1: { reportActionID: 'action1', actionName: CONST.REPORT.ACTIONS.TYPE.IOU, @@ -966,7 +971,7 @@ describe('TransactionPreviewUtils', () => { message: [], pendingAction: null, }, - } as unknown as ReportActions; + }); expect(transactionHasRBR(basicProps.transaction, [], rbrEmail, rbrAccountID, rbrReport, undefined, rbrPolicy, reportActionsWithErrors)).toBe(true); }); @@ -975,7 +980,7 @@ describe('TransactionPreviewUtils', () => { ...createRandomPolicy(1), approvalMode: CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL, }; - const dewReportActions = { + const dewReportActions = createMock({ action1: { reportActionID: 'action1', actionName: CONST.REPORT.ACTIONS.TYPE.DEW_SUBMIT_FAILED, @@ -984,7 +989,7 @@ describe('TransactionPreviewUtils', () => { originalMessage: {message: 'Failed to submit'}, pendingAction: null, }, - } as unknown as ReportActions; + }); expect(transactionHasRBR(basicProps.transaction, [], rbrEmail, rbrAccountID, rbrReport, undefined, dewPolicy, dewReportActions)).toBe(true); }); diff --git a/tests/unit/TryNewDotUtilsTest.ts b/tests/unit/TryNewDotUtilsTest.ts index f9e490693b61..c2f8038b43ed 100644 --- a/tests/unit/TryNewDotUtilsTest.ts +++ b/tests/unit/TryNewDotUtilsTest.ts @@ -5,6 +5,7 @@ import type {TryNewDot} from '@src/types/onyx'; import {subDays} from 'date-fns'; import Onyx from 'react-native-onyx'; +import createMock from '../utils/createMock'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; Onyx.init({keys: ONYXKEYS}); @@ -29,12 +30,12 @@ describe('TryNewDotUtils', () => { }); it('keeps mobile-locked HybridApp users in NewApp', () => { - const tryNewDot = { + const tryNewDot = createMock({ isLockedToNewApp: true, classicRedirect: { dismissed: true, }, - } as TryNewDot; + }); expect(shouldUseOldApp(tryNewDot)).toBe(false); }); @@ -71,66 +72,72 @@ describe('TryNewDotUtils', () => { }); it('blocks the OldDot redirect when the classicRedirect nudge has gone stale', () => { - const tryNewDot = { + const tryNewDot: Parameters[0] = { classicRedirect: { dismissed: false, + // @ts-expect-error - NVP data is serialized with a string timestamp. timestamp: subDays(new Date(), 31).toISOString(), }, - } as unknown as TryNewDot; + }; expect(isOldAppRedirectBlocked(tryNewDot, false)).toBe(true); }); it('still shows the OldDot redirect when the classicRedirect nudge is fresh', () => { - const tryNewDot = { + const tryNewDot: Parameters[0] = { classicRedirect: { dismissed: false, + // @ts-expect-error - NVP data is serialized with a string timestamp. timestamp: subDays(new Date(), 5).toISOString(), }, - } as unknown as TryNewDot; + }; expect(isOldAppRedirectBlocked(tryNewDot, false)).toBe(false); }); it('reports that a user has been in NewDot 30 days when the nudge is over a month old and not dismissed', () => { - const tryNewDot = { + const tryNewDot: Parameters[0] = { classicRedirect: { dismissed: false, + // @ts-expect-error - NVP data is serialized with a string timestamp. timestamp: subDays(new Date(), 31).toISOString(), }, - } as unknown as TryNewDot; + }; expect(hasBeenInNewDot30Days(tryNewDot)).toBe(true); }); it('does not report 30 days in NewDot when the nudge is less than a month old', () => { - const tryNewDot = { + const tryNewDot: Parameters[0] = { classicRedirect: { dismissed: false, + // @ts-expect-error - NVP data is serialized with a string timestamp. timestamp: subDays(new Date(), 10).toISOString(), }, - } as unknown as TryNewDot; + }; expect(hasBeenInNewDot30Days(tryNewDot)).toBe(false); }); it('does not report 30 days in NewDot once the user has dismissed the nudge', () => { - const tryNewDot = { + const tryNewDot: Parameters[0] = { classicRedirect: { dismissed: true, + // @ts-expect-error - NVP data is serialized with a string timestamp. timestamp: subDays(new Date(), 60).toISOString(), }, - } as unknown as TryNewDot; + }; expect(hasBeenInNewDot30Days(tryNewDot)).toBe(false); }); it('does not report 30 days in NewDot when no timestamp is set', () => { - const tryNewDot = { + const tryNewDot: Parameters[0] = { + // @ts-expect-error - NVP data is serialized without newer required fields. classicRedirect: { dismissed: false, }, - } as unknown as TryNewDot; + }; expect(hasBeenInNewDot30Days(tryNewDot)).toBe(false); }); diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 65808c7e919f..424f3e2f84ae 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -21,6 +21,7 @@ import type {PolicyEmployeeList} from '@src/types/onyx/PolicyEmployee'; import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; import createRandomPolicy from '../utils/collections/policies'; +import createMock from '../utils/createMock'; import {buildPersonalDetails, convertToDisplayString, localeCompare, translateLocal} from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -608,10 +609,10 @@ describe('WorkflowUtils', () => { submitsTo: 'alice@example.com', }, }; - const policy: Partial = { + const policy = createMock({ ...createMockPolicy(employees, 'alice@example.com'), owner: 'alice@example.com', - }; + }); const personalDetailsForTest: PersonalDetailsList = { 'alice@example.com': {accountID: 1, login: 'alice@example.com', displayName: 'Alice'}, 'guide@expensify.com': {accountID: 2, login: 'guide@expensify.com', displayName: 'Guide'}, @@ -619,7 +620,7 @@ describe('WorkflowUtils', () => { }; const {approvalWorkflows, availableMembers} = convertPolicyEmployeesToApprovalWorkflows({ - policy: policy as Policy, + policy, personalDetails: personalDetailsForTest, localeCompare, currentUserLogin: 'alice@example.com', @@ -646,17 +647,17 @@ describe('WorkflowUtils', () => { submitsTo: 'admin@expensify.com', }, }; - const policy: Partial = { + const policy = createMock({ ...createMockPolicy(employees, 'admin@expensify.com'), owner: 'admin@expensify.com', - }; + }); const personalDetailsForTest: PersonalDetailsList = { 'admin@expensify.com': {accountID: 1, login: 'admin@expensify.com', displayName: 'Admin'}, 'guide@expensify.com': {accountID: 2, login: 'guide@expensify.com', displayName: 'Guide'}, }; const {availableMembers} = convertPolicyEmployeesToApprovalWorkflows({ - policy: policy as Policy, + policy, personalDetails: personalDetailsForTest, localeCompare, currentUserLogin: 'admin@expensify.com', @@ -678,17 +679,17 @@ describe('WorkflowUtils', () => { submitsTo: 'alice@example.com', }, }; - const policy: Partial = { + const policy = createMock({ ...createMockPolicy(employees, 'alice@example.com'), owner: 'alice@example.com', - }; + }); const personalDetailsForTest: PersonalDetailsList = { 'alice@example.com': {accountID: 1, login: 'alice@example.com', displayName: 'Alice'}, 'guide@expensify.com': {accountID: 2, login: 'guide@expensify.com', displayName: 'Guide'}, }; const {availableMembers} = convertPolicyEmployeesToApprovalWorkflows({ - policy: policy as Policy, + policy, personalDetails: personalDetailsForTest, localeCompare, }); @@ -713,10 +714,10 @@ describe('WorkflowUtils', () => { submitsTo: 'bob@example.com', }, }; - const policy: Partial = { + const policy = createMock({ ...createMockPolicy(employees, 'bob@example.com'), owner: 'alice@example.com', - }; + }); const personalDetailsForTest: PersonalDetailsList = { 'alice@example.com': {accountID: 1, login: 'alice@example.com', displayName: 'Alice'}, 'guide@expensify.com': {accountID: 2, login: 'guide@expensify.com', displayName: 'Guide'}, @@ -724,7 +725,7 @@ describe('WorkflowUtils', () => { }; const {approvalWorkflows} = convertPolicyEmployeesToApprovalWorkflows({ - policy: policy as Policy, + policy, personalDetails: personalDetailsForTest, localeCompare, currentUserLogin: 'alice@example.com', @@ -756,10 +757,10 @@ describe('WorkflowUtils', () => { submitsTo: 'bob@example.com', }, }; - const policy: Partial = { + const policy = createMock({ ...createMockPolicy(employees, 'bob@example.com'), owner: 'alice@example.com', - }; + }); const personalDetailsForTest: PersonalDetailsList = { 'alice@example.com': {accountID: 1, login: 'alice@example.com', displayName: 'Alice'}, 'bob@example.com': {accountID: 2, login: 'bob@example.com', displayName: 'Bob'}, @@ -768,7 +769,7 @@ describe('WorkflowUtils', () => { }; const {approvalWorkflows} = convertPolicyEmployeesToApprovalWorkflows({ - policy: policy as Policy, + policy, personalDetails: personalDetailsForTest, localeCompare, currentUserLogin: 'alice@example.com', @@ -793,7 +794,7 @@ describe('WorkflowUtils', () => { submitsTo: 'finalapprover@example.com', }, }; - const policy: Partial = { + const policy = createMock({ ...createMockPolicy(employees, 'owner@example.com'), owner: 'owner@example.com', approver: 'owner@example.com', @@ -807,7 +808,7 @@ describe('WorkflowUtils', () => { }, }, }, - }; + }); const personalDetailsForTest: PersonalDetailsList = { 'unassigned@example.com': {accountID: 1, login: 'unassigned@example.com', displayName: 'Unassigned'}, 'assigned@example.com': {accountID: 2, login: 'assigned@example.com', displayName: 'Assigned'}, @@ -816,7 +817,7 @@ describe('WorkflowUtils', () => { }; const {approvalWorkflows} = convertPolicyEmployeesToApprovalWorkflows({ - policy: policy as Policy, + policy, personalDetails: personalDetailsForTest, localeCompare, }); @@ -1500,13 +1501,13 @@ describe('WorkflowUtils', () => { describe('getOpenConnectedToPolicyBusinessBankAccounts', () => { const matchingBankAccountID = 12345; - const policyWithACH = { + const policyWithACH = createMock({ ...createRandomPolicy(1), outputCurrency: 'USD', achAccount: { bankAccountID: matchingBankAccountID, }, - } as Policy; + }); const openBusinessBankAccount = { bankCurrency: 'USD', diff --git a/tests/unit/submitDismissStrategiesTest.ts b/tests/unit/submitDismissStrategiesTest.ts index ac9c7b4c8b65..352509552c82 100644 --- a/tests/unit/submitDismissStrategiesTest.ts +++ b/tests/unit/submitDismissStrategiesTest.ts @@ -9,6 +9,8 @@ import {dismissOnly, dismissRHPToReport, dismissSuperWideRHP, dismissWideToNewSe import CONST from '@src/CONST'; import type {SearchDataTypes} from '@src/types/onyx/SearchResults'; +import createMock from '../utils/createMock'; + const mockGetIsNarrowLayout = jest.fn(); const mockGetTopmostReportParams = jest.fn<{reportID: string} | undefined, [unknown]>(); const mockGetReportOrDraftReport = jest.fn(); @@ -71,8 +73,14 @@ describe('submitDismissStrategies', () => { it('ends span, flushes deferred write, and runs callback in afterTransition', () => { dismissOnly(runAfterDismiss); - const opts = jest.mocked(Navigation.dismissModal).mock.calls.at(0)?.at(0) as {afterTransition: () => void} | undefined; - opts?.afterTransition(); + const opts = jest.mocked(Navigation.dismissModal).mock.calls.at(0)?.at(0); + if (!opts) { + throw new Error('Expected dismissModal options'); + } + if (!opts.afterTransition) { + throw new Error('Expected dismissModal afterTransition callback'); + } + opts.afterTransition(); expect(endSubmitFollowUpActionSpan).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_FOLLOW_UP_ACTION.DISMISS_MODAL_ONLY); expect(flushDeferredWrite).toHaveBeenCalledWith(CONST.DEFERRED_LAYOUT_WRITE_KEYS.DISMISS_MODAL); @@ -99,9 +107,11 @@ describe('submitDismissStrategies', () => { it('pops RHP and runs callback after transitions when report has no existing transactions', () => { mockGetReportOrDraftReport.mockReturnValue({reportID: 'report-1', transactionCount: 0}); mockIsMoneyRequestReport.mockReturnValue(true); - (navigationRef.getRootState as jest.Mock).mockReturnValue({ - routes: [{state: {key: 'rhp-key'}}], - }); + jest.spyOn(navigationRef, 'getRootState').mockReturnValue( + createMock>({ + routes: [{state: {key: 'rhp-key'}}], + }), + ); dismissRHPToReport('report-1', runAfterDismiss); @@ -137,9 +147,11 @@ describe('submitDismissStrategies', () => { it('pops RHP when report is not a money request report (no existing transactions)', () => { mockGetReportOrDraftReport.mockReturnValue({reportID: 'report-1'}); mockIsMoneyRequestReport.mockReturnValue(false); - (navigationRef.getRootState as jest.Mock).mockReturnValue({ - routes: [{state: {key: 'rhp-key-2'}}], - }); + jest.spyOn(navigationRef, 'getRootState').mockReturnValue( + createMock>({ + routes: [{state: {key: 'rhp-key-2'}}], + }), + ); dismissRHPToReport('report-1', runAfterDismiss); @@ -205,8 +217,14 @@ describe('submitDismissStrategies', () => { executeDismissModalStrategy('report-1', runAfterDismiss); - const opts = jest.mocked(Navigation.dismissModal).mock.calls.at(0)?.at(0) as {afterTransition: () => void} | undefined; - opts?.afterTransition(); + const opts = jest.mocked(Navigation.dismissModal).mock.calls.at(0)?.at(0); + if (!opts) { + throw new Error('Expected dismissModal options'); + } + if (!opts.afterTransition) { + throw new Error('Expected dismissModal afterTransition callback'); + } + opts.afterTransition(); expect(endSubmitFollowUpActionSpan).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_FOLLOW_UP_ACTION.DISMISS_MODAL_ONLY, 'report-1'); expect(flushDeferredWrite).toHaveBeenCalledWith(CONST.DEFERRED_LAYOUT_WRITE_KEYS.DISMISS_MODAL); @@ -239,8 +257,14 @@ describe('submitDismissStrategies', () => { executeDismissModalStrategy('report-1', runAfterDismiss); - const opts = jest.mocked(Navigation.revealRouteBeforeDismissingModal).mock.calls.at(0)?.at(1) as {afterTransition: () => void} | undefined; - opts?.afterTransition(); + const opts = jest.mocked(Navigation.revealRouteBeforeDismissingModal).mock.calls.at(0)?.[1]; + if (!opts) { + throw new Error('Expected revealRouteBeforeDismissingModal options'); + } + if (!opts.afterTransition) { + throw new Error('Expected revealRouteBeforeDismissingModal afterTransition callback'); + } + opts.afterTransition(); expect(flushDeferredWrite).toHaveBeenCalledWith(CONST.DEFERRED_LAYOUT_WRITE_KEYS.DISMISS_MODAL); expect(runAfterDismiss).toHaveBeenCalled(); @@ -252,9 +276,15 @@ describe('submitDismissStrategies', () => { executeDismissModalStrategy('report-1', runAfterDismiss); - const opts = jest.mocked(Navigation.dismissModalWithReport).mock.calls.at(0)?.at(2) as {onBeforeNavigate: (willOpenReport: boolean) => void} | undefined; + const opts = jest.mocked(Navigation.dismissModalWithReport).mock.calls.at(0)?.[2]; jest.mocked(setPendingSubmitFollowUpAction).mockClear(); - opts?.onBeforeNavigate(true); + if (!opts) { + throw new Error('Expected dismissModalWithReport options'); + } + if (!opts.onBeforeNavigate) { + throw new Error('Expected dismissModalWithReport onBeforeNavigate callback'); + } + opts.onBeforeNavigate(true); expect(setPendingSubmitFollowUpAction).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_FOLLOW_UP_ACTION.DISMISS_MODAL_AND_OPEN_REPORT, 'report-1'); }); @@ -264,9 +294,15 @@ describe('submitDismissStrategies', () => { executeDismissModalStrategy('report-1', runAfterDismiss); - const opts = jest.mocked(Navigation.dismissModalWithReport).mock.calls.at(0)?.at(2) as {onBeforeNavigate: (willOpenReport: boolean) => void} | undefined; + const opts = jest.mocked(Navigation.dismissModalWithReport).mock.calls.at(0)?.[2]; jest.mocked(setPendingSubmitFollowUpAction).mockClear(); - opts?.onBeforeNavigate(false); + if (!opts) { + throw new Error('Expected dismissModalWithReport options'); + } + if (!opts.onBeforeNavigate) { + throw new Error('Expected dismissModalWithReport onBeforeNavigate callback'); + } + opts.onBeforeNavigate(false); expect(setPendingSubmitFollowUpAction).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_FOLLOW_UP_ACTION.DISMISS_MODAL_ONLY, 'report-1'); });