From 5d692b4792a7d325c6bf32b02502d39dab918c5b Mon Sep 17 00:00:00 2001 From: KJ21-ENG <140263938+KJ21-ENG@users.noreply.github.com> Date: Thu, 30 Jul 2026 21:42:07 +0530 Subject: [PATCH 1/3] Clean up unsafe assertions in test targets --- .../tests/resolveCanvasSize.test.ts | 15 +-- .../GetUpdateMoneyRequestParamsTest.ts | 32 +++++-- .../IOUTest/UpdateMoneyRequestVendorTest.ts | 96 ++++++++----------- ...aceOptimisticReportWithActualReportTest.ts | 45 +++++---- tests/actions/connections/SageIntacct.ts | 20 ++-- tests/navigation/linkToHelpersTests.ts | 16 ++-- tests/navigation/useDynamicBackPathTests.ts | 17 +++- tests/ui/AgentsPromoBannersTest.tsx | 10 +- tests/ui/AssignCardFeed.tsx | 60 ++++++------ tests/ui/components/HeaderViewTest.tsx | 40 +++++--- tests/ui/components/SettlementButtonTest.tsx | 11 ++- .../unit/ReportActionsListPaddingViewTest.tsx | 30 ++++-- tests/unit/SearchParserTest.ts | 51 ++++++++-- tests/unit/SuggestionMentionTest.tsx | 62 ++++++++---- .../unit/showReportActionNotificationTest.ts | 34 +++++-- 15 files changed, 334 insertions(+), 205 deletions(-) diff --git a/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts b/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts index 44ebbe8fdfbb..05c7363c5aa3 100644 --- a/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts +++ b/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts @@ -1,15 +1,18 @@ +/// + import type {TNode} from 'react-native-render-html'; import {describe, expect, test} from 'bun:test'; +import createMock from 'tests/utils/createMock'; import resolveCanvasSize from '../src/resolveCanvasSize'; function makeChartNode(attributes: TNode['attributes'], children: TNode[] = []): TNode { - return { + return createMock({ tagName: 'victorychart', attributes, children, - } as unknown as TNode; + }); } describe('resolveCanvasSize', () => { @@ -30,11 +33,11 @@ describe('resolveCanvasSize', () => { describe('validation errors', () => { test('throws when overlays exist without chart dimensions', () => { const tnode = makeChartNode({}, [ - { + createMock({ tagName: 'victorylabel', attributes: {x: '10', y: '20', text: 'Title'}, children: [], - } as unknown as TNode, + }), ]); expect(() => resolveCanvasSize(tnode)).toThrow('require explicit width and height'); @@ -60,11 +63,11 @@ describe('resolveCanvasSize', () => { test('throws when overlay has non-numeric coordinates and chart dimensions are missing', () => { const tnode = makeChartNode({}, [ - { + createMock({ tagName: 'victorylabel', attributes: {x: 'not-a-number', y: '20', text: 'Title'}, children: [], - } as unknown as TNode, + }), ]); expect(() => resolveCanvasSize(tnode)).toThrow('require explicit width and height'); diff --git a/tests/actions/IOUTest/GetUpdateMoneyRequestParamsTest.ts b/tests/actions/IOUTest/GetUpdateMoneyRequestParamsTest.ts index 53254dfbf686..f1c90459a066 100644 --- a/tests/actions/IOUTest/GetUpdateMoneyRequestParamsTest.ts +++ b/tests/actions/IOUTest/GetUpdateMoneyRequestParamsTest.ts @@ -1,5 +1,6 @@ import {getUpdateMoneyRequestParams} from '@libs/actions/IOU/UpdateMoneyRequest'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; +import {isRecord} from '@libs/ObjectUtils'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; @@ -51,6 +52,15 @@ const REPORT_ID = 'testReportID'; const IOU_REPORT_ID = 'testIOUReportID'; const POLICY_ID = 'testPolicyID'; +function isRecentlyUsedTags(value: unknown, tagListName: TKey): value is Pick { + if (!isRecord(value)) { + return false; + } + + const tags = value[tagListName]; + return Array.isArray(tags) && tags.every((tag: unknown): tag is string => typeof tag === 'string'); +} + const transactionThreadReport: Report = { reportID: REPORT_ID, type: CONST.REPORT.TYPE.EXPENSE, @@ -162,8 +172,10 @@ describe('getUpdateMoneyRequestParams — policyTagList', () => { // Then the tag should appear in the recently used tags for the correct policy and tag list const recentlyUsedTagsEntry = onyxData.optimisticData?.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${POLICY_ID}`); expect(recentlyUsedTagsEntry).toBeDefined(); - const value = recentlyUsedTagsEntry?.value as RecentlyUsedTags; - expect(value[tagListName]).toContain(tag1); + if (!recentlyUsedTagsEntry || !isRecentlyUsedTags(recentlyUsedTagsEntry.value, tagListName)) { + throw new Error('Expected recently used tags for the changed tag list'); + } + expect(recentlyUsedTagsEntry.value[tagListName]).toContain(tag1); }); it('should prepend the new tag before existing recently used tags', () => { @@ -203,9 +215,11 @@ describe('getUpdateMoneyRequestParams — policyTagList', () => { // Then the new tag should be first and the old tag should still be present const recentlyUsedTagsEntry = onyxData.optimisticData?.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${POLICY_ID}`); expect(recentlyUsedTagsEntry).toBeDefined(); - const value = recentlyUsedTagsEntry?.value as RecentlyUsedTags; - expect(value[tagListName].at(0)).toBe(tag2); - expect(value[tagListName]).toContain(tag1); + if (!recentlyUsedTagsEntry || !isRecentlyUsedTags(recentlyUsedTagsEntry.value, tagListName)) { + throw new Error('Expected recently used tags for the changed tag list'); + } + expect(recentlyUsedTagsEntry.value[tagListName].at(0)).toBe(tag2); + expect(recentlyUsedTagsEntry.value[tagListName]).toContain(tag1); }); it('should deduplicate when the same tag is set again', () => { @@ -245,9 +259,11 @@ describe('getUpdateMoneyRequestParams — policyTagList', () => { // Then tag1 should appear exactly once and be at the front const recentlyUsedTagsEntry = onyxData.optimisticData?.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${POLICY_ID}`); expect(recentlyUsedTagsEntry).toBeDefined(); - const value = recentlyUsedTagsEntry?.value as RecentlyUsedTags; - expect(value[tagListName].filter((t) => t === tag1).length).toBe(1); - expect(value[tagListName].at(0)).toBe(tag1); + if (!recentlyUsedTagsEntry || !isRecentlyUsedTags(recentlyUsedTagsEntry.value, tagListName)) { + throw new Error('Expected recently used tags for the changed tag list'); + } + expect(recentlyUsedTagsEntry.value[tagListName].filter((tag) => tag === tag1)).toHaveLength(1); + expect(recentlyUsedTagsEntry.value[tagListName].at(0)).toBe(tag1); }); it('should fall back to the same behavior as passing an empty policyTagList when policyTagList is undefined and Onyx has no policy tags data', () => { diff --git a/tests/actions/IOUTest/UpdateMoneyRequestVendorTest.ts b/tests/actions/IOUTest/UpdateMoneyRequestVendorTest.ts index 47aa22e4b71a..57ef891fa424 100644 --- a/tests/actions/IOUTest/UpdateMoneyRequestVendorTest.ts +++ b/tests/actions/IOUTest/UpdateMoneyRequestVendorTest.ts @@ -1,12 +1,15 @@ import {updateMoneyRequestVendor} from '@libs/actions/IOU/UpdateMoneyRequest'; -import * as API from '@libs/API'; +import * as APIActions from '@libs/API'; +import {getOriginalMessage} from '@libs/ReportActionsUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Report, Transaction, TransactionViolation} from '@src/types/onyx'; +import type {Report, ReportAction, Transaction, TransactionViolation} from '@src/types/onyx'; import Onyx from 'react-native-onyx'; +import {getRequiredOnyxUpdate, getRequiredOnyxUpdates, getRequiredWriteCall} from '../../utils/TestHelper'; +import {isObject} from '../../utils/typeGuards'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; const TRANSACTION_ID = 'txn-vendor-test'; @@ -34,14 +37,14 @@ const otherViolation: TransactionViolation = { }; describe('updateMoneyRequestVendor', () => { - let writeSpy: jest.SpyInstance; + let writeSpy: jest.SpiedFunction; beforeAll(() => { Onyx.init({keys: ONYXKEYS}); }); beforeEach(() => { - writeSpy = jest.spyOn(API, 'write').mockImplementation(jest.fn()); + writeSpy = jest.spyOn(APIActions, 'write').mockImplementation(jest.fn()); }); afterEach(async () => { @@ -49,15 +52,7 @@ describe('updateMoneyRequestVendor', () => { await Onyx.clear(); }); - type OnyxDataArg = { - optimisticData: Array<{key: string; value: unknown}>; - successData: Array<{key: string; value: unknown}>; - failureData: Array<{key: string; value: unknown}>; - }; - const getOnyxDataArg = (): OnyxDataArg | undefined => { - const firstCall = writeSpy.mock.calls.at(0) as unknown[] | undefined; - return firstCall?.at(2) as OnyxDataArg | undefined; - }; + const getOnyxDataArg = () => getRequiredWriteCall(writeSpy.mock.calls, 0)[2]; it('clears an existing inactive-vendor violation optimistically when a vendor is picked', async () => { await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`, [otherViolation, inactiveVendorViolation]); @@ -65,10 +60,8 @@ describe('updateMoneyRequestVendor', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-active', transaction: baseTransaction, delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const violationsUpdate = onyxData?.optimisticData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`); - expect(violationsUpdate).toBeDefined(); - expect(violationsUpdate?.value).toEqual([otherViolation]); + const violationsUpdate = getRequiredOnyxUpdate(getOnyxDataArg(), 'optimisticData', `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`, Onyx.METHOD.SET, true); + expect(violationsUpdate.value).toEqual([otherViolation]); }); it('clears an existing inactive-vendor violation optimistically when the vendor is cleared', async () => { @@ -77,10 +70,8 @@ describe('updateMoneyRequestVendor', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: '', transaction: baseTransaction, delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const violationsUpdate = onyxData?.optimisticData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`); - expect(violationsUpdate).toBeDefined(); - expect(violationsUpdate?.value).toEqual([]); + const violationsUpdate = getRequiredOnyxUpdate(getOnyxDataArg(), 'optimisticData', `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`, Onyx.METHOD.SET, true); + expect(violationsUpdate.value).toEqual([]); }); it('restores the original violation list in failureData so a server rejection rolls back cleanly', async () => { @@ -90,9 +81,8 @@ describe('updateMoneyRequestVendor', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-active', transaction: baseTransaction, delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const failureViolations = onyxData?.failureData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`); - expect(failureViolations?.value).toEqual(original); + const failureViolations = getRequiredOnyxUpdate(getOnyxDataArg(), 'failureData', `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`, Onyx.METHOD.SET, true); + expect(failureViolations.value).toEqual(original); }); it('does not write a violations update when there was no inactive-vendor violation to clear', async () => { @@ -101,9 +91,10 @@ describe('updateMoneyRequestVendor', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-active', transaction: baseTransaction, delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const violationsUpdate = onyxData?.optimisticData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`); - expect(violationsUpdate).toBeUndefined(); + const violationsUpdate = getRequiredOnyxUpdates(getOnyxDataArg(), 'optimisticData').some( + (entry) => isObject(entry) && entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${TRANSACTION_ID}`, + ); + expect(violationsUpdate).toBe(false); }); it('falls back to the Onyx-cached transaction for vendor rollback when caller omits transaction', async () => { @@ -116,9 +107,8 @@ describe('updateMoneyRequestVendor', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-new', delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const transactionFailure = onyxData?.failureData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`); - expect(transactionFailure?.value).toEqual({ + const transactionFailure = getRequiredOnyxUpdate(getOnyxDataArg(), 'failureData', `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, Onyx.METHOD.MERGE, true); + expect(transactionFailure.value).toEqual({ pendingFields: {vendor: null}, comment: {vendor: previousVendor}, }); @@ -130,17 +120,15 @@ describe('updateMoneyRequestVendor', () => { // pendingFields-clear entry still runs (so the offline indicator clears on rejection). updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-new', delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const transactionFailure = onyxData?.failureData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`); - expect(transactionFailure?.value).toEqual({pendingFields: {vendor: null}}); + const transactionFailure = getRequiredOnyxUpdate(getOnyxDataArg(), 'failureData', `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, Onyx.METHOD.MERGE, true); + expect(transactionFailure.value).toEqual({pendingFields: {vendor: null}}); }); it('writes pendingFields.vendor = UPDATE in optimisticData so the offline indicator surfaces', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-new', transaction: baseTransaction, delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const transactionOptimistic = onyxData?.optimisticData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`); - expect(transactionOptimistic?.value).toEqual({ + const transactionOptimistic = getRequiredOnyxUpdate(getOnyxDataArg(), 'optimisticData', `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, Onyx.METHOD.MERGE, true); + expect(transactionOptimistic.value).toEqual({ comment: {vendor: {externalID: 'v-new', isManuallySet: true}}, pendingFields: {vendor: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE}, }); @@ -149,9 +137,8 @@ describe('updateMoneyRequestVendor', () => { it('clears pendingFields.vendor in successData when the server confirms the write', () => { updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-new', transaction: baseTransaction, delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const transactionSuccess = onyxData?.successData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`); - expect(transactionSuccess?.value).toEqual({pendingFields: {vendor: null}}); + const transactionSuccess = getRequiredOnyxUpdate(getOnyxDataArg(), 'successData', `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, Onyx.METHOD.MERGE, true); + expect(transactionSuccess.value).toEqual({pendingFields: {vendor: null}}); }); it('clears pendingFields.vendor in failureData when the server rejects the write', () => { @@ -159,9 +146,8 @@ describe('updateMoneyRequestVendor', () => { // clear on failure — otherwise the row stays stuck in "pending" forever after a server reject. updateMoneyRequestVendor({transactionID: TRANSACTION_ID, vendorID: 'v-new', delegateAccountID: undefined}); - const onyxData = getOnyxDataArg(); - const transactionFailure = onyxData?.failureData.find((entry) => entry.key === `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`); - expect(transactionFailure?.value).toMatchObject({pendingFields: {vendor: null}}); + const transactionFailure = getRequiredOnyxUpdate(getOnyxDataArg(), 'failureData', `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, Onyx.METHOD.MERGE, true); + expect(transactionFailure.value).toMatchObject({pendingFields: {vendor: null}}); }); describe('optimistic MODIFIED_EXPENSE report action', () => { @@ -176,14 +162,15 @@ describe('updateMoneyRequestVendor', () => { reportName: 'Transaction thread', } as Report; - type ReportActionMap = Record; + type ModifiedExpenseReportAction = ReportAction; + function isModifiedExpenseReportAction(value: unknown): value is ModifiedExpenseReportAction { + return isObject(value) && value.actionName === CONST.REPORT.ACTIONS.TYPE.MODIFIED_EXPENSE && typeof value.reportActionID === 'string' && typeof value.created === 'string'; + } - const findOptimisticModifiedExpense = (): {actionName?: string; originalMessage?: {vendor?: unknown; oldVendor?: unknown}} | undefined => { - const onyxData = getOnyxDataArg(); + const findOptimisticModifiedExpense = () => { const reportActionsKey = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${TRANSACTION_THREAD_REPORT_ID}`; - const update = onyxData?.optimisticData.find((entry) => entry.key === reportActionsKey); - const value = update?.value as ReportActionMap | undefined; - return value ? Object.values(value).find((action) => action?.actionName === CONST.REPORT.ACTIONS.TYPE.MODIFIED_EXPENSE) : undefined; + const update = getRequiredOnyxUpdate(getOnyxDataArg(), 'optimisticData', reportActionsKey, Onyx.METHOD.MERGE, true); + return Object.values(update.value).find((action): action is ModifiedExpenseReportAction => isModifiedExpenseReportAction(action)); }; it('builds an optimistic MODIFIED_EXPENSE with `vendor` set and `oldVendor` null when adding a vendor (no prior)', () => { @@ -199,7 +186,7 @@ describe('updateMoneyRequestVendor', () => { expect(optimisticAction).toBeDefined(); // `oldVendor: null` signals "no prior vendor". Onyx strips nested nulls on merge, which // is fine — `ModifiedExpenseMessage` treats either key's presence as a vendor change. - expect(optimisticAction?.originalMessage).toMatchObject({ + expect(getOriginalMessage(optimisticAction)).toMatchObject({ vendor: {externalID: 'v-new', isManuallySet: true}, oldVendor: null, }); @@ -221,7 +208,7 @@ describe('updateMoneyRequestVendor', () => { }); const optimisticAction = findOptimisticModifiedExpense(); - expect(optimisticAction?.originalMessage).toMatchObject({ + expect(getOriginalMessage(optimisticAction)).toMatchObject({ oldVendor: previousVendor, vendor: {externalID: 'v-new', isManuallySet: true}, }); @@ -243,7 +230,7 @@ describe('updateMoneyRequestVendor', () => { }); const optimisticAction = findOptimisticModifiedExpense(); - expect(optimisticAction?.originalMessage).toMatchObject({ + expect(getOriginalMessage(optimisticAction)).toMatchObject({ oldVendor: previousVendor, vendor: null, }); @@ -257,9 +244,10 @@ describe('updateMoneyRequestVendor', () => { delegateAccountID: undefined, }); - const onyxData = getOnyxDataArg(); - const reportActionsUpdate = onyxData?.optimisticData.find((entry) => entry.key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS)); - expect(reportActionsUpdate).toBeUndefined(); + const reportActionsUpdate = getRequiredOnyxUpdates(getOnyxDataArg(), 'optimisticData').some( + (entry) => isObject(entry) && typeof entry.key === 'string' && entry.key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS), + ); + expect(reportActionsUpdate).toBe(false); }); }); }); diff --git a/tests/actions/ReplaceOptimisticReportWithActualReportTest.ts b/tests/actions/ReplaceOptimisticReportWithActualReportTest.ts index 1590b5c2c864..d78f5e145d99 100644 --- a/tests/actions/ReplaceOptimisticReportWithActualReportTest.ts +++ b/tests/actions/ReplaceOptimisticReportWithActualReportTest.ts @@ -1,7 +1,10 @@ import {beforeAll, beforeEach, describe, expect, it} from '@jest/globals'; +import type * as NavigationModule from '@libs/Navigation/Navigation'; + import CONST from '@src/CONST'; import {replaceOptimisticReportWithActualReport} from '@src/libs/actions/replaceOptimisticReportWithActualReport'; +import type * as ReportActions from '@src/libs/actions/Report'; import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; @@ -13,36 +16,44 @@ import {createRandomReport} from '../utils/collections/reports'; import getOnyxValue from '../utils/getOnyxValue'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; +type Navigation = typeof NavigationModule.default; + type SwitchReportEventData = { preexistingReportID: string; reportToCopyDraftTo: string; callback: () => void; }; -const mockNavigate = jest.fn(); -const mockSetParams = jest.fn(); +const mockNavigate = jest.fn, Parameters>(); +const mockSetParams = jest.fn, Parameters>(); const mockIsReady = jest.fn(() => false); const mockGetActiveRoute = jest.fn(() => ''); const mockGetCurrentRoute = jest.fn(() => undefined as {name: string; params: Record} | undefined); -jest.mock('@libs/Navigation/Navigation', () => ({ - navigate: (...args: unknown[]) => mockNavigate(...args) as void, - setParams: (...args: unknown[]) => mockSetParams(...args) as void, - getActiveRoute: () => mockGetActiveRoute(), - navigationRef: { - isReady: () => mockIsReady(), - getCurrentRoute: () => mockGetCurrentRoute(), - }, -})); - -const mockOpenReport = jest.fn(); +jest.mock('@libs/Navigation/Navigation', () => { + const mockNavigation = { + navigate: (...args: Parameters): ReturnType => mockNavigate(...args), + setParams: (...args: Parameters): ReturnType => mockSetParams(...args), + getActiveRoute: () => mockGetActiveRoute(), + navigationRef: { + isReady: () => mockIsReady(), + getCurrentRoute: () => mockGetCurrentRoute(), + }, + }; + + return { + __esModule: true, + ...mockNavigation, + default: mockNavigation, + }; +}); + +const mockOpenReport = jest.fn, Parameters>(); jest.mock('@src/libs/actions/Report', () => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const originalModule = jest.requireActual('@src/libs/actions/Report'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const originalModule = jest.requireActual('@src/libs/actions/Report'); return { ...originalModule, - openReport: (...args: unknown[]) => mockOpenReport(...args) as void, + openReport: (...args: Parameters): ReturnType => mockOpenReport(...args), }; }); diff --git a/tests/actions/connections/SageIntacct.ts b/tests/actions/connections/SageIntacct.ts index 2a0fe6072868..6f44786a88c5 100644 --- a/tests/actions/connections/SageIntacct.ts +++ b/tests/actions/connections/SageIntacct.ts @@ -6,11 +6,10 @@ import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy as PolicyType} from '@src/types/onyx'; import type {SageIntacctConnectionsConfig} from '@src/types/onyx/Policy'; import type {AnyOnyxData} from '@src/types/onyx/Request'; -import type {OnyxKey, OnyxUpdate} from 'react-native-onyx'; +import type {NullishDeep, OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; @@ -24,16 +23,17 @@ const writeSpy = jest.spyOn(API, 'write'); const MOCK_POLICY_ID = 'MOCK_POLICY_ID'; const MOCK_ONYX_ERROR = {key: 'error'}; -function getSageIntacctConfig(update?: OnyxUpdate): SageIntacctConnectionsConfig | undefined { - if (!update || typeof update.value !== 'object' || update.value === null) { +type SageIntacctConfigMerge = NullishDeep; + +function getSageIntacctConfig(update?: OnyxUpdate): SageIntacctConfigMerge | undefined { + if (!update || !update.value || typeof update.value !== 'object' || !('connections' in update.value)) { return undefined; } - const policyData = update.value as Pick; - return policyData.connections?.intacct?.config; + return update.value.connections?.intacct?.config ?? undefined; } -function getRequiredSageIntacctConfig(update?: OnyxUpdate): SageIntacctConnectionsConfig { +function getRequiredSageIntacctConfig(update?: OnyxUpdate): SageIntacctConfigMerge { const config = getSageIntacctConfig(update); if (!config) { throw new Error('Sage Intacct config is missing from the provided Onyx update'); @@ -59,7 +59,7 @@ describe('actions/connections/SageIntacct', () => { beforeEach(() => { jest.clearAllMocks(); - (getMicroSecondOnyxErrorWithTranslationKey as jest.Mock).mockReturnValue(MOCK_ONYX_ERROR); + jest.mocked(getMicroSecondOnyxErrorWithTranslationKey).mockReturnValue(MOCK_ONYX_ERROR); return Onyx.clear().then(waitForBatchedUpdates); }); @@ -75,9 +75,7 @@ describe('actions/connections/SageIntacct', () => { expect(command).toBe(WRITE_COMMANDS.UPDATE_SAGE_INTACCT_TRAVEL_INVOICING_PAYABLE_ACCOUNT); const call = writeSpy.mock.calls.at(0); - const params = call?.[1] as {policyID: string; creditCardAccountID: string}; - expect(params.policyID).toBe(MOCK_POLICY_ID); - expect(params.creditCardAccountID).toBe('account-123'); + expect(call?.[1]).toMatchObject({policyID: MOCK_POLICY_ID, creditCardAccountID: 'account-123'}); }); it('updates travelInvoicingPayableAccountID optimistically, sets pending field, and clears error field', () => { diff --git a/tests/navigation/linkToHelpersTests.ts b/tests/navigation/linkToHelpersTests.ts index 6b8cbc4b287a..fe713dc9ce8a 100644 --- a/tests/navigation/linkToHelpersTests.ts +++ b/tests/navigation/linkToHelpersTests.ts @@ -6,21 +6,23 @@ import SCREENS from '@src/SCREENS'; import type {NavigationState, PartialState} from '@react-navigation/native'; -function makeRootState(routes: Array<{name: string; key?: string}>): NavigationState { - return { +import createMock from '../utils/createMock'; + +function makeRootState(routes: Array<{name: keyof RootNavigatorParamList; key?: string}>): NavigationState { + return createMock>({ routes: routes.map((r, i) => ({name: r.name, key: r.key ?? `k-${i}`, params: undefined})), index: routes.length - 1, key: 'root', routeNames: routes.map((r) => r.name), stale: false, type: 'stack', - } as unknown as NavigationState; + }); } -function makePartialState(routes: Array<{name: string}>): PartialState> { - return { +function makePartialState(routes: Array<{name: keyof RootNavigatorParamList}>): PartialState> { + return createMock>>({ routes: routes.map((r) => ({name: r.name})), - } as PartialState>; + }); } describe('isSwitchingTabsWithinTabNavigator', () => { @@ -51,7 +53,7 @@ describe('isSwitchingTabsWithinTabNavigator', () => { it('returns false when target state has no routes', () => { const current = makeRootState([{name: NAVIGATORS.TAB_NAVIGATOR}]); - const target = {routes: undefined} as unknown as PartialState>; + const target = createMock>>({routes: undefined}); expect(isSwitchingTabsWithinTabNavigator(current, target)).toBe(false); }); }); diff --git a/tests/navigation/useDynamicBackPathTests.ts b/tests/navigation/useDynamicBackPathTests.ts index cc21cbadd9f9..3629da24b624 100644 --- a/tests/navigation/useDynamicBackPathTests.ts +++ b/tests/navigation/useDynamicBackPathTests.ts @@ -2,6 +2,8 @@ import {renderHook} from '@testing-library/react-native'; import useDynamicBackPath from '@hooks/useDynamicBackPath'; +import isDynamicRouteSuffix from '@libs/Navigation/helpers/dynamicRoutesUtils/isDynamicRouteSuffix'; + import type {DynamicRouteSuffix} from '@src/ROUTES'; import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; @@ -28,6 +30,13 @@ jest.mock('@src/ROUTES', () => ({ const useRootNavigationStateMock = jest.requireMock('@hooks/useRootNavigationState'); const getPathFromStateMock: jest.Mock = jest.requireMock('@libs/Navigation/helpers/getPathFromState'); +function getMockDynamicRouteSuffix(path: string): DynamicRouteSuffix { + if (!isDynamicRouteSuffix(path)) { + throw new Error(`Expected mocked dynamic route suffix to be recognized: ${path}`); + } + return path; +} + describe('useDynamicBackPath', () => { beforeEach(() => { jest.clearAllMocks(); @@ -97,8 +106,8 @@ describe('useDynamicBackPath', () => { expect(result.current).toBe('settings/wallet'); }); - const FLAG_COMMENT_PATH = 'flag/:reportID/:reportActionID' as DynamicRouteSuffix; - const MEMBER_DETAILS_PATH = 'member-details/:accountID' as DynamicRouteSuffix; + const FLAG_COMMENT_PATH = getMockDynamicRouteSuffix('flag/:reportID/:reportActionID'); + const MEMBER_DETAILS_PATH = getMockDynamicRouteSuffix('member-details/:accountID'); it('should remove parametric suffix with single param', () => { getPathFromStateMock.mockReturnValue('r/123/members/member-details/456'); @@ -141,8 +150,8 @@ describe('useDynamicBackPath', () => { }); describe('optional path params', () => { - const OPT_TRAILING_PATH = 'opt-page/:id?' as DynamicRouteSuffix; - const OPT_MIDDLE_PATH = 'wrap/:p?/end' as DynamicRouteSuffix; + const OPT_TRAILING_PATH = getMockDynamicRouteSuffix('opt-page/:id?'); + const OPT_MIDDLE_PATH = getMockDynamicRouteSuffix('wrap/:p?/end'); it('removes a trailing-optional suffix when the optional segment is present', () => { getPathFromStateMock.mockReturnValue('r/123/opt-page/789'); diff --git a/tests/ui/AgentsPromoBannersTest.tsx b/tests/ui/AgentsPromoBannersTest.tsx index f259c50c60bc..7af9128d308b 100644 --- a/tests/ui/AgentsPromoBannersTest.tsx +++ b/tests/ui/AgentsPromoBannersTest.tsx @@ -53,9 +53,11 @@ jest.mock('@libs/actions/Policy/Rules', () => { }); jest.mock('@components/RenderHTML', () => { - const ReactMock = require('react') as typeof React; + const ReactMock = jest.requireActual('react'); - const {Text} = require('react-native') as {Text: React.ComponentType<{children?: React.ReactNode}>}; + // Keep the requireActual boundary's full module shape; this type-only import syntax is the repository-approved exception to the import-style lint rule. + // eslint-disable-next-line @typescript-eslint/consistent-type-imports + const {Text} = jest.requireActual('react-native'); return ({html}: {html: string}) => { const plainText = html.replaceAll(/<[^>]*>/g, ''); @@ -89,11 +91,11 @@ function buildPolicy(): Policy { } as Policy; } -const rulesRoute = { +const rulesRoute: React.ComponentProps['route'] = { key: 'rules-route', name: SCREENS.WORKSPACE.RULES, params: {policyID: POLICY_ID}, -} as never; +}; const renderRulesPage = () => render( diff --git a/tests/ui/AssignCardFeed.tsx b/tests/ui/AssignCardFeed.tsx index 3c80895ec03e..a10b91eaa76a 100644 --- a/tests/ui/AssignCardFeed.tsx +++ b/tests/ui/AssignCardFeed.tsx @@ -31,6 +31,7 @@ import {NavigationContainer} from '@react-navigation/native'; import React from 'react'; import Onyx from 'react-native-onyx'; +import createMock from '../utils/createMock'; import * as LHNTestUtils from '../utils/LHNTestUtils'; import * as TestHelper from '../utils/TestHelper'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; @@ -38,10 +39,10 @@ import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct' const WORKSPACE_ACCOUNT_ID = 5678; // Commercial feed (VCF) - has encrypted card numbers -const COMMERCIAL_FEED = `${CONST.COMPANY_CARD.FEED_BANK_NAME.VISA}#${WORKSPACE_ACCOUNT_ID}` as CompanyCardFeedWithDomainID; +const COMMERCIAL_FEED: CompanyCardFeedWithDomainID = `${CONST.COMPANY_CARD.FEED_BANK_NAME.VISA}#${WORKSPACE_ACCOUNT_ID}`; // Direct feed (Plaid) - card name equals card ID -const DIRECT_FEED = `plaid.ins_123#${WORKSPACE_ACCOUNT_ID}` as CompanyCardFeedWithDomainID; +const DIRECT_FEED = `plaid.ins_123#${WORKSPACE_ACCOUNT_ID}`; const CARD_ID = '1234'; @@ -144,6 +145,14 @@ const renderConfirmationStep = (initialParams: SettingsNavigatorParamList[typeof ); }; +const renderDirectConfirmationStep = (policyID: string) => + renderConfirmationStep({ + policyID, + // @ts-expect-error -- Plaid feed identifiers are accepted at runtime but are not represented by the company-feed union. + feed: DIRECT_FEED, + cardID: CARD_ID, + }); + /** * Creates mock assign card data for testing. * @@ -165,18 +174,22 @@ const createMockAssignCardData = (options: {feedType: 'commercial' | 'direct'; e // For direct feeds, encryptedCardNumber equals the card name // cspell:disable-next-line const encryptedCardNumber = feedType === 'commercial' ? 'v12:74E3CA3C4C0FA02FDCF754FDSFDSF' : 'Plaid Checking 0000'; - const bankName: CompanyCardFeed = feedType === 'commercial' ? CONST.COMPANY_CARD.FEED_BANK_NAME.VISA : ('plaid.ins_123' as CompanyCardFeed); + // The assignment flow accepts dynamic Plaid feed names at runtime, but the company-feed model only enumerates known feeds. + // @ts-expect-error -- This is the deliberate runtime Plaid-vs-model boundary covered by the direct-feed scenarios below. + const directFeedName: CompanyCardFeed = 'plaid.ins_123'; + const bankName: CompanyCardFeed = feedType === 'commercial' ? CONST.COMPANY_CARD.FEED_BANK_NAME.VISA : directFeedName; + const commonCardToAssign = { + bankName, + email, + cardName, + customCardName, + encryptedCardNumber, + dateOption: CONST.COMPANY_CARD.TRANSACTION_START_DATE_OPTIONS.FROM_BEGINNING, + startDate: '2024-12-27', + }; return { - cardToAssign: { - bankName, - email, - cardName, - customCardName, - encryptedCardNumber, - dateOption: CONST.COMPANY_CARD.TRANSACTION_START_DATE_OPTIONS.FROM_BEGINNING, - startDate: '2024-12-27', - }, + cardToAssign: commonCardToAssign, currentStep: CONST.COMPANY_CARD.STEP.CONFIRMATION, isEditing: false, }; @@ -192,10 +205,11 @@ describe('AssignCardFeed', () => { beforeEach(() => { // Mock the useResponsiveLayout hook to control layout behavior in tests. - jest.spyOn(useResponsiveLayoutModule, 'default').mockReturnValue({ + const wideLayout = createMock({ isSmallScreenWidth: false, shouldUseNarrowLayout: false, - } as ResponsiveLayoutResult); + }); + jest.spyOn(useResponsiveLayoutModule, 'default').mockReturnValue(wideLayout); }); afterEach(async () => { @@ -730,11 +744,7 @@ describe('AssignCardFeed', () => { await Onyx.merge(ONYXKEYS.ASSIGN_CARD, createMockAssignCardData({feedType: 'direct'})); }); - const {unmount} = renderConfirmationStep({ - policyID: policy.id, - feed: DIRECT_FEED, - cardID: CARD_ID, - }); + const {unmount} = renderDirectConfirmationStep(policy.id); await waitForBatchedUpdatesWithAct(); @@ -762,11 +772,7 @@ describe('AssignCardFeed', () => { await Onyx.merge(ONYXKEYS.ASSIGN_CARD, createMockAssignCardData({feedType: 'direct', cardName})); }); - const {unmount} = renderConfirmationStep({ - policyID: policy.id, - feed: DIRECT_FEED, - cardID: CARD_ID, - }); + const {unmount} = renderDirectConfirmationStep(policy.id); await waitForBatchedUpdatesWithAct(); @@ -839,11 +845,7 @@ describe('AssignCardFeed', () => { await Onyx.merge(ONYXKEYS.ASSIGN_CARD, mockData); }); - const {unmount} = renderConfirmationStep({ - policyID: policy.id, - feed: DIRECT_FEED, - cardID: CARD_ID, - }); + const {unmount} = renderDirectConfirmationStep(policy.id); await waitForBatchedUpdatesWithAct(); diff --git a/tests/ui/components/HeaderViewTest.tsx b/tests/ui/components/HeaderViewTest.tsx index c0a46284d1f4..e586d9e51f85 100644 --- a/tests/ui/components/HeaderViewTest.tsx +++ b/tests/ui/components/HeaderViewTest.tsx @@ -17,7 +17,7 @@ import type * as ReportType from '@userActions/Report'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {ReportAction} from '@src/types/onyx'; +import type {Report, ReportAction} from '@src/types/onyx'; import type {KeyValueMapping} from 'react-native-onyx'; @@ -25,6 +25,7 @@ import React from 'react'; import Onyx from 'react-native-onyx'; import {createRandomReport, createRegularChat} from '../../utils/collections/reports'; +import createMock from '../../utils/createMock'; import {translateLocal} from '../../utils/TestHelper'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; @@ -43,7 +44,7 @@ jest.mock('@userActions/Report', () => ({ joinRoom: jest.fn(), })); -const mockUseCurrentUserPersonalDetails = useCurrentUserPersonalDetails as jest.MockedFunction; +const mockUseCurrentUserPersonalDetails = jest.mocked(useCurrentUserPersonalDetails); const currentUserAccountID = 1; describe('HeaderView', () => { @@ -70,7 +71,8 @@ describe('HeaderView', () => { const chatReportID = '1'; const accountID = 2; let displayName = 'test'; - const report = { + const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${chatReportID}` as const; + const report: Report = { ...createRandomReport(Number(chatReportID), CONST.REPORT.CHAT_TYPE.INVOICE), invoiceReceiver: { accountID, @@ -78,14 +80,17 @@ describe('HeaderView', () => { }, }; await act(async () => { - await Onyx.multiSet({ - [`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`]: report, - [ONYXKEYS.PERSONAL_DETAILS_LIST]: { - [accountID]: { - displayName, + await Onyx.multiSet( + createMock({ + [reportKey]: report, + [ONYXKEYS.PERSONAL_DETAILS_LIST]: { + [accountID]: { + accountID, + displayName, + }, }, - }, - } as unknown as KeyValueMapping); + }), + ); }); render( @@ -178,11 +183,16 @@ describe('HeaderView', () => { }); await waitForBatchedUpdates(); - await Onyx.multiSet({ - [`${ONYXKEYS.COLLECTION.REPORT}${originalReportID}`]: originalReport, - [`${ONYXKEYS.COLLECTION.REPORT}${parentReportID}`]: parentReport, - [`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`]: threadReport, - } as unknown as KeyValueMapping); + const originalReportKey = `${ONYXKEYS.COLLECTION.REPORT}${originalReportID}` as const; + const parentReportKey = `${ONYXKEYS.COLLECTION.REPORT}${parentReportID}` as const; + const threadReportKey = `${ONYXKEYS.COLLECTION.REPORT}${threadReportID}` as const; + await Onyx.multiSet( + createMock({ + [originalReportKey]: originalReport, + [parentReportKey]: parentReport, + [threadReportKey]: threadReport, + }), + ); render( diff --git a/tests/ui/components/SettlementButtonTest.tsx b/tests/ui/components/SettlementButtonTest.tsx index aa88c6e256ed..0cb5320fd372 100644 --- a/tests/ui/components/SettlementButtonTest.tsx +++ b/tests/ui/components/SettlementButtonTest.tsx @@ -24,6 +24,7 @@ import type {ValueOf} from 'type-fest'; import React from 'react'; import Onyx from 'react-native-onyx'; +import createMock from '../../utils/createMock'; import {translateLocal} from '../../utils/TestHelper'; import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; @@ -597,14 +598,14 @@ describe('SettlementButton', () => { report: expenseReport, chatReport: createChatReport(), policy: createTestPolicy({ - achAccount: { + achAccount: createMock>({ bankAccountID: BANK_ACCOUNT_ID, routingNumber: '123456789', addressName: 'Test Business', bankName: 'Test Bank', reimburser: 'reimburser@test.com', state: CONST.BANK_ACCOUNT.STATE.OPEN, - } as Policy['achAccount'], + }), }), lastPaymentMethod: { [POLICY_ID]: { @@ -637,14 +638,14 @@ describe('SettlementButton', () => { report: expenseReport, chatReport: createChatReport(), policy: createTestPolicy({ - achAccount: { + achAccount: createMock>({ bankAccountID: BANK_ACCOUNT_ID, routingNumber: '123456789', addressName: 'Test Business', bankName: 'Test Bank', reimburser: 'reimburser@test.com', state: CONST.BANK_ACCOUNT.STATE.OPEN, - } as Policy['achAccount'], + }), }), bankAccountList: createBankAccountList('3333'), // No lastPaymentMethod → hasIntentToPay = true (achAccount.state === OPEN && !lastPaymentMethod) @@ -1119,7 +1120,7 @@ describe('SettlementButton', () => { describe('createWorkspace regression test', () => { it('should NOT call createWorkspace during render for invoice scenarios', async () => { - const createWorkspaceMock = createWorkspace as jest.Mock; + const createWorkspaceMock = jest.mocked(createWorkspace); createWorkspaceMock.mockClear(); const invoiceReport = createInvoiceReport(); diff --git a/tests/unit/ReportActionsListPaddingViewTest.tsx b/tests/unit/ReportActionsListPaddingViewTest.tsx index 8c91fa65dcc1..60469ba4963d 100644 --- a/tests/unit/ReportActionsListPaddingViewTest.tsx +++ b/tests/unit/ReportActionsListPaddingViewTest.tsx @@ -4,6 +4,7 @@ import Text from '@components/Text'; import useReportRecipientLocalTime from '@hooks/useReportRecipientLocalTime'; +import {isRecord} from '@libs/ObjectUtils'; import {canUserPerformWriteAction} from '@libs/ReportUtils'; import ReportActionsListPaddingView from '@pages/inbox/report/ReportActionsListPaddingView'; @@ -12,7 +13,7 @@ import useShouldShowComposerForActiveEditDraft from '@pages/inbox/report/useShou import CONST from '@src/CONST'; import type {Report} from '@src/types/onyx'; -import type {ViewStyle} from 'react-native'; +import type {StyleProp, ViewStyle} from 'react-native'; import React from 'react'; import {StyleSheet} from 'react-native'; @@ -32,19 +33,19 @@ jest.mock('@hooks/useThemeStyles', () => () => ({ pb4: {paddingBottom: PB4_PADDING_BOTTOM}, })); -const mockUseReportRecipientLocalTime = useReportRecipientLocalTime as jest.MockedFunction; -const mockUseShouldShowComposerForActiveEditDraft = useShouldShowComposerForActiveEditDraft as jest.MockedFunction; -const mockCanUserPerformWriteAction = canUserPerformWriteAction as jest.MockedFunction; +const mockUseReportRecipientLocalTime = jest.mocked(useReportRecipientLocalTime); +const mockUseShouldShowComposerForActiveEditDraft = jest.mocked(useShouldShowComposerForActiveEditDraft); +const mockCanUserPerformWriteAction = jest.mocked(canUserPerformWriteAction); const CURRENT_USER_ACCOUNT_ID = 1; -const REPORT = { +const REPORT: Report = { reportID: '1', type: CONST.REPORT.TYPE.CHAT, participants: { [CURRENT_USER_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}, }, -} as Report; +}; type PaddingScenario = { canShowRecipientLocalTime: boolean; @@ -91,14 +92,27 @@ function renderPaddingView(isReportArchived = false) { ); } +type PaddingStyle = Pick; + +function isPaddingStyleProp(value: unknown): value is StyleProp { + if (value === null || value === undefined || value === false || typeof value === 'number') { + return true; + } + if (Array.isArray(value)) { + return value.every((entry: unknown) => isPaddingStyleProp(entry)); + } + return isRecord(value) && (!('paddingBottom' in value) || typeof value.paddingBottom === 'number'); +} + function getPaddingBottom(toJSON: ReturnType['toJSON']) { const root = toJSON(); - if (!root || typeof root !== 'object' || !('props' in root)) { + if (!root || !isRecord(root) || !('props' in root) || !isRecord(root.props)) { return undefined; } - return StyleSheet.flatten(root.props?.style as ViewStyle)?.paddingBottom; + const style = root.props.style; + return isPaddingStyleProp(style) ? StyleSheet.flatten(style)?.paddingBottom : undefined; } describe('ReportActionsListPaddingView', () => { diff --git a/tests/unit/SearchParserTest.ts b/tests/unit/SearchParserTest.ts index f53542dc1f91..a143b6c294a8 100644 --- a/tests/unit/SearchParserTest.ts +++ b/tests/unit/SearchParserTest.ts @@ -1,7 +1,7 @@ -import type {SearchQueryJSON} from '@components/Search/types'; - +import {isRecord} from '@libs/ObjectUtils'; import {parse} from '@libs/SearchParser/searchParser'; +import type {SearchQueryJSON} from '@src/components/Search/types'; import CONST from '@src/CONST'; import parserCommonTests from '../utils/fixtures/searchParsersCommonQueries'; @@ -1520,30 +1520,69 @@ const limitTests = [ }, ]; +type ParsedRawFilter = NonNullable[number]; +type ParsedSearchQuery = Pick; + +function isParsedRawFilter(value: unknown): value is ParsedRawFilter { + if (!isRecord(value)) { + return false; + } + + const filterValue = value.value; + const hasValidValue = typeof filterValue === 'string' || (Array.isArray(filterValue) && filterValue.every((item: unknown) => typeof item === 'string')); + + return ( + typeof value.key === 'string' && + Object.values(CONST.SEARCH.SYNTAX_OPERATORS).some((operator) => operator === value.operator) && + hasValidValue && + (value.isDefault === undefined || typeof value.isDefault === 'boolean') + ); +} + +function isParsedSearchQuery(value: unknown): value is ParsedSearchQuery { + return isRecord(value) && (value.rawFilterList === undefined || (Array.isArray(value.rawFilterList) && value.rawFilterList.every(isParsedRawFilter))); +} + describe('search parser', () => { test.each(tests)(`parsing: $query`, ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + const parsed: unknown = parse(query); + if (!isParsedSearchQuery(parsed)) { + throw new Error('Expected search parser to return a typed search query AST'); + } + const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); }); }); describe('Testing search parser with special characters and wrapped in quotes.', () => { test.each(keywordTests)(`parsing: $query`, ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + const parsed: unknown = parse(query); + if (!isParsedSearchQuery(parsed)) { + throw new Error('Expected search parser to return a typed search query AST'); + } + const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); }); }); describe('search parser - view and groupBy defaults', () => { test.each(viewAndGroupByTests)(`parsing: $query`, ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + const parsed: unknown = parse(query); + if (!isParsedSearchQuery(parsed)) { + throw new Error('Expected search parser to return a typed search query AST'); + } + const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); }); }); describe('search parser - limit filter', () => { test.each(limitTests)('$description: $query', ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + const parsed: unknown = parse(query); + if (!isParsedSearchQuery(parsed)) { + throw new Error('Expected search parser to return a typed search query AST'); + } + const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); }); }); diff --git a/tests/unit/SuggestionMentionTest.tsx b/tests/unit/SuggestionMentionTest.tsx index b833a5e5ae1d..aebe9ac895eb 100644 --- a/tests/unit/SuggestionMentionTest.tsx +++ b/tests/unit/SuggestionMentionTest.tsx @@ -1,6 +1,7 @@ import {act, render, waitFor} from '@testing-library/react-native'; import type {TextSelection} from '@components/Composer/types'; +import PlaceholderIcon from '@components/Icon/PlaceholderIcon'; import type {Mention} from '@components/MentionSuggestions'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; @@ -15,6 +16,7 @@ import usePolicy from '@hooks/usePolicy'; import SuggestionMention from '@pages/inbox/report/ReportActionCompose/SuggestionMention'; +import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {PersonalDetailsList, PolicyEmployeeList, Report} from '@src/types/onyx'; @@ -23,6 +25,7 @@ import type {UseOnyxResult} from 'react-native-onyx'; import React from 'react'; import createRandomPolicy from '../utils/collections/policies'; +import createMock from '../utils/createMock'; type MentionSuggestionsProps = { mentions: Mention[]; @@ -32,11 +35,22 @@ type MentionSuggestionsProps = { const mockMentionSuggestionsSpy = jest.fn(); const mockSetHighlightedMentionIndex = jest.fn(); -const mockIcons = {Megaphone: 'megaphone', FallbackAvatar: 'fallback'}; -const mockLocalize = { - translate: (key: string) => key, +const mockIcons = createMock>({Megaphone: PlaceholderIcon, FallbackAvatar: PlaceholderIcon}); +// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Translation interpolation parameters are intentionally ignored by this mock. +const mockTranslate: ReturnType['translate'] = (key, ..._parameters) => String(key); +const mockLocalize: ReturnType = { + translate: mockTranslate, + numberFormat: () => '', + getLocalDateFromDatetime: () => new Date(), + datetimeToRelative: () => '', + datetimeToCalendarTime: () => '', formatPhoneNumber: (value: string) => value, + toLocaleDigit: () => '', + toLocaleOrdinal: () => '', + fromLocaleDigit: () => '', localeCompare: (first: string, second: string) => first.localeCompare(second), + formatTravelDate: () => '', + preferredLocale: CONST.LOCALES.DEFAULT, }; const mockReports = {}; @@ -115,6 +129,23 @@ function getLastMentionSuggestionsProps(): MentionSuggestionsProps { return props; } +type UseOnyxCall = Parameters; +type UseOnyxCallResult = ReturnType; + +const mockUseOnyxImplementation = (...args: UseOnyxCall): UseOnyxCallResult => { + const [key] = args; + if (key === ONYXKEYS.CONCIERGE_REPORT_ID) { + return createOnyxResult(''); + } + if (key === ONYXKEYS.COLLECTION.REPORT) { + return createOnyxResult(mockReports); + } + if (typeof key === 'string' && key.startsWith(ONYXKEYS.COLLECTION.REPORT)) { + return createOnyxResult(mockCurrentReport); + } + return createOnyxResult(undefined); +}; + describe('SuggestionMention', () => { beforeEach(() => { mockMentionSuggestionsSpy.mockClear(); @@ -131,21 +162,9 @@ describe('SuggestionMention', () => { callbackRef.current = callback; return React.useCallback((...args: unknown[]) => callbackRef.current(...args), []) as typeof callback; }); - mockUseMemoizedLazyExpensifyIcons.mockImplementation((() => mockIcons) as unknown as typeof useMemoizedLazyExpensifyIcons); - mockUseLocalize.mockImplementation(() => mockLocalize as ReturnType); - mockUseOnyx.mockImplementation(((...args: Parameters) => { - const key = args[0]; - if (key === ONYXKEYS.CONCIERGE_REPORT_ID) { - return createOnyxResult(''); - } - if (key === ONYXKEYS.COLLECTION.REPORT) { - return createOnyxResult(mockReports); - } - if (typeof key === 'string' && key.startsWith(ONYXKEYS.COLLECTION.REPORT)) { - return createOnyxResult(mockCurrentReport); - } - return createOnyxResult(undefined); - }) as typeof useOnyx); + mockUseMemoizedLazyExpensifyIcons.mockImplementation(() => mockIcons); + mockUseLocalize.mockImplementation(() => createMock>(mockLocalize)); + mockUseOnyx.mockImplementation(mockUseOnyxImplementation); mockUsePolicy.mockReturnValue(undefined); }); @@ -275,9 +294,10 @@ describe('SuggestionMention', () => { }; const buildReportWithParticipant = (overrides: Partial): Report => { - const participants: Record = {}; - participants[PARTICIPANT_ACCOUNT_ID] = {notificationPreference: 'always'}; - return {...overrides, participants} as unknown as Report; + const participants = { + [PARTICIPANT_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}, + }; + return createMock({...overrides, participants}); }; it('weights report participants above policy employees and everyone else for a group chat', async () => { diff --git a/tests/unit/showReportActionNotificationTest.ts b/tests/unit/showReportActionNotificationTest.ts index 942c7889bb9c..f29092b3a01d 100644 --- a/tests/unit/showReportActionNotificationTest.ts +++ b/tests/unit/showReportActionNotificationTest.ts @@ -1,11 +1,15 @@ -import {afterEach, beforeAll, beforeEach, describe, expect, it, jest} from '@jest/globals'; +import {afterEach, beforeAll, beforeEach, describe, expect, it} from '@jest/globals'; + +import type {LocalNotificationModule, LocalNotificationModifiedExpenseParams} from '@libs/Notification/LocalNotification/types'; import CONST from '@src/CONST'; import * as Report from '@src/libs/actions/Report'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {ReportAttributesDerivedValue} from '@src/types/onyx'; import Onyx from 'react-native-onyx'; +import createMock from '../utils/createMock'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; jest.mock('@libs/ActiveClientManager', () => ({ @@ -14,13 +18,17 @@ jest.mock('@libs/ActiveClientManager', () => ({ init: jest.fn(), })); -const mockShowModifiedExpenseNotification = jest.fn(); -const mockShowCommentNotification = jest.fn(); +const mockShowModifiedExpenseNotification = jest.fn(); +const mockShowCommentNotification = jest.fn>(); jest.mock('@libs/Notification/LocalNotification', () => ({ __esModule: true, default: { - showModifiedExpenseNotification: (...args: unknown[]) => mockShowModifiedExpenseNotification(...args), - showCommentNotification: (...args: unknown[]) => mockShowCommentNotification(...args), + showModifiedExpenseNotification: (params: LocalNotificationModifiedExpenseParams) => { + mockShowModifiedExpenseNotification(params); + }, + showCommentNotification: (...args: Parameters) => { + mockShowCommentNotification(...args); + }, showUpdateAvailableNotification: jest.fn(), clearReportNotifications: jest.fn(), }, @@ -46,7 +54,7 @@ const CURRENT_USER_ACCOUNT_ID = 1; const CURRENT_USER_LOGIN = 'test@user.com'; const REPORT_ID = '100'; const OTHER_USER_ACCOUNT_ID = 2; -const REPORT_ATTRIBUTES = {someReportKey: {reportName: 'Test Report'}} as Record; +const REPORT_ATTRIBUTES = createMock({someReportKey: {reportName: 'Test Report'}}); describe('showReportActionNotification', () => { beforeAll(() => { @@ -94,12 +102,15 @@ describe('showReportActionNotification', () => { undefined, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_LOGIN, - REPORT_ATTRIBUTES as Parameters[5], + REPORT_ATTRIBUTES, ); await waitForBatchedUpdates(); expect(mockShowModifiedExpenseNotification).toHaveBeenCalledTimes(1); - const callArgs = mockShowModifiedExpenseNotification.mock.calls.at(0)?.at(0) as Record; + const callArgs = mockShowModifiedExpenseNotification.mock.calls.at(0)?.at(0); + if (!callArgs) { + throw new Error('Modified expense notification arguments are missing'); + } expect(callArgs.reportAttributes).toBe(REPORT_ATTRIBUTES); expect(mockShowCommentNotification).not.toHaveBeenCalled(); }); @@ -127,7 +138,10 @@ describe('showReportActionNotification', () => { await waitForBatchedUpdates(); expect(mockShowModifiedExpenseNotification).toHaveBeenCalledTimes(1); - const callArgs = mockShowModifiedExpenseNotification.mock.calls.at(0)?.at(0) as Record; + const callArgs = mockShowModifiedExpenseNotification.mock.calls.at(0)?.at(0); + if (!callArgs) { + throw new Error('Modified expense notification arguments are missing'); + } expect(callArgs.reportAttributes).toBeUndefined(); expect(mockShowCommentNotification).not.toHaveBeenCalled(); }); @@ -150,7 +164,7 @@ describe('showReportActionNotification', () => { undefined, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_LOGIN, - REPORT_ATTRIBUTES as Parameters[5], + REPORT_ATTRIBUTES, ); await waitForBatchedUpdates(); From 638264a4402d8380e1fccaf6f69ffae922bbc8fb Mon Sep 17 00:00:00 2001 From: KJ21-ENG <140263938+KJ21-ENG@users.noreply.github.com> Date: Fri, 31 Jul 2026 03:54:25 +0530 Subject: [PATCH 2/3] Fix cleanup review findings --- .../tests/resolveCanvasSize.test.ts | 2 - tests/ui/AgentsPromoBannersTest.tsx | 11 ++- tests/unit/SearchParserTest.ts | 40 ++-------- tests/unit/SuggestionMentionTest.tsx | 78 +++++++++---------- 4 files changed, 54 insertions(+), 77 deletions(-) diff --git a/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts b/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts index 05c7363c5aa3..c0972c4244c6 100644 --- a/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts +++ b/server/victory-chart-renderer/tests/resolveCanvasSize.test.ts @@ -1,5 +1,3 @@ -/// - import type {TNode} from 'react-native-render-html'; import {describe, expect, test} from 'bun:test'; diff --git a/tests/ui/AgentsPromoBannersTest.tsx b/tests/ui/AgentsPromoBannersTest.tsx index 7af9128d308b..47b9d0099445 100644 --- a/tests/ui/AgentsPromoBannersTest.tsx +++ b/tests/ui/AgentsPromoBannersTest.tsx @@ -12,6 +12,8 @@ import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; import type {Policy} from '@src/types/onyx'; +import type * as ReactIs from 'react-is'; + import React from 'react'; import Onyx from 'react-native-onyx'; @@ -55,9 +57,12 @@ jest.mock('@libs/actions/Policy/Rules', () => { jest.mock('@components/RenderHTML', () => { const ReactMock = jest.requireActual('react'); - // Keep the requireActual boundary's full module shape; this type-only import syntax is the repository-approved exception to the import-style lint rule. - // eslint-disable-next-line @typescript-eslint/consistent-type-imports - const {Text} = jest.requireActual('react-native'); + const {isValidElementType} = jest.requireActual('react-is'); + const reactNativeActual: unknown = jest.requireActual('react-native'); + if (typeof reactNativeActual !== 'object' || reactNativeActual === null || !('Text' in reactNativeActual) || !isValidElementType(reactNativeActual.Text)) { + throw new Error('Expected react-native to expose a valid Text element type'); + } + const {Text} = reactNativeActual; return ({html}: {html: string}) => { const plainText = html.replaceAll(/<[^>]*>/g, ''); diff --git a/tests/unit/SearchParserTest.ts b/tests/unit/SearchParserTest.ts index a143b6c294a8..3e9a7cfb576b 100644 --- a/tests/unit/SearchParserTest.ts +++ b/tests/unit/SearchParserTest.ts @@ -1,7 +1,6 @@ import {isRecord} from '@libs/ObjectUtils'; import {parse} from '@libs/SearchParser/searchParser'; -import type {SearchQueryJSON} from '@src/components/Search/types'; import CONST from '@src/CONST'; import parserCommonTests from '../utils/fixtures/searchParsersCommonQueries'; @@ -1520,34 +1519,11 @@ const limitTests = [ }, ]; -type ParsedRawFilter = NonNullable[number]; -type ParsedSearchQuery = Pick; - -function isParsedRawFilter(value: unknown): value is ParsedRawFilter { - if (!isRecord(value)) { - return false; - } - - const filterValue = value.value; - const hasValidValue = typeof filterValue === 'string' || (Array.isArray(filterValue) && filterValue.every((item: unknown) => typeof item === 'string')); - - return ( - typeof value.key === 'string' && - Object.values(CONST.SEARCH.SYNTAX_OPERATORS).some((operator) => operator === value.operator) && - hasValidValue && - (value.isDefault === undefined || typeof value.isDefault === 'boolean') - ); -} - -function isParsedSearchQuery(value: unknown): value is ParsedSearchQuery { - return isRecord(value) && (value.rawFilterList === undefined || (Array.isArray(value.rawFilterList) && value.rawFilterList.every(isParsedRawFilter))); -} - describe('search parser', () => { test.each(tests)(`parsing: $query`, ({query, expected}) => { const parsed: unknown = parse(query); - if (!isParsedSearchQuery(parsed)) { - throw new Error('Expected search parser to return a typed search query AST'); + if (!isRecord(parsed)) { + throw new Error('Expected search parser to return a record'); } const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); @@ -1557,8 +1533,8 @@ describe('search parser', () => { describe('Testing search parser with special characters and wrapped in quotes.', () => { test.each(keywordTests)(`parsing: $query`, ({query, expected}) => { const parsed: unknown = parse(query); - if (!isParsedSearchQuery(parsed)) { - throw new Error('Expected search parser to return a typed search query AST'); + if (!isRecord(parsed)) { + throw new Error('Expected search parser to return a record'); } const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); @@ -1568,8 +1544,8 @@ describe('Testing search parser with special characters and wrapped in quotes.', describe('search parser - view and groupBy defaults', () => { test.each(viewAndGroupByTests)(`parsing: $query`, ({query, expected}) => { const parsed: unknown = parse(query); - if (!isParsedSearchQuery(parsed)) { - throw new Error('Expected search parser to return a typed search query AST'); + if (!isRecord(parsed)) { + throw new Error('Expected search parser to return a record'); } const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); @@ -1579,8 +1555,8 @@ describe('search parser - view and groupBy defaults', () => { describe('search parser - limit filter', () => { test.each(limitTests)('$description: $query', ({query, expected}) => { const parsed: unknown = parse(query); - if (!isParsedSearchQuery(parsed)) { - throw new Error('Expected search parser to return a typed search query AST'); + if (!isRecord(parsed)) { + throw new Error('Expected search parser to return a record'); } const {rawFilterList, ...resultWithoutRawFilters} = parsed; expect(resultWithoutRawFilters).toEqual(expected); diff --git a/tests/unit/SuggestionMentionTest.tsx b/tests/unit/SuggestionMentionTest.tsx index aebe9ac895eb..41feb9709957 100644 --- a/tests/unit/SuggestionMentionTest.tsx +++ b/tests/unit/SuggestionMentionTest.tsx @@ -11,7 +11,6 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails' import useDebounce from '@hooks/useDebounce'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; -import useOnyx from '@hooks/useOnyx'; import usePolicy from '@hooks/usePolicy'; import SuggestionMention from '@pages/inbox/report/ReportActionCompose/SuggestionMention'; @@ -20,9 +19,8 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {PersonalDetailsList, PolicyEmployeeList, Report} from '@src/types/onyx'; -import type {UseOnyxResult} from 'react-native-onyx'; - import React from 'react'; +import Onyx from 'react-native-onyx'; import createRandomPolicy from '../utils/collections/policies'; import createMock from '../utils/createMock'; @@ -36,8 +34,14 @@ type MentionSuggestionsProps = { const mockMentionSuggestionsSpy = jest.fn(); const mockSetHighlightedMentionIndex = jest.fn(); const mockIcons = createMock>({Megaphone: PlaceholderIcon, FallbackAvatar: PlaceholderIcon}); -// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Translation interpolation parameters are intentionally ignored by this mock. -const mockTranslate: ReturnType['translate'] = (key, ..._parameters) => String(key); +const mockTranslate: ReturnType['translate'] = (key, ...parameters) => { + for (const parameter of parameters) { + if (parameter) { + return String(key); + } + } + return String(key); +}; const mockLocalize: ReturnType = { translate: mockTranslate, numberFormat: () => '', @@ -52,14 +56,8 @@ const mockLocalize: ReturnType = { formatTravelDate: () => '', preferredLocale: CONST.LOCALES.DEFAULT, }; -const mockReports = {}; let mockPersonalDetails: PersonalDetailsList = {}; -let mockCurrentReport: Report | undefined; - -function createOnyxResult(value: NonNullable | undefined): UseOnyxResult { - return [value, {status: 'loaded'}]; -} jest.mock('@components/MentionSuggestions', () => { const ReactLib = jest.requireActual('react'); @@ -87,7 +85,6 @@ jest.mock('@hooks/useLazyAsset', () => ({ useMemoizedLazyExpensifyIcons: jest.fn(), })); jest.mock('@hooks/useLocalize', () => jest.fn()); -jest.mock('@hooks/useOnyx', () => jest.fn()); jest.mock('@hooks/usePolicy', () => jest.fn()); const mockUsePersonalDetails = jest.mocked(usePersonalDetails); @@ -97,7 +94,6 @@ const mockUseCurrentUserPersonalDetails = jest.mocked(useCurrentUserPersonalDeta const mockUseDebounce = jest.mocked(useDebounce); const mockUseMemoizedLazyExpensifyIcons = jest.mocked(useMemoizedLazyExpensifyIcons); const mockUseLocalize = jest.mocked(useLocalize); -const mockUseOnyx = jest.mocked(useOnyx); const mockUsePolicy = jest.mocked(usePolicy); function renderSuggestionMention(value: string, updateComment = jest.fn(), selection: TextSelection = {start: value.length, end: value.length}) { @@ -129,29 +125,11 @@ function getLastMentionSuggestionsProps(): MentionSuggestionsProps { return props; } -type UseOnyxCall = Parameters; -type UseOnyxCallResult = ReturnType; - -const mockUseOnyxImplementation = (...args: UseOnyxCall): UseOnyxCallResult => { - const [key] = args; - if (key === ONYXKEYS.CONCIERGE_REPORT_ID) { - return createOnyxResult(''); - } - if (key === ONYXKEYS.COLLECTION.REPORT) { - return createOnyxResult(mockReports); - } - if (typeof key === 'string' && key.startsWith(ONYXKEYS.COLLECTION.REPORT)) { - return createOnyxResult(mockCurrentReport); - } - return createOnyxResult(undefined); -}; - describe('SuggestionMention', () => { beforeEach(() => { mockMentionSuggestionsSpy.mockClear(); mockSetHighlightedMentionIndex.mockClear(); mockPersonalDetails = {}; - mockCurrentReport = undefined; mockUsePersonalDetails.mockImplementation(() => mockPersonalDetails); mockUseArrowKeyFocusManager.mockReturnValue([0, mockSetHighlightedMentionIndex]); @@ -164,10 +142,15 @@ describe('SuggestionMention', () => { }); mockUseMemoizedLazyExpensifyIcons.mockImplementation(() => mockIcons); mockUseLocalize.mockImplementation(() => createMock>(mockLocalize)); - mockUseOnyx.mockImplementation(mockUseOnyxImplementation); mockUsePolicy.mockReturnValue(undefined); }); + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + it('shows user mention suggestions when prefix has a trailing dot', async () => { mockPersonalDetails = {}; mockPersonalDetails[2] = { @@ -302,13 +285,18 @@ describe('SuggestionMention', () => { it('weights report participants above policy employees and everyone else for a group chat', async () => { setupPersonalDetails(); - mockUseCurrentReportIDState.mockReturnValue({currentReportID: 'group1'}); - mockCurrentReport = buildReportWithParticipant({ + const currentReportID = 'group1'; + mockUseCurrentReportIDState.mockReturnValue({currentReportID, currentRHPReportID: ''}); + const report = buildReportWithParticipant({ reportID: 'group1', - chatType: 'group' as Report['chatType'], + chatType: CONST.REPORT.CHAT_TYPE.GROUP, }); mockUsePolicy.mockReturnValue(policyWithEmployeeUb); + await act(async () => { + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${currentReportID}`, report); + }); + renderSuggestionMention('@u'); await waitFor(() => expect(mockMentionSuggestionsSpy).toHaveBeenCalled()); @@ -319,14 +307,19 @@ describe('SuggestionMention', () => { it('weights details when the current report belongs to the active workspace', async () => { setupPersonalDetails(); - mockUseCurrentReportIDState.mockReturnValue({currentReportID: 'wsp1'}); - mockCurrentReport = buildReportWithParticipant({ + const currentReportID = 'wsp1'; + mockUseCurrentReportIDState.mockReturnValue({currentReportID, currentRHPReportID: ''}); + const report = buildReportWithParticipant({ reportID: 'wsp1', - chatType: 'policyExpenseChat' as Report['chatType'], + chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, policyID: 'policyID', }); mockUsePolicy.mockReturnValue(policyWithEmployeeUb); + await act(async () => { + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${currentReportID}`, report); + }); + renderSuggestionMention('@u'); await waitFor(() => expect(mockMentionSuggestionsSpy).toHaveBeenCalled()); @@ -337,10 +330,15 @@ describe('SuggestionMention', () => { it('skips weighting for a 1:1 DM and falls back to alphabetical order', async () => { setupPersonalDetails(); - mockUseCurrentReportIDState.mockReturnValue({currentReportID: 'dm1'}); - mockCurrentReport = buildReportWithParticipant({reportID: 'dm1'}); + const currentReportID = 'dm1'; + mockUseCurrentReportIDState.mockReturnValue({currentReportID, currentRHPReportID: ''}); + const report = buildReportWithParticipant({reportID: 'dm1'}); mockUsePolicy.mockReturnValue(policyWithEmployeeUb); + await act(async () => { + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${currentReportID}`, report); + }); + renderSuggestionMention('@u'); await waitFor(() => expect(mockMentionSuggestionsSpy).toHaveBeenCalled()); From dc63a8f5a52d4af9c2debb8467419e76fe8e2eec Mon Sep 17 00:00:00 2001 From: KJ21-ENG <140263938+KJ21-ENG@users.noreply.github.com> Date: Tue, 4 Aug 2026 01:23:30 +0530 Subject: [PATCH 3/3] Fix cleanup review findings --- tests/navigation/useDynamicBackPathTests.ts | 83 +++++++++++++------ .../unit/ReportActionsListPaddingViewTest.tsx | 29 +++---- tests/unit/SearchParserTest.ts | 37 +++------ 3 files changed, 82 insertions(+), 67 deletions(-) diff --git a/tests/navigation/useDynamicBackPathTests.ts b/tests/navigation/useDynamicBackPathTests.ts index 3629da24b624..88c3d7f73162 100644 --- a/tests/navigation/useDynamicBackPathTests.ts +++ b/tests/navigation/useDynamicBackPathTests.ts @@ -2,9 +2,6 @@ import {renderHook} from '@testing-library/react-native'; import useDynamicBackPath from '@hooks/useDynamicBackPath'; -import isDynamicRouteSuffix from '@libs/Navigation/helpers/dynamicRoutesUtils/isDynamicRouteSuffix'; - -import type {DynamicRouteSuffix} from '@src/ROUTES'; import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; jest.mock('@hooks/useRootNavigationState', () => jest.fn()); @@ -30,12 +27,13 @@ jest.mock('@src/ROUTES', () => ({ const useRootNavigationStateMock = jest.requireMock('@hooks/useRootNavigationState'); const getPathFromStateMock: jest.Mock = jest.requireMock('@libs/Navigation/helpers/getPathFromState'); -function getMockDynamicRouteSuffix(path: string): DynamicRouteSuffix { - if (!isDynamicRouteSuffix(path)) { - throw new Error(`Expected mocked dynamic route suffix to be recognized: ${path}`); - } - return path; -} +const GENERATED_ROUTE_PATHS = [ + DYNAMIC_ROUTES.VERIFY_ACCOUNT.path, + 'custom-test-route', + DYNAMIC_ROUTES.ADDRESS_COUNTRY.path, + DYNAMIC_ROUTES.FLAG_COMMENT.path, + 'member-details/:accountID', +] as const; describe('useDynamicBackPath', () => { beforeEach(() => { @@ -46,21 +44,28 @@ describe('useDynamicBackPath', () => { it('should return HOME when path is null or undefined', () => { getPathFromStateMock.mockReturnValue(undefined); - const {result} = renderHook(() => useDynamicBackPath('verify-account')); + const {result} = renderHook(() => useDynamicBackPath(DYNAMIC_ROUTES.VERIFY_ACCOUNT.path)); expect(result.current).toBe(ROUTES.HOME); }); - for (const {path} of Object.values(DYNAMIC_ROUTES)) { - if (path.includes('?')) { - continue; - } + for (const path of GENERATED_ROUTE_PATHS) { it(`should remove suffix ${path} when it is the last segment`, () => { const pathPrefix = 'settings/wallet'; const fullPath = `${pathPrefix}/${path}`; getPathFromStateMock.mockReturnValue(fullPath); - const {result} = renderHook(() => useDynamicBackPath(path)); + const {result} = renderHook(() => { + if (path === 'custom-test-route') { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(path); + } + if (path === 'member-details/:accountID') { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(path); + } + return useDynamicBackPath(path); + }); expect(result.current).toBe(pathPrefix); }); @@ -106,13 +111,16 @@ describe('useDynamicBackPath', () => { expect(result.current).toBe('settings/wallet'); }); - const FLAG_COMMENT_PATH = getMockDynamicRouteSuffix('flag/:reportID/:reportActionID'); - const MEMBER_DETAILS_PATH = getMockDynamicRouteSuffix('member-details/:accountID'); + const FLAG_COMMENT_PATH = DYNAMIC_ROUTES.FLAG_COMMENT.path; + const MEMBER_DETAILS_PATH = 'member-details/:accountID'; it('should remove parametric suffix with single param', () => { getPathFromStateMock.mockReturnValue('r/123/members/member-details/456'); - const {result} = renderHook(() => useDynamicBackPath(MEMBER_DETAILS_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(MEMBER_DETAILS_PATH); + }); expect(result.current).toBe('r/123/members'); }); @@ -150,13 +158,16 @@ describe('useDynamicBackPath', () => { }); describe('optional path params', () => { - const OPT_TRAILING_PATH = getMockDynamicRouteSuffix('opt-page/:id?'); - const OPT_MIDDLE_PATH = getMockDynamicRouteSuffix('wrap/:p?/end'); + const OPT_TRAILING_PATH = 'opt-page/:id?'; + const OPT_MIDDLE_PATH = 'wrap/:p?/end'; it('removes a trailing-optional suffix when the optional segment is present', () => { getPathFromStateMock.mockReturnValue('r/123/opt-page/789'); - const {result} = renderHook(() => useDynamicBackPath(OPT_TRAILING_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_TRAILING_PATH); + }); expect(result.current).toBe('r/123'); }); @@ -164,7 +175,10 @@ describe('useDynamicBackPath', () => { it('removes a trailing-optional suffix when the optional segment is absent', () => { getPathFromStateMock.mockReturnValue('r/123/opt-page'); - const {result} = renderHook(() => useDynamicBackPath(OPT_TRAILING_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_TRAILING_PATH); + }); expect(result.current).toBe('r/123'); }); @@ -172,7 +186,10 @@ describe('useDynamicBackPath', () => { it('removes a middle-optional suffix when the optional segment is present', () => { getPathFromStateMock.mockReturnValue('r/123/wrap/x/end'); - const {result} = renderHook(() => useDynamicBackPath(OPT_MIDDLE_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_MIDDLE_PATH); + }); expect(result.current).toBe('r/123'); }); @@ -180,7 +197,10 @@ describe('useDynamicBackPath', () => { it('removes a middle-optional suffix when the optional segment is absent', () => { getPathFromStateMock.mockReturnValue('r/123/wrap/end'); - const {result} = renderHook(() => useDynamicBackPath(OPT_MIDDLE_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_MIDDLE_PATH); + }); expect(result.current).toBe('r/123'); }); @@ -188,7 +208,10 @@ describe('useDynamicBackPath', () => { it('preserves query params when stripping optional present-form', () => { getPathFromStateMock.mockReturnValue('r/123/opt-page/789?tab=details'); - const {result} = renderHook(() => useDynamicBackPath(OPT_TRAILING_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_TRAILING_PATH); + }); expect(result.current).toBe('r/123?tab=details'); }); @@ -196,7 +219,10 @@ describe('useDynamicBackPath', () => { it('preserves query params when stripping optional absent-form', () => { getPathFromStateMock.mockReturnValue('r/123/opt-page?tab=details'); - const {result} = renderHook(() => useDynamicBackPath(OPT_TRAILING_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_TRAILING_PATH); + }); expect(result.current).toBe('r/123?tab=details'); }); @@ -204,7 +230,10 @@ describe('useDynamicBackPath', () => { it('does NOT remove optional suffix when the path does not actually end with the pattern', () => { getPathFromStateMock.mockReturnValue('r/123/opt-page/789/extra'); - const {result} = renderHook(() => useDynamicBackPath(OPT_TRAILING_PATH)); + const {result} = renderHook(() => { + // @ts-expect-error -- deliberately tests a mock-only navigation route outside the production suffix union. + return useDynamicBackPath(OPT_TRAILING_PATH); + }); expect(result.current).toBe('r/123/opt-page/789/extra'); }); diff --git a/tests/unit/ReportActionsListPaddingViewTest.tsx b/tests/unit/ReportActionsListPaddingViewTest.tsx index 60469ba4963d..008b1e28edd2 100644 --- a/tests/unit/ReportActionsListPaddingViewTest.tsx +++ b/tests/unit/ReportActionsListPaddingViewTest.tsx @@ -13,10 +13,7 @@ import useShouldShowComposerForActiveEditDraft from '@pages/inbox/report/useShou import CONST from '@src/CONST'; import type {Report} from '@src/types/onyx'; -import type {StyleProp, ViewStyle} from 'react-native'; - import React from 'react'; -import {StyleSheet} from 'react-native'; const PB4_PADDING_BOTTOM = 16; @@ -92,18 +89,6 @@ function renderPaddingView(isReportArchived = false) { ); } -type PaddingStyle = Pick; - -function isPaddingStyleProp(value: unknown): value is StyleProp { - if (value === null || value === undefined || value === false || typeof value === 'number') { - return true; - } - if (Array.isArray(value)) { - return value.every((entry: unknown) => isPaddingStyleProp(entry)); - } - return isRecord(value) && (!('paddingBottom' in value) || typeof value.paddingBottom === 'number'); -} - function getPaddingBottom(toJSON: ReturnType['toJSON']) { const root = toJSON(); @@ -112,7 +97,19 @@ function getPaddingBottom(toJSON: ReturnType['toJSON']) { } const style = root.props.style; - return isPaddingStyleProp(style) ? StyleSheet.flatten(style)?.paddingBottom : undefined; + if (!Array.isArray(style)) { + return undefined; + } + + for (let index = style.length - 1; index >= 0; index -= 1) { + const entry: unknown = style.at(index); + if (!isRecord(entry) || !('paddingBottom' in entry)) { + continue; + } + return typeof entry.paddingBottom === 'number' ? entry.paddingBottom : undefined; + } + + return undefined; } describe('ReportActionsListPaddingView', () => { diff --git a/tests/unit/SearchParserTest.ts b/tests/unit/SearchParserTest.ts index 3e9a7cfb576b..d2b8fc260134 100644 --- a/tests/unit/SearchParserTest.ts +++ b/tests/unit/SearchParserTest.ts @@ -1519,46 +1519,35 @@ const limitTests = [ }, ]; +function parseSearchQueryWithoutRawFilters(query: string): Record { + const parsed: unknown = parse(query); + if (!isRecord(parsed)) { + throw new Error('Expected search parser to return a record'); + } + const {rawFilterList, ...resultWithoutRawFilters} = parsed; + return resultWithoutRawFilters; +} + describe('search parser', () => { test.each(tests)(`parsing: $query`, ({query, expected}) => { - const parsed: unknown = parse(query); - if (!isRecord(parsed)) { - throw new Error('Expected search parser to return a record'); - } - const {rawFilterList, ...resultWithoutRawFilters} = parsed; - expect(resultWithoutRawFilters).toEqual(expected); + expect(parseSearchQueryWithoutRawFilters(query)).toEqual(expected); }); }); describe('Testing search parser with special characters and wrapped in quotes.', () => { test.each(keywordTests)(`parsing: $query`, ({query, expected}) => { - const parsed: unknown = parse(query); - if (!isRecord(parsed)) { - throw new Error('Expected search parser to return a record'); - } - const {rawFilterList, ...resultWithoutRawFilters} = parsed; - expect(resultWithoutRawFilters).toEqual(expected); + expect(parseSearchQueryWithoutRawFilters(query)).toEqual(expected); }); }); describe('search parser - view and groupBy defaults', () => { test.each(viewAndGroupByTests)(`parsing: $query`, ({query, expected}) => { - const parsed: unknown = parse(query); - if (!isRecord(parsed)) { - throw new Error('Expected search parser to return a record'); - } - const {rawFilterList, ...resultWithoutRawFilters} = parsed; - expect(resultWithoutRawFilters).toEqual(expected); + expect(parseSearchQueryWithoutRawFilters(query)).toEqual(expected); }); }); describe('search parser - limit filter', () => { test.each(limitTests)('$description: $query', ({query, expected}) => { - const parsed: unknown = parse(query); - if (!isRecord(parsed)) { - throw new Error('Expected search parser to return a record'); - } - const {rawFilterList, ...resultWithoutRawFilters} = parsed; - expect(resultWithoutRawFilters).toEqual(expected); + expect(parseSearchQueryWithoutRawFilters(query)).toEqual(expected); }); });