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
7 changes: 3 additions & 4 deletions tests/unit/DistanceRateTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy, Transaction, TransactionViolations} from '@src/types/onyx';

import type {OnyxKey} from 'react-native-onyx';

import Onyx from 'react-native-onyx';

import createRandomPolicy from '../utils/collections/policies';
Expand Down Expand Up @@ -148,12 +146,13 @@ describe('DistanceRate', () => {
}
await waitForBatchedUpdates();
const onyxPolicy = await new Promise<Policy>((resolve) => {
const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policy.id}` as const;
Onyx.connect({
key: `${ONYXKEYS.COLLECTION.POLICY}${policy.id}` as OnyxKey,
key: policyKey,
// eslint-disable-next-line rulesdir/prefer-early-return
callback: (value) => {
if (value !== undefined) {
resolve(value as Policy);
resolve(value);
}
},
});
Expand Down
5 changes: 3 additions & 2 deletions tests/unit/DynamicContactMethodDetailsPageTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ describe('DynamicContactMethodDetailsPage', () => {
});
});
beforeEach(() => {
global.fetch = getGlobalFetchMock();
mockFetch = fetch as MockFetch;
const globalFetchMock = getGlobalFetchMock();
global.fetch = globalFetchMock;
mockFetch = globalFetchMock;
return Onyx.clear().then(waitForBatchedUpdates);
});

Expand Down
14 changes: 9 additions & 5 deletions tests/unit/FlashListTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {FlashList} from '@shopify/flash-list';
import React from 'react';
import {View} from 'react-native';

import createMock from '../utils/createMock';

type CellProps = {
index: number;
onLayout: (event: LayoutChangeEvent) => void;
Expand Down Expand Up @@ -72,11 +74,13 @@ describe('FlashList - stale onLayout after rapid data change', () => {
// Pre-fix: this throws "index out of bounds, not enough layouts"
// Post-fix: validateItemSize bails when tryGetLayout returns undefined
expect(() => {
staleOnLayout?.({
nativeEvent: {
layout: {x: 0, y: 0, width: 100, height: 50},
},
} as LayoutChangeEvent);
staleOnLayout?.(
createMock<LayoutChangeEvent>({
nativeEvent: {
layout: {x: 0, y: 0, width: 100, height: 50},
},
}),
);
}).not.toThrow();
});
});
10 changes: 7 additions & 3 deletions tests/unit/components/ScreenWrapperPreventRemoveTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import ScreenWrapper from '@components/ScreenWrapper';

import ONYXKEYS from '@src/ONYXKEYS';

import type {usePreventRemove} from '@react-navigation/native';
import type ReactTestRendererType from 'react-test-renderer';

// These rules are disabled because `require()` is used inside jest.mock factories for module resolution,
Expand All @@ -12,7 +13,6 @@ import Onyx from 'react-native-onyx';

import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';

// eslint-disable-next-line
const ReactTestRenderer: typeof ReactTestRendererType = require('react-test-renderer');

Onyx.init({keys: ONYXKEYS});
Expand Down Expand Up @@ -120,12 +120,16 @@ function getNavigationMock() {
}

function getUsePreventRemove() {
return jest.requireMock<{usePreventRemove: jest.Mock}>('@react-navigation/native').usePreventRemove;
return jest.requireMock<{usePreventRemove: jest.MockedFunction<typeof usePreventRemove>}>('@react-navigation/native').usePreventRemove;
}

function lastPreventRemoveCondition(): boolean {
const mock = getUsePreventRemove();
return mock.mock.calls.at(-1)?.[0] as boolean;
const lastCall = mock.mock.calls.at(-1);
if (!lastCall) {
throw new Error('Expected usePreventRemove to have been called');
}
return lastCall[0];
}

async function renderScreenWrapper(): Promise<ReactTestRendererType.ReactTestRenderer> {
Expand Down
6 changes: 4 additions & 2 deletions tests/unit/getTimeDifferenceIntervalsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import type {OnyxEntry} from 'react-native-onyx';

import {addDays, differenceInDays, differenceInMinutes, startOfDay} from 'date-fns';

import createMock from '../utils/createMock';

describe('getTimeDifferenceIntervals', () => {
const createMockTransaction = (startDate: string, endDate: string): OnyxEntry<Transaction> =>
({
createMock<Transaction>({
comment: {
customUnit: {
attributes: {
Expand All @@ -19,7 +21,7 @@ describe('getTimeDifferenceIntervals', () => {
},
},
},
}) as OnyxEntry<Transaction>;
});

it('calculates hours for same-day transactions', () => {
// Given a transaction that starts and ends on the same day
Expand Down
4 changes: 3 additions & 1 deletion tests/unit/goBackFromWorkspaceSettingPagesTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import type {NavigationState, PartialState} from '@react-navigation/native';

import {StackActions} from '@react-navigation/native';

import createMock from '../utils/createMock';

jest.mock('@libs/Navigation/Navigation', () => ({
__esModule: true,
default: {
Expand All @@ -33,7 +35,7 @@ function mockRootState(routes: Array<{name: string; state?: PartialState<Navigat
index: index ?? routes.length - 1,
};
// eslint-disable-next-line @typescript-eslint/unbound-method -- jest.fn() mock doesn't rely on `this` binding
jest.mocked(navigationRef.getRootState).mockReturnValue(state as unknown as NavigationState);
jest.mocked(navigationRef.getRootState).mockReturnValue(createMock<NavigationState>(state));
}

describe('goBackFromWorkspaceSettingPages', () => {
Expand Down
13 changes: 8 additions & 5 deletions tests/unit/hooks/useCachedImageSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import CONST from '@src/CONST';

import type {ImageSource} from 'expo-image';

import createMock from '../../utils/createMock';

const MOCK_URI = 'https://example.com/image.png';
// eslint-disable-next-line @typescript-eslint/naming-convention
const MOCK_HEADERS = {'X-Auth-Token': 'token123'};
Expand All @@ -20,13 +22,14 @@ let mockCreateObjectURL: jest.Mock;
let mockRevokeObjectURL: jest.Mock;

const createMockResponse = (ok = true) => {
const response = {
const clone = jest.fn<Response, []>();
const response = createMock<Response>({
ok,
blob: jest.fn().mockResolvedValue(MOCK_BLOB),
clone: jest.fn(),
};
response.clone.mockReturnValue(response);
return response as unknown as Response;
clone,
});
clone.mockReturnValue(response);
return response;
};

beforeEach(() => {
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/hooks/useConfirmationCtaText.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import ONYXKEYS from '@src/ONYXKEYS';
import React from 'react';
import Onyx from 'react-native-onyx';

import createMock from '../../utils/createMock';
import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct';

type Params = Parameters<typeof useConfirmationCtaText>[0];
Expand Down Expand Up @@ -86,7 +87,7 @@ describe('useConfirmationCtaText', () => {
});

it('includes formatted amount in sendInvoice copy when invoicing details are present', () => {
const policy = {invoice: {companyName: 'Acme', companyWebsite: 'acme.com'}} as Params['policy'];
const policy = createMock<NonNullable<Params['policy']>>({invoice: {companyName: 'Acme', companyWebsite: 'acme.com'}});
const {result} = renderHook(() => useConfirmationCtaText({...baseParams, isTypeInvoice: true, iouType: CONST.IOU.TYPE.INVOICE, policy, formattedAmount: '$50.00'}), {
wrapper: Wrapper,
});
Expand Down
4 changes: 3 additions & 1 deletion tests/unit/hooks/useContainerWidth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import useContainerWidth from '@hooks/useContainerWidth';

import type {LayoutChangeEvent} from 'react-native';

import createMock from '../../utils/createMock';

function createLayoutEvent(width: number): LayoutChangeEvent {
return {nativeEvent: {layout: {x: 0, y: 0, width, height: 0}}} as LayoutChangeEvent;
return createMock<LayoutChangeEvent>({nativeEvent: {layout: {x: 0, y: 0, width, height: 0}}});
}

describe('useContainerWidth', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ import Onyx from 'react-native-onyx';

import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';

const mockUseIsFocused = jest.fn().mockReturnValue(true);
const mockUseIsFocused = jest.fn<boolean, []>().mockReturnValue(true);

jest.mock('@react-navigation/native', () => {
const actualNav = jest.requireActual<typeof ReactNavigation>('@react-navigation/native');
return {
...actualNav,
useIsFocused: () => mockUseIsFocused() as boolean,
useIsFocused: () => mockUseIsFocused(),
};
});

Expand Down
12 changes: 8 additions & 4 deletions tests/unit/hooks/useDomainGroupFilter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,36 @@ import useDomainGroupFilter from '@hooks/useDomainGroupFilter';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type Domain from '@src/types/onyx/Domain';
import type {DomainSecurityGroup, SecurityGroupKey} from '@src/types/onyx/Domain';

import Onyx from 'react-native-onyx';

import createMock from '../../utils/createMock';
import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';

const DOMAIN_ACCOUNT_ID = 99999;
const SECURITY_GROUP_PREFIX = CONST.DOMAIN.DOMAIN_SECURITY_GROUP_PREFIX;

function buildDomain(groups: Record<string, {members: Record<string, 'read' | null>; name: string}>): Domain {
const domain: Record<string, unknown> = {
const domain = createMock<Domain>({
validated: true,
accountID: DOMAIN_ACCOUNT_ID,
email: 'admin@test.com',
domain_defaultSecurityGroupID: Object.keys(groups).at(0) ?? '',
};
});

for (const [groupID, group] of Object.entries(groups)) {
domain[`${SECURITY_GROUP_PREFIX}${groupID}`] = {
const securityGroupKey: SecurityGroupKey = `${SECURITY_GROUP_PREFIX}${groupID}`;
const securityGroup: DomainSecurityGroup = {
shared: group.members,
name: group.name,
enableRestrictedPrimaryLogin: false,
enableRestrictedPolicyCreation: false,
};
domain[securityGroupKey] = securityGroup;
}

return domain as unknown as Domain;
return domain;
}

function buildMemberRow(accountID: number): DomainMemberRowData {
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/hooks/useExpenseSubmission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Onyx from 'react-native-onyx';

import type * as Split from '../../../src/libs/actions/IOU/Split';

import createMock from '../../utils/createMock';
import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct';

const mockRequestMoneyAction = jest.fn();
Expand Down Expand Up @@ -174,7 +175,7 @@ function buildParams(overrides: Partial<Parameters<typeof useExpenseSubmission>[
receiptFiles: {},
report: {reportID: REPORT_ID, type: CONST.REPORT.TYPE.CHAT} as Report,
reportID: REPORT_ID,
policy: {id: 'policy-1'} as Policy,
policy: createMock<Policy>({id: 'policy-1'}),
policyCategories: {} as PolicyCategories,
isDraftPolicy: false,
currentUserPersonalDetails: {accountID: CURRENT_USER_ACCOUNT_ID, login: 'me@test.com', email: 'me@test.com'},
Expand Down
Loading
Loading