From 3b240ae567d29084f764d97196f68d420f733e68 Mon Sep 17 00:00:00 2001 From: KJ21-ENG <140263938+KJ21-ENG@users.noreply.github.com> Date: Thu, 13 Aug 2026 10:01:15 +0530 Subject: [PATCH 1/2] Remove unsafe test type assertions --- tests/unit/LHNAvatarPipelineTest.ts | 26 ++- ...ransactionListActiveTransactionIDsTest.tsx | 4 +- .../getReportRouteForCurrentContextTest.ts | 4 +- tests/unit/NavigationFocusReturnTest.ts | 8 +- tests/unit/NetworkStateReachabilityTest.ts | 24 ++- tests/unit/NextStepUtilsTest.ts | 15 +- tests/unit/PaymentCardFormTest.tsx | 6 +- tests/unit/ReimbursementAccountUtilsTest.ts | 5 +- tests/unit/libs/MoneyRequestReportUtils.ts | 9 +- tests/unit/markPullRequestsAsDeployedTest.ts | 86 ++++---- .../ReportActionEditMessageContext.test.tsx | 196 +++++++++--------- .../unit/pages/settings/AddAgentPageTest.tsx | 8 +- .../unit/pages/settings/EditNamePageTest.tsx | 6 +- .../pages/settings/EditPromptPageTest.tsx | 6 +- .../popReportsSplitNavigatorToReportTest.ts | 82 ++++---- 15 files changed, 264 insertions(+), 221 deletions(-) diff --git a/tests/unit/LHNAvatarPipelineTest.ts b/tests/unit/LHNAvatarPipelineTest.ts index 5f5726edd984..c9932b3def0c 100644 --- a/tests/unit/LHNAvatarPipelineTest.ts +++ b/tests/unit/LHNAvatarPipelineTest.ts @@ -25,6 +25,7 @@ import { createWorkspaceTaskReport, createWorkspaceThread, } from '../utils/collections/reports'; +import createMock from '../utils/createMock'; import {translateLocal} from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -195,15 +196,18 @@ describe('LHN Avatar Pipeline', () => { } as Report); // Receiver policy (for B2B invoice cases) - await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${RECEIVER_POLICY_ID}`, { - id: RECEIVER_POLICY_ID, - name: 'Receiver Workspace', - type: CONST.POLICY.TYPE.TEAM, - role: CONST.POLICY.ROLE.ADMIN, - owner: 'user2@test.com', - ownerAccountID: 2, - outputCurrency: 'USD', - } as Policy); + await Onyx.set( + `${ONYXKEYS.COLLECTION.POLICY}${RECEIVER_POLICY_ID}`, + createMock({ + id: RECEIVER_POLICY_ID, + name: 'Receiver Workspace', + type: CONST.POLICY.TYPE.TEAM, + role: CONST.POLICY.ROLE.ADMIN, + owner: 'user2@test.com', + ownerAccountID: 2, + outputCurrency: 'USD', + }), + ); // B2B invoice room (for B2B invoice report cases) await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${B2B_INVOICE_ROOM_ID}`, { @@ -549,11 +553,11 @@ describe('LHN Avatar Pipeline', () => { // ── Case 12c: Personal task (parent is DM) → SINGLE ────────────── it('Task Report (personal, parent is DM) → single', () => { - const report = { + const report = createMock({ ...createWorkspaceTaskReport(123, [CURRENT_USER_ACCOUNT_ID, 2], PARENT_DM_REPORT_ID), policyID: undefined, ownerAccountID: 2, - } as unknown as Report; + }); const result = computeAvatarResult({report, policy: null}); expect(result.shouldShowSubscript).toBe(false); diff --git a/tests/unit/MoneyRequestReportTransactionListActiveTransactionIDsTest.tsx b/tests/unit/MoneyRequestReportTransactionListActiveTransactionIDsTest.tsx index 9fe9dc19f4e6..5ca692bb657c 100644 --- a/tests/unit/MoneyRequestReportTransactionListActiveTransactionIDsTest.tsx +++ b/tests/unit/MoneyRequestReportTransactionListActiveTransactionIDsTest.tsx @@ -9,6 +9,7 @@ import {findFocusedRoute} from '@react-navigation/native'; import {useEffect, useMemo} from 'react'; import createRandomTransaction from '../utils/collections/transaction'; +import createMock from '../utils/createMock'; // Mock the TransactionThreadNavigation module jest.mock('@libs/actions/TransactionThreadNavigation', () => ({ @@ -62,11 +63,12 @@ describe('MoneyRequestReportTransactionList - Active Transaction IDs Effect', () const mockClearActiveTransactionIDs = jest.mocked(clearActiveTransactionIDs); const mockGetActiveTransactionIDs = jest.mocked(getActiveTransactionIDs); const mockFindFocusedRoute = jest.mocked(findFocusedRoute); + const mockGetRootState = jest.spyOn(navigationRef, 'getRootState'); beforeEach(() => { jest.clearAllMocks(); mockGetActiveTransactionIDs.mockReturnValue({ids: null, descriptors: null}); - (navigationRef.getRootState as jest.Mock).mockReturnValue({} as ReturnType); + mockGetRootState.mockReturnValue(createMock>>({})); }); it('should call setActiveTransactionIDs when focused route is SEARCH_REPORT', () => { diff --git a/tests/unit/Navigation/getReportRouteForCurrentContextTest.ts b/tests/unit/Navigation/getReportRouteForCurrentContextTest.ts index 89b1d10d1c85..0742030c1b6d 100644 --- a/tests/unit/Navigation/getReportRouteForCurrentContextTest.ts +++ b/tests/unit/Navigation/getReportRouteForCurrentContextTest.ts @@ -11,8 +11,8 @@ jest.mock('@libs/Navigation/Navigation', () => ({ jest.mock('@libs/Navigation/helpers/isSearchTopmostFullScreenRoute', () => jest.fn()); describe('getReportRouteForCurrentContext', () => { - const mockGetActiveRoute = Navigation.getActiveRoute as jest.MockedFunction; - const mockIsSearchTopmostFullScreenRoute = isSearchTopmostFullScreenRoute as jest.MockedFunction; + const mockGetActiveRoute = jest.mocked(Navigation.getActiveRoute); + const mockIsSearchTopmostFullScreenRoute = jest.mocked(isSearchTopmostFullScreenRoute); beforeEach(() => { jest.clearAllMocks(); diff --git a/tests/unit/NavigationFocusReturnTest.ts b/tests/unit/NavigationFocusReturnTest.ts index 475357a776b8..9612937bb69b 100644 --- a/tests/unit/NavigationFocusReturnTest.ts +++ b/tests/unit/NavigationFocusReturnTest.ts @@ -2200,7 +2200,9 @@ describe('shouldSkipAutoFocusDueToExistingFocus', () => { } it('returns false when body holds focus (nothing else claimed)', () => { - (document.activeElement as HTMLElement | null)?.blur(); + if (document.activeElement instanceof HTMLElement) { + document.activeElement.blur(); + } expect(shouldSkipAutoFocusDueToExistingFocus()).toBe(false); }); @@ -3010,8 +3012,8 @@ describe('teardown / setup lifecycle', () => { const originalAddListener = navigationRef.addListener.bind(navigationRef); const originalIsReady = navigationRef.isReady.bind(navigationRef); const originalGetRootState = navigationRef.getRootState.bind(navigationRef); - const addListenerSpy = jest.fn(() => () => {}); - navigationRef.addListener = addListenerSpy as unknown as typeof navigationRef.addListener; + const addListenerSpy = jest.fn, Parameters>(() => () => {}); + navigationRef.addListener = addListenerSpy; navigationRef.isReady = () => false; navigationRef.getRootState = () => undefined; try { diff --git a/tests/unit/NetworkStateReachabilityTest.ts b/tests/unit/NetworkStateReachabilityTest.ts index 0ab4e6279684..18eabc9b0bfb 100644 --- a/tests/unit/NetworkStateReachabilityTest.ts +++ b/tests/unit/NetworkStateReachabilityTest.ts @@ -3,13 +3,16 @@ import type Middleware from '@src/libs/Middleware/types'; import type * as NetworkState from '@src/libs/NetworkState'; import type Request from '@src/types/onyx/Request'; -import type {NetInfoState} from '@react-native-community/netinfo'; +import type {NetInfoState, NetInfoWifiState} from '@react-native-community/netinfo'; import type {OnyxKey} from 'react-native-onyx'; +import {NetInfoStateType} from '@react-native-community/netinfo'; + let netInfoListener: ((state: NetInfoState) => void) | null = null; const mockOnyxCallbacks = new Map void>(); jest.mock('@react-native-community/netinfo', () => ({ + NetInfoStateType: {wifi: 'wifi'}, addEventListener: jest.fn((cb: (state: NetInfoState) => void) => { netInfoListener = cb; return () => { @@ -28,17 +31,28 @@ jest.mock('react-native-onyx', () => ({ }), })); -function fireNetInfoState(overrides: Partial) { +function fireNetInfoState(overrides: Partial) { if (!netInfoListener) { throw new Error('NetInfo listener not registered'); } netInfoListener({ isConnected: true, isInternetReachable: true, - type: 'wifi' as NetInfoState['type'], - details: null, + type: NetInfoStateType.wifi, + details: { + isConnectionExpensive: false, + ssid: null, + bssid: null, + strength: null, + ipAddress: null, + subnet: null, + frequency: null, + linkSpeed: null, + rxLinkSpeed: null, + txLinkSpeed: null, + }, ...overrides, - } as NetInfoState); + }); } function fireSessionChange(accountID: number) { diff --git a/tests/unit/NextStepUtilsTest.ts b/tests/unit/NextStepUtilsTest.ts index b04d09bc7b98..2daec5c20eae 100644 --- a/tests/unit/NextStepUtilsTest.ts +++ b/tests/unit/NextStepUtilsTest.ts @@ -16,11 +16,12 @@ import type {Policy, Report, ReportAction, Transaction, TransactionViolations} f import type {ReportNextStep} from '@src/types/onyx/Report'; import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; -import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; +import type {OnyxCollection} from 'react-native-onyx'; import {format} from 'date-fns'; import Onyx from 'react-native-onyx'; +import createMock from '../utils/createMock'; import {formatPhoneNumber, getCurrencyDecimalsLocal, translateLocal} from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -895,12 +896,12 @@ describe('libs/NextStepUtils', () => { statusNum: CONST.REPORT.STATUS_NUM.OPEN, } as Report; - const transaction: Transaction = { + const transaction = createMock({ transactionID: 'txn-1', reportID: report.reportID, amount: -500, currency: CONST.CURRENCY.USD, - } as Transaction; + }); const transactionViolations: OnyxCollection = { [`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transaction.transactionID}`]: [ @@ -914,7 +915,7 @@ describe('libs/NextStepUtils', () => { const result = getReportNextStep({ moneyRequestReport: report, moneyRequestReportOwnerLogin: currentUserEmail, - transactions: [transaction] as Array>, + transactions: [transaction], policy: undefined, transactionViolations, currentUserEmail, @@ -1021,12 +1022,12 @@ describe('libs/NextStepUtils', () => { statusNum: CONST.REPORT.STATUS_NUM.OPEN, } as Report; - const transaction: Transaction = { + const transaction = createMock({ transactionID: 'txn-2', reportID: report.reportID, amount: -500, currency: CONST.CURRENCY.USD, - } as Transaction; + }); const transactionViolations: OnyxCollection = { [`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transaction.transactionID}`]: [ @@ -1043,7 +1044,7 @@ describe('libs/NextStepUtils', () => { const result = getReportNextStep({ moneyRequestReport: report, moneyRequestReportOwnerLogin: currentUserEmail, - transactions: [transaction] as Array>, + transactions: [transaction], policy, transactionViolations, currentUserEmail, diff --git a/tests/unit/PaymentCardFormTest.tsx b/tests/unit/PaymentCardFormTest.tsx index a43efc0921e0..0920fdd5e78a 100644 --- a/tests/unit/PaymentCardFormTest.tsx +++ b/tests/unit/PaymentCardFormTest.tsx @@ -12,6 +12,8 @@ import AddPaymentCard from '@pages/settings/Subscription/PaymentCard'; import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; +import type ReactNative from 'react-native'; + import {PortalProvider} from '@gorhom/portal'; import {NavigationContainer} from '@react-navigation/native'; import {createStackNavigator} from '@react-navigation/stack'; @@ -22,8 +24,8 @@ import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; jest.mock('@components/RenderHTML', () => { - const ReactMock = require('react') as typeof React; - const {Text} = require('react-native') as {Text: React.ComponentType<{children?: React.ReactNode}>}; + const ReactMock = jest.requireActual('react'); + const {Text} = jest.requireActual('react-native'); return ({html}: {html: string}) => { const plainText = html.replaceAll(/<[^>]*>/g, ''); diff --git a/tests/unit/ReimbursementAccountUtilsTest.ts b/tests/unit/ReimbursementAccountUtilsTest.ts index 9a7839398d36..68b0a431ee7b 100644 --- a/tests/unit/ReimbursementAccountUtilsTest.ts +++ b/tests/unit/ReimbursementAccountUtilsTest.ts @@ -5,6 +5,7 @@ import type {ACHDataReimbursementAccount} from '../../src/types/onyx/Reimburseme import CONST from '../../src/CONST'; import {getBankAccountIDAsNumber} from '../../src/libs/ReimbursementAccountUtils'; import ONYXKEYS from '../../src/ONYXKEYS'; +import createMock from '../utils/createMock'; Onyx.init({keys: ONYXKEYS}); @@ -21,7 +22,7 @@ describe('ReimbursementAccountUtils', () => { it('should return DEFAULT_NUMBER_ID when bankAccountID is undefined on achData', () => { // Given achData without bank account id // When resolving the numeric bank account id - const result = getBankAccountIDAsNumber({} as ACHDataReimbursementAccount); + const result = getBankAccountIDAsNumber(createMock({})); // Then we default to CONST.DEFAULT_NUMBER_ID expect(result).toBe(CONST.DEFAULT_NUMBER_ID); }); @@ -29,7 +30,7 @@ describe('ReimbursementAccountUtils', () => { it('should return the existing bankAccountID when present', () => { // Given achData with a bank account id // When resolving the numeric bank account id - const result = getBankAccountIDAsNumber({bankAccountID: 42} as ACHDataReimbursementAccount); + const result = getBankAccountIDAsNumber(createMock({bankAccountID: 42})); // Then we return that id (not the default) expect(result).toBe(42); }); diff --git a/tests/unit/libs/MoneyRequestReportUtils.ts b/tests/unit/libs/MoneyRequestReportUtils.ts index c5986cd023ce..08267a086d5f 100644 --- a/tests/unit/libs/MoneyRequestReportUtils.ts +++ b/tests/unit/libs/MoneyRequestReportUtils.ts @@ -5,6 +5,7 @@ import type {ReportAction, Transaction} from '@src/types/onyx'; import {actionR14932, actionR98765} from '../../../__mocks__/reportData/actions'; import {transactionR14932, transactionR98765} from '../../../__mocks__/reportData/transactions'; +import createMock from '../../utils/createMock'; describe('getThreadReportIDsForTransactions', () => { test('returns empty list for no transactions', () => { @@ -37,17 +38,17 @@ describe('getThreadReportIDsForTransactions', () => { describe('isActionVisibleOnMoneyRequestReport', () => { test('hides created action by default', () => { - const createdAction = { + const createdAction = createMock({ actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - } as ReportAction; + }); expect(isActionVisibleOnMoneyRequestReport(createdAction)).toBe(false); }); test('shows created action when explicitly allowed', () => { - const createdAction = { + const createdAction = createMock({ actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - } as ReportAction; + }); expect(isActionVisibleOnMoneyRequestReport(createdAction, true)).toBe(true); }); diff --git a/tests/unit/markPullRequestsAsDeployedTest.ts b/tests/unit/markPullRequestsAsDeployedTest.ts index 8b18c7f5ea29..482c0bd250c6 100644 --- a/tests/unit/markPullRequestsAsDeployedTest.ts +++ b/tests/unit/markPullRequestsAsDeployedTest.ts @@ -7,10 +7,7 @@ import type {InternalOctokit} from '../../.github/libs/GithubUtils'; import CONST from '../../.github/libs/CONST'; import GithubUtils from '../../.github/libs/GithubUtils'; import GitUtils from '../../.github/libs/GitUtils'; - -type ObjectMethodData = { - data: T; -}; +import createMock from '../utils/createMock'; type PullRequest = { issue_number: number; @@ -40,10 +37,10 @@ type CommitData = { let run: () => Promise; const mockGetInput = jest.fn(); -const mockGetPullRequest = jest.fn(); -const mockCreateComment = jest.fn(); -const mockListTags = jest.fn(); -const mockGetCommit = jest.fn(); +const mockGetPullRequest = jest.fn(); +const mockCreateComment = jest.fn>(); +const mockListTags = jest.fn}>, Parameters>(); +const mockGetCommit = jest.fn(); let workflowRunURL: string | null; @@ -108,36 +105,47 @@ beforeAll(() => { mockGetInput.mockImplementation(mockGetInputDefaultImplementation); // Mock octokit module - const mockOctokit = { - rest: { - issues: { - listForRepo: jest.fn().mockImplementation(async () => ({ - data: [ - { - number: 5, - }, - ], - })), - - listEvents: jest.fn().mockImplementation(async () => ({ - data: [{event: 'closed', actor: {login: 'thor'}}], - })), - createComment: mockCreateComment, - }, - pulls: { - get: mockGetPullRequest, - }, - repos: { - listTags: mockListTags, - }, - git: { - getCommit: mockGetCommit, - }, - }, - paginate: jest.fn().mockImplementation((objectMethod: () => Promise>) => objectMethod().then(({data}) => data)), - }; - - GithubUtils.internalOctokit = mockOctokit as unknown as InternalOctokit; + GithubUtils.initOctokitWithToken('fake_token'); + const initializedOctokit = GithubUtils.internalOctokit; + if (!initializedOctokit) { + throw new Error('GithubUtils failed to initialize Octokit.'); + } + jest.spyOn(initializedOctokit.rest.issues, 'listForRepo').mockResolvedValue( + createMock>>({ + data: [{number: 5}], + headers: {}, + }), + ); + const listEventsEndpoint = initializedOctokit.rest.issues.listEvents.endpoint; + const listEventsDefaults = initializedOctokit.rest.issues.listEvents.defaults; + jest.spyOn(initializedOctokit.rest.issues, 'listEvents').mockResolvedValue( + createMock>>({ + data: [{event: 'closed', actor: {login: 'thor'}}], + headers: {}, + }), + ); + const mockListEvents = jest.mocked(initializedOctokit.rest.issues.listEvents, {shallow: true}); + mockListEvents.endpoint = listEventsEndpoint; + mockListEvents.defaults = listEventsDefaults; + jest.spyOn(initializedOctokit.rest.issues, 'createComment').mockImplementation(async (...args) => { + mockCreateComment(...args); + return createMock>>({}); + }); + jest.spyOn(initializedOctokit.rest.pulls, 'get').mockImplementation(async (params) => { + if (!params) { + throw new Error('Pull request parameters are required.'); + } + return createMock>>(mockGetPullRequest(params)); + }); + jest.spyOn(initializedOctokit.rest.repos, 'listTags').mockImplementation(async (...args) => + createMock>>(await mockListTags(...args)), + ); + jest.spyOn(initializedOctokit.rest.git, 'getCommit').mockImplementation(async (params) => { + if (!params) { + throw new Error('Commit parameters are required.'); + } + return createMock>>(mockGetCommit(params)); + }); // Mock GitUtils GitUtils.getPullRequestsDeployedBetween = jest.fn(); @@ -145,7 +153,7 @@ beforeAll(() => { jest.mock('../../.github/libs/ActionUtils', () => ({ getJSONInput: jest.fn().mockImplementation((name: string, defaultValue: string) => { try { - const input = mockGetInput(name) as string; + const input = String(mockGetInput(name)); return JSON.parse(input) as unknown; } catch (err) { return defaultValue; diff --git a/tests/unit/pages/inbox/report/ReportActionEditMessageContext.test.tsx b/tests/unit/pages/inbox/report/ReportActionEditMessageContext.test.tsx index 52ce793646be..04c94df416d0 100644 --- a/tests/unit/pages/inbox/report/ReportActionEditMessageContext.test.tsx +++ b/tests/unit/pages/inbox/report/ReportActionEditMessageContext.test.tsx @@ -8,25 +8,22 @@ import {ReportActionEditMessageContextProvider, useReportActionActiveEdit, useRe import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Report, ReportAction, ReportActions, ReportActionsDrafts} from '@src/types/onyx'; - -import type {OnyxCollection} from 'react-native-onyx'; +import type {Report, ReportAction, ReportActions} from '@src/types/onyx'; +import type {ReportCollectionDataSet} from '@src/types/onyx/Report'; +import type {ReportActionsCollectionDataSet} from '@src/types/onyx/ReportAction'; +import type CollectionDataSet from '@src/types/utils/CollectionDataSet'; import React from 'react'; +import Onyx from 'react-native-onyx'; import {getFakeReport, getFakeReportAction} from '../../../../utils/LHNTestUtils'; +import waitForBatchedUpdatesWithAct from '../../../../utils/waitForBatchedUpdatesWithAct'; jest.mock('@hooks/useAncestors', () => ({ __esModule: true, default: jest.fn(() => []), })); -const mockUseOnyx = jest.fn(); -jest.mock('@hooks/useOnyx', () => ({ - __esModule: true, - default: (key: unknown, opts?: {selector?: (collection: unknown) => unknown}) => mockUseOnyx(key, opts) as unknown[], -})); - const mockUseAncestors = jest.mocked(useAncestors); let getOriginalReportIDSpy: jest.SpiedFunction; @@ -38,37 +35,27 @@ const MAIN_ACTION_ID = '9002'; const ANCESTOR_REPORT_ID = '60001'; const ANCESTOR_ACTION_ID = '91003'; -type OnyxSelectorOptions = {selector?: (collection: unknown) => unknown}; - type BuildOnyxLayerParams = { mainReport: Report; mainReportActions: ReportActions; - fullReportActionsCollection: OnyxCollection; - fullDraftsCollection: OnyxCollection; + fullReportActionsCollection: ReportActionsCollectionDataSet; + fullDraftsCollection: CollectionDataSet; }; -function buildUseOnyxImplementation(params: BuildOnyxLayerParams) { - return (key: unknown, opts?: OnyxSelectorOptions) => { - const keyStr = key as string; - - if (keyStr === `${ONYXKEYS.COLLECTION.REPORT}${MAIN_REPORT_ID}`) { - return [params.mainReport]; - } - - if (keyStr === `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`) { - return [params.mainReportActions]; - } - - if (keyStr === ONYXKEYS.COLLECTION.REPORT_ACTIONS && opts?.selector) { - return [opts.selector(params.fullReportActionsCollection)]; - } - - if (keyStr === ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS && opts?.selector) { - return [opts.selector(params.fullDraftsCollection)]; - } - - return [undefined]; +async function seedOnyxLayer(params: BuildOnyxLayerParams) { + const reportCollectionDataSet: ReportCollectionDataSet = { + [`${ONYXKEYS.COLLECTION.REPORT}${MAIN_REPORT_ID}`]: params.mainReport, }; + const reportActionsCollectionDataSet: ReportActionsCollectionDataSet = { + ...params.fullReportActionsCollection, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: params.mainReportActions, + }; + await Onyx.multiSet({ + ...reportCollectionDataSet, + ...reportActionsCollectionDataSet, + ...params.fullDraftsCollection, + }); + await waitForBatchedUpdatesWithAct(); } function createReportWithId(reportID: string): Report { @@ -87,9 +74,7 @@ function createReportActionWithId(reportActionID: string): ReportAction { }; } -function renderActiveEditHook(mockImplementation: ReturnType, effectiveTransactionThreadReportID?: string) { - mockUseOnyx.mockImplementation(mockImplementation); - +async function renderActiveEditHook(effectiveTransactionThreadReportID?: string) { function EditProviderWrapper({children}: {children: React.ReactNode}) { return ( useReportActionActiveEdit(), { + const renderedHook = renderHook(() => useReportActionActiveEdit(), { wrapper: EditProviderWrapper, }); + await waitForBatchedUpdatesWithAct(); + return renderedHook; } -function renderActiveEditAndActionsHook(mockImplementation: ReturnType, effectiveTransactionThreadReportID?: string) { - mockUseOnyx.mockImplementation(mockImplementation); - +async function renderActiveEditAndActionsHook(effectiveTransactionThreadReportID?: string) { function EditProviderWrapper({children}: {children: React.ReactNode}) { return ( ({ activeEdit: useReportActionActiveEdit(), activeEditActions: useReportActionActiveEditActions(), @@ -129,17 +114,19 @@ function renderActiveEditAndActionsHook(mockImplementation: ReturnType undefined); - mockUseOnyx.mockReturnValue([undefined]); } describe('ReportActionEditMessageContextProvider', () => { beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); // Spy the real export so the provider's import uses the same function (jest.mock replacement did not intercept calls). getOriginalReportIDSpy = jest.spyOn(ReportUtils, 'getOriginalReportID'); }); @@ -152,21 +139,26 @@ describe('ReportActionEditMessageContextProvider', () => { resetProviderTestState(); }); + afterEach(async () => { + await Onyx.clear(); + await waitForBatchedUpdatesWithAct(); + }); + describe('transaction thread report', () => { - it('surfaces an edit on the effective transaction thread when it differs from the visible report', () => { + it('surfaces an edit on the effective transaction thread when it differs from the visible report', async () => { const threadReportAction = createReportActionWithId(THREAD_ACTION_ID); const mainReport = createReportWithId(MAIN_REPORT_ID); const mainReportActions: ReportActions = {}; - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: mainReportActions, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: threadReportAction, }, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: { @@ -175,14 +167,14 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl, THREAD_REPORT_ID); + const {result} = await renderActiveEditHook(THREAD_REPORT_ID); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.EDITING); expect(result.current.editingReportID).toBe(THREAD_REPORT_ID); @@ -191,18 +183,18 @@ describe('ReportActionEditMessageContextProvider', () => { expect(result.current.editingMessage).toBe('edited on thread'); }); - it('does not load transaction-thread drafts when effective thread ID is undefined', () => { + it('does not load transaction-thread drafts when effective thread ID is undefined', async () => { const threadReportAction = createReportActionWithId(THREAD_ACTION_ID); const mainReport = createReportWithId(MAIN_REPORT_ID); - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: threadReportAction, }, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: { @@ -211,31 +203,31 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: {}, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl); + const {result} = await renderActiveEditHook(); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.OFF); expect(result.current.editingReportID).toBeNull(); }); - it('does not load transaction-thread drafts when effective thread ID is the fake report ID', () => { + it('does not load transaction-thread drafts when effective thread ID is the fake report ID', async () => { const threadReportAction = createReportActionWithId(THREAD_ACTION_ID); const mainReport = createReportWithId(MAIN_REPORT_ID); - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: threadReportAction, }, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: { @@ -244,31 +236,31 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: {}, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl, CONST.FAKE_REPORT_ID); + const {result} = await renderActiveEditHook(CONST.FAKE_REPORT_ID); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.OFF); expect(result.current.editingReportID).toBeNull(); }); - it('does not load transaction-thread drafts when effective thread ID equals the visible report ID', () => { + it('does not load transaction-thread drafts when effective thread ID equals the visible report ID', async () => { const threadReportAction = createReportActionWithId(THREAD_ACTION_ID); const mainReport = createReportWithId(MAIN_REPORT_ID); - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: threadReportAction, }, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: { @@ -277,28 +269,28 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: {}, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl, MAIN_REPORT_ID); + const {result} = await renderActiveEditHook(MAIN_REPORT_ID); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.OFF); expect(result.current.editingReportID).toBeNull(); }); - it('does not surface additional edits when a draft exists without its report action', () => { + it('does not surface additional edits when a draft exists without its report action', async () => { const mainReport = createReportWithId(MAIN_REPORT_ID); - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${THREAD_REPORT_ID}`]: {}, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: {}, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: { @@ -307,20 +299,20 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: {}, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl, THREAD_REPORT_ID); + const {result} = await renderActiveEditHook(THREAD_REPORT_ID); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.OFF); expect(result.current.editingReportID).toBeNull(); }); - it('prefers the main report draft over a transaction-thread draft when both exist', () => { + it('prefers the main report draft over a transaction-thread draft when both exist', async () => { const mainReportAction = createReportActionWithId(MAIN_ACTION_ID); const threadReportAction = createReportActionWithId(THREAD_ACTION_ID); @@ -329,14 +321,14 @@ describe('ReportActionEditMessageContextProvider', () => { [MAIN_ACTION_ID]: mainReportAction, }; - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: mainReportActions, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${THREAD_REPORT_ID}`]: { [THREAD_ACTION_ID]: threadReportAction, }, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: { [MAIN_ACTION_ID]: { message: 'main wins', @@ -349,14 +341,14 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl, THREAD_REPORT_ID); + const {result} = await renderActiveEditHook(THREAD_REPORT_ID); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.EDITING); expect(result.current.editingReportID).toBe(MAIN_REPORT_ID); @@ -366,7 +358,7 @@ describe('ReportActionEditMessageContextProvider', () => { }); describe('ancestor drafts', () => { - it('prefers an ancestor draft over the main report draft', () => { + it('prefers an ancestor draft over the main report draft', async () => { const ancestorReport = createReportWithId(ANCESTOR_REPORT_ID); const ancestorAction = createReportActionWithId(ANCESTOR_ACTION_ID); const mainReportAction = createReportActionWithId(MAIN_ACTION_ID); @@ -375,7 +367,7 @@ describe('ReportActionEditMessageContextProvider', () => { mockUseAncestors.mockReturnValue([{report: ancestorReport, reportAction: ancestorAction, shouldDisplayNewMarker: false}]); getOriginalReportIDSpy.mockImplementation(() => ANCESTOR_REPORT_ID); - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: { [MAIN_ACTION_ID]: mainReportAction, }, @@ -384,7 +376,7 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: { [MAIN_ACTION_ID]: { message: 'main draft message', @@ -397,7 +389,7 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: { [MAIN_ACTION_ID]: mainReportAction, @@ -406,7 +398,7 @@ describe('ReportActionEditMessageContextProvider', () => { fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl); + const {result} = await renderActiveEditHook(); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.EDITING); expect(result.current.editingReportID).toBe(ANCESTOR_REPORT_ID); @@ -417,18 +409,18 @@ describe('ReportActionEditMessageContextProvider', () => { }); describe('main report draft only', () => { - it('surfaces a draft on the visible report when there are no ancestors', () => { + it('surfaces a draft on the visible report when there are no ancestors', async () => { const mainReportAction = createReportActionWithId(MAIN_ACTION_ID); const mainReport = createReportWithId(MAIN_REPORT_ID); const mainReportActions: ReportActions = { [MAIN_ACTION_ID]: mainReportAction, }; - const fullReportActionsCollection: OnyxCollection = { + const fullReportActionsCollection: ReportActionsCollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${MAIN_REPORT_ID}`]: mainReportActions, }; - const fullDraftsCollection: OnyxCollection = { + const fullDraftsCollection: CollectionDataSet = { [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${MAIN_REPORT_ID}`]: { [MAIN_ACTION_ID]: { message: 'local edit', @@ -436,14 +428,14 @@ describe('ReportActionEditMessageContextProvider', () => { }, }; - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions, fullReportActionsCollection, fullDraftsCollection, }); - const {result} = renderActiveEditHook(mockImpl); + const {result} = await renderActiveEditHook(); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.EDITING); expect(result.current.editingReportID).toBe(MAIN_REPORT_ID); @@ -456,10 +448,10 @@ describe('ReportActionEditMessageContextProvider', () => { }); }); - it('stays off when there are no drafts', () => { + it('stays off when there are no drafts', async () => { const mainReport = createReportWithId(MAIN_REPORT_ID); - const mockImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: {}, fullReportActionsCollection: { @@ -470,7 +462,7 @@ describe('ReportActionEditMessageContextProvider', () => { }, }); - const {result} = renderActiveEditHook(mockImpl); + const {result} = await renderActiveEditHook(); expect(result.current.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.OFF); expect(result.current.editingReportID).toBeNull(); @@ -480,14 +472,14 @@ describe('ReportActionEditMessageContextProvider', () => { }); describe('actions', () => { - function localDraftMock() { + function localDraftOnyxData(): BuildOnyxLayerParams { const mainReportAction = createReportActionWithId(MAIN_ACTION_ID); const mainReport = createReportWithId(MAIN_REPORT_ID); const mainReportActions: ReportActions = { [MAIN_ACTION_ID]: mainReportAction, }; - return buildUseOnyxImplementation({ + return { mainReport, mainReportActions, fullReportActionsCollection: { @@ -500,11 +492,12 @@ describe('ReportActionEditMessageContextProvider', () => { }, }, }, - }); + }; } - it('sets editing state to submitted when submitEdit runs', () => { - const {result} = renderActiveEditAndActionsHook(localDraftMock()); + it('sets editing state to submitted when submitEdit runs', async () => { + await seedOnyxLayer(localDraftOnyxData()); + const {result} = await renderActiveEditAndActionsHook(); expect(result.current.activeEdit.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.EDITING); @@ -515,9 +508,9 @@ describe('ReportActionEditMessageContextProvider', () => { expect(result.current.activeEdit.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.SUBMITTED); }); - it('clears transient state when stopEditing runs and no draft re-applies edit mode', () => { + it('clears transient state when stopEditing runs and no draft re-applies edit mode', async () => { const mainReport = createReportWithId(MAIN_REPORT_ID); - const emptyDraftsImpl = buildUseOnyxImplementation({ + await seedOnyxLayer({ mainReport, mainReportActions: {}, fullReportActionsCollection: { @@ -528,7 +521,7 @@ describe('ReportActionEditMessageContextProvider', () => { }, }); - const {result} = renderActiveEditAndActionsHook(emptyDraftsImpl); + const {result} = await renderActiveEditAndActionsHook(); expect(result.current.activeEdit.editingState).toBe(CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.OFF); @@ -546,8 +539,9 @@ describe('ReportActionEditMessageContextProvider', () => { expect(result.current.activeEdit.currentEditMessageSelection).toBeNull(); }); - it('updates currentEditMessageSelection while editing', () => { - const {result} = renderActiveEditAndActionsHook(localDraftMock()); + it('updates currentEditMessageSelection while editing', async () => { + await seedOnyxLayer(localDraftOnyxData()); + const {result} = await renderActiveEditAndActionsHook(); const nextSelection = {start: 0, end: 4}; @@ -558,8 +552,9 @@ describe('ReportActionEditMessageContextProvider', () => { expect(result.current.activeEdit.currentEditMessageSelection).toEqual(nextSelection); }); - it('ignores setCurrentEditMessageSelection when not in editing state', () => { - const {result} = renderActiveEditAndActionsHook(localDraftMock()); + it('ignores setCurrentEditMessageSelection when not in editing state', async () => { + await seedOnyxLayer(localDraftOnyxData()); + const {result} = await renderActiveEditAndActionsHook(); act(() => { result.current.activeEditActions.submitEdit(); @@ -575,8 +570,9 @@ describe('ReportActionEditMessageContextProvider', () => { expect(result.current.activeEdit.currentEditMessageSelection).toEqual(selectionAfterSubmit); }); - it('updates editing message via setEditingMessage', () => { - const {result} = renderActiveEditAndActionsHook(localDraftMock()); + it('updates editing message via setEditingMessage', async () => { + await seedOnyxLayer(localDraftOnyxData()); + const {result} = await renderActiveEditAndActionsHook(); act(() => { result.current.activeEditActions.setEditingMessage('replaced'); diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 67fdedb05983..9c6049429907 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -12,10 +12,12 @@ import AddAgentPage from '@pages/settings/Agents/AddAgentPage'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type SCREENS from '@src/SCREENS'; +import SCREENS from '@src/SCREENS'; import React from 'react'; +import createMock from '../../../utils/createMock'; + const OWNER_ACCOUNT_ID = 999; const OWNER_LOGIN = 'owner@test.com'; const OPTIMISTIC_REPORT_ID = '4567890123456789'; @@ -167,14 +169,14 @@ const mockUseOnyx = jest.mocked(useOnyx); type AddAgentRouteProp = PlatformStackRouteProp; function makeRoute(params: AddAgentRouteProp['params'] = {}): AddAgentRouteProp { - return {name: '', key: '', params} as unknown as AddAgentRouteProp; + return createMock({name: SCREENS.SETTINGS.AGENTS.ADD, key: '', params}); } function renderAddAgentPage(routeParams: AddAgentRouteProp['params'] = {}) { return render( ['navigation']>({})} />, ); } diff --git a/tests/unit/pages/settings/EditNamePageTest.tsx b/tests/unit/pages/settings/EditNamePageTest.tsx index cb1d3baa189b..044048544d3e 100644 --- a/tests/unit/pages/settings/EditNamePageTest.tsx +++ b/tests/unit/pages/settings/EditNamePageTest.tsx @@ -12,6 +12,8 @@ import type SCREENS from '@src/SCREENS'; import React from 'react'; +import createMock from '../../../utils/createMock'; + jest.mock('@userActions/Agent', () => ({ updateAgentName: jest.fn(), })); @@ -89,8 +91,8 @@ const TEST_ACCOUNT_ID = 12345; type EditNamePageRoute = PlatformStackScreenProps['route']; type EditNamePageNavigation = PlatformStackScreenProps['navigation']; -const mockRoute = {params: {accountID: TEST_ACCOUNT_ID}} as EditNamePageRoute; -const mockNavigation = {} as EditNamePageNavigation; +const mockRoute = createMock({params: {accountID: TEST_ACCOUNT_ID}}); +const mockNavigation = createMock({}); describe('EditNamePage', () => { beforeEach(() => { diff --git a/tests/unit/pages/settings/EditPromptPageTest.tsx b/tests/unit/pages/settings/EditPromptPageTest.tsx index 110b179dfb0a..99329748bcfa 100644 --- a/tests/unit/pages/settings/EditPromptPageTest.tsx +++ b/tests/unit/pages/settings/EditPromptPageTest.tsx @@ -12,6 +12,8 @@ import type SCREENS from '@src/SCREENS'; import React from 'react'; +import createMock from '../../../utils/createMock'; + jest.mock('@userActions/Agent', () => ({ updateAgentPrompt: jest.fn(), })); @@ -87,8 +89,8 @@ const TEST_ACCOUNT_ID = 12345; type EditPromptPageRoute = PlatformStackScreenProps['route']; type EditPromptPageNavigation = PlatformStackScreenProps['navigation']; -const mockRoute = {params: {accountID: TEST_ACCOUNT_ID}} as EditPromptPageRoute; -const mockNavigation = {} as EditPromptPageNavigation; +const mockRoute = createMock({params: {accountID: TEST_ACCOUNT_ID}}); +const mockNavigation = createMock({}); describe('EditPromptPage', () => { beforeEach(() => { diff --git a/tests/unit/popReportsSplitNavigatorToReportTest.ts b/tests/unit/popReportsSplitNavigatorToReportTest.ts index 8d96bdffd22b..f64a0435660d 100644 --- a/tests/unit/popReportsSplitNavigatorToReportTest.ts +++ b/tests/unit/popReportsSplitNavigatorToReportTest.ts @@ -6,6 +6,8 @@ import SCREENS from '@src/SCREENS'; import {StackActions} from '@react-navigation/native'; +import createMock from '../utils/createMock'; + jest.mock('@libs/Navigation/navigationRef', () => ({ __esModule: true, default: { @@ -20,8 +22,8 @@ const SPLIT_NAV_KEY = 'splitNavKey'; // The mocked navigationRef has no `this` usage in its methods, so unbinding the references is safe. /* eslint-disable @typescript-eslint/unbound-method */ -const mockedGetRootState = navigationRef.getRootState as unknown as jest.Mock; -const mockedDispatch = navigationRef.dispatch as unknown as jest.Mock; +const mockedGetRootState = jest.mocked(navigationRef.getRootState); +const mockedDispatch = jest.mocked(navigationRef.dispatch); /* eslint-enable @typescript-eslint/unbound-method */ /** @@ -31,7 +33,7 @@ const mockedDispatch = navigationRef.dispatch as unknown as jest.Mock; * a non-REPORT placeholder (e.g. sidebar). */ function buildRootStateWithSplitNavRoutes(splitRoutes: Array<{reportID: string} | null>, splitNavKey: string | undefined = SPLIT_NAV_KEY) { - return { + return createMock>>({ routes: [ { name: NAVIGATORS.TAB_NAVIGATOR, @@ -48,7 +50,7 @@ function buildRootStateWithSplitNavRoutes(splitRoutes: Array<{reportID: string} }, }, ], - }; + }); } describe('popReportsSplitNavigatorToReport', () => { @@ -63,15 +65,17 @@ describe('popReportsSplitNavigatorToReport', () => { }); it('no-ops when there is no TAB_NAVIGATOR in the root state', () => { - mockedGetRootState.mockReturnValue({routes: [{name: NAVIGATORS.RIGHT_MODAL_NAVIGATOR}]}); + mockedGetRootState.mockReturnValue(createMock>>({routes: [{name: NAVIGATORS.RIGHT_MODAL_NAVIGATOR}]})); popReportsSplitNavigatorToReport(SELF_DM_REPORT_ID); expect(mockedDispatch).not.toHaveBeenCalled(); }); it('no-ops when there is no REPORTS_SPLIT_NAVIGATOR inside the TAB_NAVIGATOR', () => { - mockedGetRootState.mockReturnValue({ - routes: [{name: NAVIGATORS.TAB_NAVIGATOR, state: {routes: [{name: NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR}]}}], - }); + mockedGetRootState.mockReturnValue( + createMock>>({ + routes: [{name: NAVIGATORS.TAB_NAVIGATOR, state: {routes: [{name: NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR}]}}], + }), + ); popReportsSplitNavigatorToReport(SELF_DM_REPORT_ID); expect(mockedDispatch).not.toHaveBeenCalled(); }); @@ -112,39 +116,41 @@ describe('popReportsSplitNavigatorToReport', () => { it('uses the last (most recent) occurrence of REPORTS_SPLIT_NAVIGATOR when nested in multiple TAB_NAVIGATORs', () => { // Older TAB_NAVIGATOR contains an unrelated split navigator state — the helper must target the newest one only. - mockedGetRootState.mockReturnValue({ - routes: [ - { - name: NAVIGATORS.TAB_NAVIGATOR, - state: { - routes: [ - { - name: NAVIGATORS.REPORTS_SPLIT_NAVIGATOR, - state: {key: 'oldSplit', routes: [{name: SCREENS.REPORT, params: {reportID: SELF_DM_REPORT_ID}}]}, - }, - ], + mockedGetRootState.mockReturnValue( + createMock>>({ + routes: [ + { + name: NAVIGATORS.TAB_NAVIGATOR, + state: { + routes: [ + { + name: NAVIGATORS.REPORTS_SPLIT_NAVIGATOR, + state: {key: 'oldSplit', routes: [{name: SCREENS.REPORT, params: {reportID: SELF_DM_REPORT_ID}}]}, + }, + ], + }, }, - }, - { - name: NAVIGATORS.TAB_NAVIGATOR, - state: { - routes: [ - { - name: NAVIGATORS.REPORTS_SPLIT_NAVIGATOR, - state: { - key: SPLIT_NAV_KEY, - routes: [ - {name: SCREENS.HOME}, - {name: SCREENS.REPORT, params: {reportID: SELF_DM_REPORT_ID}}, - {name: SCREENS.REPORT, params: {reportID: OTHER_REPORT_ID}}, - ], + { + name: NAVIGATORS.TAB_NAVIGATOR, + state: { + routes: [ + { + name: NAVIGATORS.REPORTS_SPLIT_NAVIGATOR, + state: { + key: SPLIT_NAV_KEY, + routes: [ + {name: SCREENS.HOME}, + {name: SCREENS.REPORT, params: {reportID: SELF_DM_REPORT_ID}}, + {name: SCREENS.REPORT, params: {reportID: OTHER_REPORT_ID}}, + ], + }, }, - }, - ], + ], + }, }, - }, - ], - }); + ], + }), + ); popReportsSplitNavigatorToReport(SELF_DM_REPORT_ID); expect(mockedDispatch).toHaveBeenCalledWith({...StackActions.pop(1), target: SPLIT_NAV_KEY}); }); From 2eb6c73e12eeec3056d4775843842489626c8ea6 Mon Sep 17 00:00:00 2001 From: KJ21-ENG <140263938+KJ21-ENG@users.noreply.github.com> Date: Thu, 13 Aug 2026 11:50:38 +0530 Subject: [PATCH 2/2] Fix CSpell and Octokit test contracts --- tests/unit/NetworkStateReachabilityTest.ts | 1 + tests/unit/markPullRequestsAsDeployedTest.ts | 157 ++++++++++--------- 2 files changed, 82 insertions(+), 76 deletions(-) diff --git a/tests/unit/NetworkStateReachabilityTest.ts b/tests/unit/NetworkStateReachabilityTest.ts index 18eabc9b0bfb..891daf0a06d6 100644 --- a/tests/unit/NetworkStateReachabilityTest.ts +++ b/tests/unit/NetworkStateReachabilityTest.ts @@ -1,3 +1,4 @@ +// cspell:ignore bssid import CONST from '@src/CONST'; import type Middleware from '@src/libs/Middleware/types'; import type * as NetworkState from '@src/libs/NetworkState'; diff --git a/tests/unit/markPullRequestsAsDeployedTest.ts b/tests/unit/markPullRequestsAsDeployedTest.ts index 482c0bd250c6..024ea45561dc 100644 --- a/tests/unit/markPullRequestsAsDeployedTest.ts +++ b/tests/unit/markPullRequestsAsDeployedTest.ts @@ -9,64 +9,48 @@ import GithubUtils from '../../.github/libs/GithubUtils'; import GitUtils from '../../.github/libs/GitUtils'; import createMock from '../utils/createMock'; -type PullRequest = { - issue_number: number; - title: string; - merged_by: {login: string}; - labels: Array<{name: string}>; -}; - -type PullRequestParams = { - pull_number: number; -}; - -type PullRequestData = { - data?: PullRequest; -}; - -type Commit = { - commit_sha: string; -}; - -type CommitData = { - data: { - message: string; - }; -}; +type GetPullRequest = InternalOctokit['rest']['pulls']['get']; +type GetPullRequestResponse = Awaited>; +type PullRequest = GetPullRequestResponse['data']; +type ListTags = InternalOctokit['rest']['repos']['listTags']; +type ListTagsResponse = Awaited>; +type Tag = ListTagsResponse['data'][number]; +type GetCommit = InternalOctokit['rest']['git']['getCommit']; +type GetCommitResponse = Awaited>; +type Commit = GetCommitResponse['data']; +type CreateComment = InternalOctokit['rest']['issues']['createComment']; +type CreateCommentResponse = Awaited>; let run: () => Promise; const mockGetInput = jest.fn(); -const mockGetPullRequest = jest.fn(); -const mockCreateComment = jest.fn>(); -const mockListTags = jest.fn}>, Parameters>(); -const mockGetCommit = jest.fn(); +const mockGetPullRequest = jest.fn, Parameters>(); +const mockCreateComment = jest.fn, Parameters>(); +const mockListTags = jest.fn, Parameters>(); +const mockGetCommit = jest.fn, Parameters>(); let workflowRunURL: string | null; const PRList: Record = { - 1: { - issue_number: 1, + 1: createMock({ + number: 1, title: 'Test PR 1', merged_by: { login: 'odin', }, labels: [], - }, - 2: { - issue_number: 2, + }), + 2: createMock({ + number: 2, title: 'Test PR 2', merged_by: { login: 'loki', }, labels: [], - }, + }), }; const version = '42.42.42-42'; -const defaultTags = [ - {name: '42.42.42-42', commit: {sha: 'abcd'}}, - {name: '42.42.42-41', commit: {sha: 'hash'}}, -]; +const defaultTags: ListTagsResponse['data'] = [createMock({name: '42.42.42-42', commit: {sha: 'abcd'}}), createMock({name: '42.42.42-41', commit: {sha: 'hash'}})]; function mockGetInputDefaultImplementation(key: string): boolean | string { switch (key) { @@ -90,11 +74,15 @@ function mockGetInputDefaultImplementation(key: string): boolean | string { } } -function mockGetCommitDefaultImplementation({commit_sha}: Commit): CommitData { +async function mockGetCommitDefaultImplementation(...[params]: Parameters): ReturnType { + if (!params) { + throw new Error('Commit parameters are required.'); + } + const {commit_sha} = params; if (commit_sha === 'abcd') { - return {data: {message: 'Test commit 1'}}; + return {data: createMock({message: 'Test commit 1'}), headers: {}, status: 200, url: ''}; } - return {data: {message: 'Test commit 2'}}; + return {data: createMock({message: 'Test commit 2'}), headers: {}, status: 200, url: ''}; } beforeAll(() => { @@ -127,25 +115,10 @@ beforeAll(() => { const mockListEvents = jest.mocked(initializedOctokit.rest.issues.listEvents, {shallow: true}); mockListEvents.endpoint = listEventsEndpoint; mockListEvents.defaults = listEventsDefaults; - jest.spyOn(initializedOctokit.rest.issues, 'createComment').mockImplementation(async (...args) => { - mockCreateComment(...args); - return createMock>>({}); - }); - jest.spyOn(initializedOctokit.rest.pulls, 'get').mockImplementation(async (params) => { - if (!params) { - throw new Error('Pull request parameters are required.'); - } - return createMock>>(mockGetPullRequest(params)); - }); - jest.spyOn(initializedOctokit.rest.repos, 'listTags').mockImplementation(async (...args) => - createMock>>(await mockListTags(...args)), - ); - jest.spyOn(initializedOctokit.rest.git, 'getCommit').mockImplementation(async (params) => { - if (!params) { - throw new Error('Commit parameters are required.'); - } - return createMock>>(mockGetCommit(params)); - }); + jest.spyOn(initializedOctokit.rest.issues, 'createComment').mockImplementation((...args) => mockCreateComment(...args)); + jest.spyOn(initializedOctokit.rest.pulls, 'get').mockImplementation((...args) => mockGetPullRequest(...args)); + jest.spyOn(initializedOctokit.rest.repos, 'listTags').mockImplementation((...args) => mockListTags(...args)); + jest.spyOn(initializedOctokit.rest.git, 'getCommit').mockImplementation((...args) => mockGetCommit(...args)); // Mock GitUtils GitUtils.getPullRequestsDeployedBetween = jest.fn(); @@ -168,10 +141,18 @@ beforeAll(() => { }); beforeEach(() => { - mockGetPullRequest.mockImplementation(({pull_number}: PullRequestParams): PullRequestData => (pull_number in PRList ? {data: PRList[pull_number]} : {})); - mockListTags.mockResolvedValue({ - data: defaultTags, + mockGetPullRequest.mockImplementation(async (params) => { + if (!params) { + throw new Error('Pull request parameters are required.'); + } + const pullRequest = PRList[params.pull_number]; + if (!pullRequest) { + throw new Error(`Unexpected pull request: ${params.pull_number}`); + } + return {data: pullRequest, headers: {}, status: 200, url: ''}; }); + mockCreateComment.mockResolvedValue({data: createMock({}), headers: {}, status: 201, url: ''}); + mockListTags.mockResolvedValue({data: defaultTags, headers: {}, status: 200, url: ''}); mockGetCommit.mockImplementation(mockGetCommitDefaultImplementation); }); @@ -195,6 +176,9 @@ describe('markPullRequestsAsDeployed', () => { expect(mockCreateComment).toHaveBeenCalledTimes(Object.keys(PRList).length); for (let i = 0; i < Object.keys(PRList).length; i++) { const PR = PRList[i + 1]; + if (!PR.merged_by) { + throw new Error(`Pull request ${PR.number} has no merger.`); + } expect(mockCreateComment).toHaveBeenNthCalledWith(i + 1, { body: `🚀 [Deployed](${workflowRunURL}) to staging by https://github.com/${PR.merged_by.login} in version: ${version} 🚀 @@ -203,7 +187,7 @@ platform | result 🕸 web 🕸|success ✅ 🤖 android 🤖|success ✅ 🍎 iOS 🍎|success ✅`, - issue_number: PR.issue_number, + issue_number: PR.number, owner: CONST.GITHUB_OWNER, repo: CONST.APP_REPO, }); @@ -232,7 +216,7 @@ platform | result 🕸 web 🕸|success ✅ 🤖 android 🤖|success ✅ 🍎 iOS 🍎|success ✅`, - issue_number: PRList[i + 1].issue_number, + issue_number: PRList[i + 1].number, owner: CONST.GITHUB_OWNER, repo: CONST.APP_REPO, }); @@ -249,33 +233,51 @@ platform | result } return mockGetInputDefaultImplementation(key); }); - mockGetPullRequest.mockImplementation(({pull_number}: PullRequestParams) => { + mockGetPullRequest.mockImplementation(async (params) => { + if (!params) { + throw new Error('Pull request parameters are required.'); + } + const {pull_number} = params; if (pull_number === 3) { return { - data: { - issue_number: 3, + data: createMock({ + number: 3, title: 'Test PR 3', merged_by: { login: 'thor', }, labels: [{name: CONST.LABELS.CP_STAGING}], - }, + }), + headers: {}, + status: 200, + url: '', }; } - return {}; + throw new Error(`Unexpected pull request: ${pull_number}`); }); mockListTags.mockResolvedValue({ - data: [{name: '42.42.42-43', commit: {sha: 'xyz'}}, ...defaultTags], + data: [createMock({name: '42.42.42-43', commit: {sha: 'xyz'}}), ...defaultTags], + headers: {}, + status: 200, + url: '', }); - mockGetCommit.mockImplementation(({commit_sha}: Commit) => { + mockGetCommit.mockImplementation(async (...args) => { + const [params] = args; + if (!params) { + throw new Error('Commit parameters are required.'); + } + const {commit_sha} = params; if (commit_sha === 'xyz') { return { - data: { + data: createMock({ message: `Merge pull request #3 blahblahblah\\n(cherry picked from commit dag_dag)\\n(cherry-picked to staging by freyja)`, - }, + }), + headers: {}, + status: 200, + url: '', }; } - return mockGetCommitDefaultImplementation({commit_sha}); + return mockGetCommitDefaultImplementation(...args); }); // Note: we import this in here so that it executes after all the mocks are set up @@ -313,6 +315,9 @@ platform | result expect(mockCreateComment).toHaveBeenCalledTimes(Object.keys(PRList).length); for (let i = 0; i < Object.keys(PRList).length; i++) { const PR = PRList[i + 1]; + if (!PR.merged_by) { + throw new Error(`Pull request ${PR.number} has no merger.`); + } expect(mockCreateComment).toHaveBeenNthCalledWith(i + 1, { body: `🚀 [Deployed](${workflowRunURL}) to staging by https://github.com/${PR.merged_by.login} in version: ${version} 🚀 @@ -321,7 +326,7 @@ platform | result 🕸 web 🕸|success ✅ 🤖 android 🤖|skipped 🚫 🍎 iOS 🍎|failed ❌`, - issue_number: PR.issue_number, + issue_number: PR.number, owner: CONST.GITHUB_OWNER, repo: CONST.APP_REPO, });