Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions tests/actions/IOUTest/SplitSelfDMTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';

import Onyx from 'react-native-onyx';

import type {MockFetch} from '../../utils/TestHelper';

import createPersonalDetails from '../../utils/collections/personalDetails';
import {createSelfDM} from '../../utils/collections/reports';
import createMock from '../../utils/createMock';
import getOnyxValue from '../../utils/getOnyxValue';
import {getGlobalFetchMock, getOnyxData} from '../../utils/TestHelper';
import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
Expand Down Expand Up @@ -71,9 +70,6 @@ jest.mock('@src/libs/SearchQueryUtils', () => {
const RORY_EMAIL = 'rory@expensifail.com';
const RORY_ACCOUNT_ID = 3;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
let mockFetch: MockFetch;

const currentUserPersonalDetails: CurrentUserPersonalDetails = {
...createPersonalDetails(RORY_ACCOUNT_ID),
login: RORY_EMAIL,
Expand All @@ -97,7 +93,6 @@ beforeAll(() => {
beforeEach(() => {
jest.clearAllTimers();
global.fetch = getGlobalFetchMock();
mockFetch = fetch as MockFetch;
return Onyx.clear().then(waitForBatchedUpdates);
});

Expand Down Expand Up @@ -326,11 +321,16 @@ describe('updateSplitTransactionsFromSplitExpensesFlow - selfDM', () => {
// Set up a snapshot that contains the original transaction, simulating the state
// where the user is on the Expenses screen and the snapshot has the tracked expense
const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}-2` as `${typeof ONYXKEYS.COLLECTION.SNAPSHOT}${string}`;
const originalTransactionSnapshotKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransaction.transactionID}`;
await Onyx.merge(snapshotKey, {
data: {[originalTransactionSnapshotKey]: originalTransaction},
search: {type: CONST.SEARCH.DATA_TYPES.EXPENSE, isLoading: false},
} as unknown as SearchResults);
const originalTransactionSnapshotKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransaction.transactionID}` satisfies `${typeof ONYXKEYS.COLLECTION.TRANSACTION}${string}`;
const snapshotFixtureData: SearchResults['data'] = {};
snapshotFixtureData[originalTransactionSnapshotKey] = originalTransaction;
await Onyx.merge(
snapshotKey,
createMock<SearchResults>({
data: snapshotFixtureData,
search: {type: CONST.SEARCH.DATA_TYPES.EXPENSE, isLoading: false},
}),
);
await waitForBatchedUpdates();

let allTransactions: OnyxCollection<Transaction>;
Expand Down
11 changes: 6 additions & 5 deletions tests/actions/IOUTest/TrackExpenseTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ import createRandomPolicy from '../../utils/collections/policies';
import createRandomPolicyCategories from '../../utils/collections/policyCategory';
import {createRandomReport} from '../../utils/collections/reports';
import createRandomTransaction, {createRandomDistanceRequestTransaction} from '../../utils/collections/transaction';
import createMock from '../../utils/createMock';
import getOnyxValue from '../../utils/getOnyxValue';
import initCurrencyListContext from '../../utils/initCurrencyListContext';
import PusherHelper from '../../utils/PusherHelper';
import * as TestHelper from '../../utils/TestHelper';
import {formatPhoneNumber, getCurrencyDecimalsLocal, getGlobalFetchMock, getOnyxData, setPersonalDetails, signInWithTestUser} from '../../utils/TestHelper';
import {formatPhoneNumber, getCurrencyDecimalsLocal, getOnyxData, setPersonalDetails, signInWithTestUser} from '../../utils/TestHelper';
import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';

jest.mock('@src/libs/Navigation/Navigation', () => ({
Expand Down Expand Up @@ -126,8 +127,8 @@ describe('actions/IOU/TrackExpense', () => {

beforeEach(async () => {
jest.clearAllTimers();
global.fetch = getGlobalFetchMock();
mockFetch = fetch as MockFetch;
mockFetch = TestHelper.createGlobalFetchMock();
global.fetch = mockFetch;
await Onyx.clear();
currencyListProvider = await initCurrencyListContext({
keys: ONYXKEYS,
Expand Down Expand Up @@ -1098,13 +1099,13 @@ describe('actions/IOU/TrackExpense', () => {
// Build the REPORT_PREVIEW action OUTSIDE Onyx and pass it explicitly.
// If the implementation falls back to deprecatedAllReportActions (Onyx) instead of using this explicit param,
// the unarchive failure-data entry will not be generated and the assertion below will fail.
const reportPreviewAction: ReportAction = {
const reportPreviewAction = createMock<ReportAction>({
reportActionID: 'preview-1',
actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW,
childReportID: archivedExpenseReportID,
created: DateUtils.getDBTime(),
message: [],
} as unknown as ReportAction;
});
const explicitReportActionsList = {
[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${accountantExpenseChatID}`]: {
[reportPreviewAction.reportActionID]: reportPreviewAction,
Expand Down
36 changes: 26 additions & 10 deletions tests/actions/SubscriptionTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,30 +141,46 @@ describe('actions/Subscription', () => {
openSubscriptionPage(undefined);

const call = mockRead.mock.calls.at(0);
const onyxData = call?.at(2) as Parameters<typeof mockRead>[2];
if (!call) {
throw new Error('Expected openSubscriptionPage to make an API read call');
}
const onyxData = call[2];
const optimisticUpdate = onyxData.optimisticData?.at(0);
const failureUpdate = onyxData.failureData?.at(0);
if (!optimisticUpdate || !failureUpdate) {
throw new Error('Expected the API read call to include optimistic and failure updates');
}

// optimisticData should only have the loading key
expect(onyxData?.optimisticData).toHaveLength(1);
expect(onyxData?.optimisticData?.[0]?.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);
expect(onyxData.optimisticData).toHaveLength(1);
expect(optimisticUpdate.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);

// failureData should only have the loading key
expect(onyxData?.failureData).toHaveLength(1);
expect(onyxData?.failureData?.[0]?.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);
expect(onyxData.failureData).toHaveLength(1);
expect(failureUpdate.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);
});

it('should not include grace period data when collection is empty', () => {
openSubscriptionPage({});

const call = mockRead.mock.calls.at(0);
const onyxData = call?.at(2) as Parameters<typeof mockRead>[2];
if (!call) {
throw new Error('Expected openSubscriptionPage to make an API read call');
}
const onyxData = call[2];
const optimisticUpdate = onyxData.optimisticData?.at(0);
const failureUpdate = onyxData.failureData?.at(0);
if (!optimisticUpdate || !failureUpdate) {
throw new Error('Expected the API read call to include optimistic and failure updates');
}

// optimisticData should only have the loading key
expect(onyxData?.optimisticData).toHaveLength(1);
expect(onyxData?.optimisticData?.[0]?.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);
expect(onyxData.optimisticData).toHaveLength(1);
expect(optimisticUpdate.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);

// failureData should only have the loading key
expect(onyxData?.failureData).toHaveLength(1);
expect(onyxData?.failureData?.[0]?.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);
expect(onyxData.failureData).toHaveLength(1);
expect(failureUpdate.key).toBe(ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA);
});
});
});
4 changes: 2 additions & 2 deletions tests/navigation/GoBackTests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ jest.mock('@libs/getIsNarrowLayout', () => jest.fn());

jest.mock('@pages/inbox/sidebar/NavigationTabBarAvatar');

const mockedGetIsNarrowLayout = getIsNarrowLayout as jest.MockedFunction<typeof getIsNarrowLayout>;
const mockedUseResponsiveLayout = useResponsiveLayout as jest.MockedFunction<typeof useResponsiveLayout>;
const mockedGetIsNarrowLayout = jest.mocked(getIsNarrowLayout);
const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout);
const mockedPolicyID = 'test-policy';
const mockedBackToRoute = '/test';
describe('Go back on the narrow layout', () => {
Expand Down
4 changes: 2 additions & 2 deletions tests/navigation/NavigateTests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ jest.mock('@libs/getIsNarrowLayout', () => jest.fn());

jest.mock('@pages/inbox/sidebar/NavigationTabBarAvatar');

const mockedGetIsNarrowLayout = getIsNarrowLayout as jest.MockedFunction<typeof getIsNarrowLayout>;
const mockedUseResponsiveLayout = useResponsiveLayout as jest.MockedFunction<typeof useResponsiveLayout>;
const mockedGetIsNarrowLayout = jest.mocked(getIsNarrowLayout);
const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout);

describe('Navigate', () => {
beforeEach(() => {
Expand Down
4 changes: 2 additions & 2 deletions tests/navigation/NavigationTests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ jest.mock('@libs/getIsNarrowLayout', () => jest.fn());

jest.mock('@pages/inbox/sidebar/NavigationTabBarAvatar');

const mockedGetIsNarrowLayout = getIsNarrowLayout as jest.MockedFunction<typeof getIsNarrowLayout>;
const mockedUseResponsiveLayout = useResponsiveLayout as jest.MockedFunction<typeof useResponsiveLayout>;
const mockedGetIsNarrowLayout = jest.mocked(getIsNarrowLayout);
const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout);

describe('Navigation', () => {
beforeEach(() => {
Expand Down
4 changes: 2 additions & 2 deletions tests/navigation/PopToSidebarTests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ jest.mock('@libs/getIsNarrowLayout', () => jest.fn());

jest.mock('@pages/inbox/sidebar/NavigationTabBarAvatar');

const mockedGetIsNarrowLayout = getIsNarrowLayout as jest.MockedFunction<typeof getIsNarrowLayout>;
const mockedUseResponsiveLayout = useResponsiveLayout as jest.MockedFunction<typeof useResponsiveLayout>;
const mockedGetIsNarrowLayout = jest.mocked(getIsNarrowLayout);
const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout);

describe('Pop to sidebar after resize from wide to narrow layout', () => {
beforeEach(() => {
Expand Down
4 changes: 2 additions & 2 deletions tests/navigation/PushFullscreenFromRHPTests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ jest.mock('@libs/getIsNarrowLayout', () => jest.fn());

jest.mock('@pages/inbox/sidebar/NavigationTabBarAvatar');

const mockedGetIsNarrowLayout = getIsNarrowLayout as jest.MockedFunction<typeof getIsNarrowLayout>;
const mockedUseResponsiveLayout = useResponsiveLayout as jest.MockedFunction<typeof useResponsiveLayout>;
const mockedGetIsNarrowLayout = jest.mocked(getIsNarrowLayout);
const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout);

describe('Push fullscreen from RHP', () => {
beforeEach(() => {
Expand Down
50 changes: 41 additions & 9 deletions tests/navigation/getMatchingFullScreenRouteTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ jest.mock('@src/ROUTES', () => ({
}));

describe('getMatchingFullScreenRoute - dynamic suffix', () => {
const mockGetStateFromPath = getStateFromPath as jest.Mock;
const mockFindFocusedRouteWithOnyxTabGuard = findFocusedRouteWithOnyxTabGuard as jest.Mock;
const mockGetStateFromPath = jest.mocked(getStateFromPath);
const mockFindFocusedRouteWithOnyxTabGuard = jest.mocked(findFocusedRouteWithOnyxTabGuard);

beforeEach(() => {
jest.clearAllMocks();
Expand All @@ -72,8 +72,14 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
routes: [{name: 'BaseScreen'}, fullScreenRoute],
index: 1,
};
const expectedStrippedPath = '/base';

mockGetStateFromPath.mockImplementation((path: string) => (path === '/base' ? basePathState : undefined));
mockGetStateFromPath.mockImplementation((path) => {
if (String(path) !== expectedStrippedPath) {
throw new Error(`Unexpected path: ${path}`);
}
return basePathState;
});

const result = getMatchingFullScreenRoute(route);

Expand All @@ -91,8 +97,14 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
routes: [{name: 'BaseScreen'}, fullScreenRoute],
index: 1,
};
const expectedStrippedPath = '/base/suffix-a';

mockGetStateFromPath.mockImplementation((path: string) => (path === '/base/suffix-a' ? basePathState : undefined));
mockGetStateFromPath.mockImplementation((path) => {
if (String(path) !== expectedStrippedPath) {
throw new Error(`Unexpected path: ${path}`);
}
return basePathState;
});

const result = getMatchingFullScreenRoute(route);

Expand All @@ -111,8 +123,14 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
routes: [{name: 'BaseScreen'}, fullScreenRoute],
index: 1,
};
const expectedStrippedPath = '/base/deep/suffix-a';

mockGetStateFromPath.mockImplementation((path: string) => (path === '/base/deep/suffix-a' ? basePathState : undefined));
mockGetStateFromPath.mockImplementation((path) => {
if (String(path) !== expectedStrippedPath) {
throw new Error(`Unexpected path: ${path}`);
}
return basePathState;
});

const result = getMatchingFullScreenRoute(route);

Expand All @@ -139,8 +157,14 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
],
index: 0,
};
const expectedStrippedPath = '/base';

mockGetStateFromPath.mockImplementation((path: string) => (path === '/base' ? basePathState : undefined));
mockGetStateFromPath.mockImplementation((path) => {
if (String(path) !== expectedStrippedPath) {
throw new Error(`Unexpected path: ${path}`);
}
return basePathState;
});
mockFindFocusedRouteWithOnyxTabGuard.mockReturnValue(nestedFocusedRoute);

const result = getMatchingFullScreenRoute(route);
Expand All @@ -160,8 +184,14 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
routes: [{name: SCREENS.NOT_FOUND, path: '/invalid/base/suffix-a'}],
index: 0,
};
const expectedStrippedPath = '/invalid/base/suffix-a';

mockGetStateFromPath.mockImplementation((path: string) => (path === '/invalid/base/suffix-a' ? invalidRouteState : undefined));
mockGetStateFromPath.mockImplementation((path) => {
if (String(path) !== expectedStrippedPath) {
throw new Error(`Unexpected path: ${path}`);
}
return invalidRouteState;
});

const result = getMatchingFullScreenRoute(route);

Expand All @@ -187,6 +217,7 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
path: '/broken/path/suffix-a/suffix-b',
};

// @ts-expect-error -- Intentionally exercise the consumer's defensive handling of an invalid undefined producer result.
mockGetStateFromPath.mockReturnValue(undefined);

const result = getMatchingFullScreenRoute(route);
Expand All @@ -206,9 +237,10 @@ describe('getMatchingFullScreenRoute - dynamic suffix', () => {
routes: [{name: 'BaseScreen'}, fullScreenRoute],
index: 1,
};
const expectedStrippedPath = '/base';

mockGetStateFromPath.mockImplementation((path: string) => {
if (path === '/base') {
mockGetStateFromPath.mockImplementation((path) => {
if (String(path) === expectedStrippedPath) {
return basePathState;
}
return {routes: [{name: 'WrongScreen'}], index: 0};
Expand Down
34 changes: 14 additions & 20 deletions tests/navigation/getPathFromStateTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,40 +40,34 @@ jest.mock('@src/ROUTES', () => ({
},
}));

type RouteEntry = {
name: string;
params?: Record<string, unknown>;
path?: string;
state?: {routes: RouteEntry[]; index: number};
};

type TestState = {
routes: RouteEntry[];
index: number;
};
type RNGetPathFromStateState = Parameters<typeof RNGetPathFromState>[0];
type NavigationStateTree = RNGetPathFromStateState | PartialState<NavigationState>;
type RouteEntry = NavigationStateTree['routes'][number];
type TestState = Pick<PartialState<NavigationState>, 'routes' | 'index'>;
type TestRouteEntry = TestState['routes'][number];

function buildState(routes: RouteEntry[], index?: number): TestState {
function buildState(routes: TestRouteEntry[], index?: number): TestState {
return {
routes,
index: index ?? routes.length - 1,
} as TestState;
};
}

function realFindFocusedRoute(s: TestState | RouteEntry['state']): RouteEntry | undefined {
let current: TestState | RouteEntry['state'] = s;
function realFindFocusedRoute(s: NavigationStateTree): RouteEntry | undefined {
let current: NavigationStateTree | undefined = s;
while (current?.routes?.[current.index ?? 0]?.state != null) {
current = current.routes[current.index ?? 0].state;
}
return current?.routes?.[current?.index ?? 0];
}

const staticBasePaths: Record<string, (params?: Record<string, unknown>) => string> = {
const staticBasePaths: Record<string, (params?: RouteEntry['params']) => string> = {
WalletScreen: () => '/settings/wallet',
ReportScreen: (params) => `/r/${(params?.reportID as string) ?? ''}`,
ReportScreen: (params) => `/r/${params && 'reportID' in params && typeof params.reportID === 'string' ? params.reportID : ''}`,
};

describe('getPathFromState', () => {
const mockRNGetPathFromState = RNGetPathFromState as jest.Mock;
const mockRNGetPathFromState = jest.mocked(RNGetPathFromState);

beforeEach(() => {
jest.clearAllMocks();
Expand Down Expand Up @@ -112,7 +106,7 @@ describe('getPathFromState', () => {

describe('dynamic route resolution from pattern and params', () => {
beforeEach(() => {
mockRNGetPathFromState.mockImplementation((s: TestState) => {
mockRNGetPathFromState.mockImplementation((s) => {
const route = realFindFocusedRoute(s);
const builder = staticBasePaths[route?.name ?? ''];
return builder ? builder(route?.params) : '/unknown';
Expand Down Expand Up @@ -271,7 +265,7 @@ describe('getPathFromState', () => {

describe('tab navigator integration (OnyxTabNavigator)', () => {
beforeEach(() => {
mockRNGetPathFromState.mockImplementation((s: TestState) => {
mockRNGetPathFromState.mockImplementation((s) => {
const route = realFindFocusedRoute(s);
const builder = staticBasePaths[route?.name ?? ''];
return builder ? builder(route?.params) : '/unknown';
Expand Down
Loading
Loading