diff --git a/tests/ui/AuthScreensInitHandlerTest.tsx b/tests/ui/AuthScreensInitHandlerTest.tsx index 6e6c09d7a337..cd9d9f5fac72 100644 --- a/tests/ui/AuthScreensInitHandlerTest.tsx +++ b/tests/ui/AuthScreensInitHandlerTest.tsx @@ -23,6 +23,7 @@ import React from 'react'; import {View} from 'react-native'; import Onyx from 'react-native-onyx'; +import createMock from '../utils/createMock'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; import wrapOnyxWithWaitForBatchedUpdates from '../utils/wrapOnyxWithWaitForBatchedUpdates'; @@ -119,6 +120,7 @@ const mockedIsLoggingInAsNewUser = jest.mocked(isLoggingInAsNewUser); const mockedDidUserLogInDuringSession = jest.mocked(didUserLogInDuringSession); const mockedIsClientTheLeader = jest.mocked(isClientTheLeader); const mockedIsReady = jest.mocked(isReady); +const mockedSubscribeToUserEvents = jest.mocked(subscribeToUserEvents); function renderAuthScreensInitHandler() { return render( @@ -175,7 +177,7 @@ describe('AuthScreensInitHandler', () => { }); it('getter passed to subscribeToUserEvents returns report attributes when available', async () => { - const mockReports = {testReport: {reportName: 'Test Report'}} as unknown as ReportAttributesDerivedValue['reports']; + const mockReports = createMock({testReport: {reportName: 'Test Report'}}); await Onyx.merge(ONYXKEYS.SESSION, {accountID: TEST_ACCOUNT_ID, email: 'test@test.com'}); await Onyx.merge(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, {reports: mockReports}); @@ -184,9 +186,14 @@ describe('AuthScreensInitHandler', () => { renderAuthScreensInitHandler(); await waitForBatchedUpdatesWithAct(); - const mockCalls = (subscribeToUserEvents as jest.Mock).mock.calls; - const firstCallArgs = mockCalls.at(0) as unknown[]; - const getter = firstCallArgs.at(3) as () => unknown; + const firstCallArgs = mockedSubscribeToUserEvents.mock.calls.at(0); + if (!firstCallArgs) { + throw new Error('Expected subscribeToUserEvents to be called'); + } + const getter = firstCallArgs[3]; + if (!getter) { + throw new Error('Expected report attributes getter to be provided'); + } expect(getter()).toEqual(mockReports); }); @@ -198,9 +205,14 @@ describe('AuthScreensInitHandler', () => { renderAuthScreensInitHandler(); await waitForBatchedUpdatesWithAct(); - const mockCalls = (subscribeToUserEvents as jest.Mock).mock.calls; - const firstCallArgs = mockCalls.at(0) as unknown[]; - const getter = firstCallArgs.at(3) as () => unknown; + const firstCallArgs = mockedSubscribeToUserEvents.mock.calls.at(0); + if (!firstCallArgs) { + throw new Error('Expected subscribeToUserEvents to be called'); + } + const getter = firstCallArgs[3]; + if (!getter) { + throw new Error('Expected report attributes getter to be provided'); + } expect(getter()).toBeUndefined(); }); diff --git a/tests/ui/DynamicStateSelectionPageTest.tsx b/tests/ui/DynamicStateSelectionPageTest.tsx index 6db6cb55729b..6fa46645391f 100644 --- a/tests/ui/DynamicStateSelectionPageTest.tsx +++ b/tests/ui/DynamicStateSelectionPageTest.tsx @@ -48,9 +48,11 @@ jest.mock('@hooks/useLocalize', () => } const [, stateKey, property] = key.split('.'); - // stateKey is parsed from an `allStates..*` path generated from mockStates itself, so it is guaranteed valid. - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - const state = mockStates[stateKey as keyof typeof mockStates]; + const stateEntry = Object.entries(mockStates).find(([keyName]) => keyName === stateKey); + if (!stateEntry) { + throw new Error(`Unknown state key: ${stateKey}`); + } + const state = stateEntry[1]; if (property === 'stateName') { return state.stateName; @@ -108,18 +110,13 @@ describe('DynamicStateSelectionPage', () => { const searchedProps = mockedSelectionList.mock.lastCall?.[0]; const expectedSearchResults = searchOptions( 'New', - Object.keys(mockStates).map((stateKey) => { - // stateKey comes from Object.keys(mockStates) itself, so it is guaranteed valid. - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - const state = mockStates[stateKey as keyof typeof mockStates]; - return { - value: state.stateISO, - keyForList: state.stateISO, - text: state.stateName, - isSelected: state.stateISO === 'NY', - searchValue: StringUtils.sanitizeString(`${state.stateISO}${state.stateName}`), - }; - }), + Object.values(mockStates).map((state) => ({ + value: state.stateISO, + keyForList: state.stateISO, + text: state.stateName, + isSelected: state.stateISO === 'NY', + searchValue: StringUtils.sanitizeString(`${state.stateISO}${state.stateName}`), + })), ); expect(searchedProps?.data.map((item) => item.keyForList)).toEqual(expectedSearchResults.map((item) => item.keyForList)); diff --git a/tests/ui/StateSelectorModalTest.tsx b/tests/ui/StateSelectorModalTest.tsx index 76e3beb9c2c9..fc7ab7da0959 100644 --- a/tests/ui/StateSelectorModalTest.tsx +++ b/tests/ui/StateSelectorModalTest.tsx @@ -42,7 +42,11 @@ jest.mock('@hooks/useLocalize', () => } const [, stateKey, property] = key.split('.'); - const state = mockStates[stateKey as keyof typeof mockStates]; + const stateEntry = Object.entries(mockStates).find(([keyName]) => keyName === stateKey); + if (!stateEntry) { + throw new Error(`Unknown state key: ${stateKey}`); + } + const state = stateEntry[1]; if (property === 'stateName') { return state.stateName; @@ -107,12 +111,12 @@ describe('StateSelectorModal', () => { const searchedProps = mockedSelectionList.mock.lastCall?.[0]; const expectedSearchResults = searchOptions( 'New', - Object.keys(mockStates).map((state) => ({ - value: mockStates[state as keyof typeof mockStates].stateISO, - keyForList: mockStates[state as keyof typeof mockStates].stateISO, - text: mockStates[state as keyof typeof mockStates].stateName, - isSelected: mockStates[state as keyof typeof mockStates].stateISO === 'NY', - searchValue: StringUtils.sanitizeString(`${mockStates[state as keyof typeof mockStates].stateISO}${mockStates[state as keyof typeof mockStates].stateName}`), + Object.values(mockStates).map((state) => ({ + value: state.stateISO, + keyForList: state.stateISO, + text: state.stateName, + isSelected: state.stateISO === 'NY', + searchValue: StringUtils.sanitizeString(`${state.stateISO}${state.stateName}`), })), ); diff --git a/tests/unit/ChatGPTTranslatorTest.ts b/tests/unit/ChatGPTTranslatorTest.ts index aa7785f97974..8d78d03867be 100644 --- a/tests/unit/ChatGPTTranslatorTest.ts +++ b/tests/unit/ChatGPTTranslatorTest.ts @@ -8,7 +8,7 @@ import type Locale from '@src/types/onyx/Locale'; jest.mock('@scripts/utils/OpenAIUtils'); -const MockedOpenAIUtils = OpenAIUtils as jest.MockedClass; +const mockedPromptResponses = jest.spyOn(OpenAIUtils.prototype, 'promptResponses'); /** * Creates a mock response for promptResponses @@ -19,7 +19,7 @@ function mockResponse(text: string, responseID = 'resp_test_123') { describe('ChatGPTTranslator.performTranslation', () => { const apiKey = 'test-api-key'; - const targetLang: Locale = 'it' as Locale; + const targetLang: Locale = 'it'; const maxRetries = 8; // eslint-disable-next-line no-template-curly-in-string const original = 'Hello ${name}!'; @@ -35,43 +35,40 @@ describe('ChatGPTTranslator.performTranslation', () => { beforeEach(() => { jest.clearAllMocks(); - MockedOpenAIUtils.prototype.promptResponses = jest.fn(); + mockedPromptResponses.mockReset(); translator = new ChatGPTTranslator(apiKey); }); it('retries if translated template has incorrect placeholders, then succeeds', async () => { // First attempt returns invalid placeholder format, second returns valid - (MockedOpenAIUtils.prototype.promptResponses as jest.Mock).mockResolvedValueOnce(mockResponse(invalidTranslation)).mockResolvedValueOnce(mockResponse(validTranslation)); + mockedPromptResponses.mockResolvedValueOnce(mockResponse(invalidTranslation)).mockResolvedValueOnce(mockResponse(validTranslation)); // @ts-expect-error TS2445 const result = await translator.performTranslation(targetLang, original); - // eslint-disable-next-line @typescript-eslint/unbound-method - expect(MockedOpenAIUtils.prototype.promptResponses).toHaveBeenCalledTimes(2); + expect(mockedPromptResponses).toHaveBeenCalledTimes(2); expect(result).toBe(validTranslation); }); it('returns original string after exceeding retry attempts', async () => { // Always returns invalid - (MockedOpenAIUtils.prototype.promptResponses as jest.Mock).mockResolvedValue(mockResponse(invalidTranslation)); + mockedPromptResponses.mockResolvedValue(mockResponse(invalidTranslation)); // @ts-expect-error TS2445 const result = await translator.performTranslation(targetLang, original); - // eslint-disable-next-line @typescript-eslint/unbound-method - expect(MockedOpenAIUtils.prototype.promptResponses).toHaveBeenCalledTimes(maxRetries + 1); + expect(mockedPromptResponses).toHaveBeenCalledTimes(maxRetries + 1); expect(result).toBe(original); }); it('retries if translated HTML has incorrect attributes, then succeeds', async () => { // First attempt returns invalid HTML format, second returns valid - (MockedOpenAIUtils.prototype.promptResponses as jest.Mock).mockResolvedValueOnce(mockResponse(invalidHTMLTranslation)).mockResolvedValueOnce(mockResponse(validHTMLTranslation)); + mockedPromptResponses.mockResolvedValueOnce(mockResponse(invalidHTMLTranslation)).mockResolvedValueOnce(mockResponse(validHTMLTranslation)); // @ts-expect-error TS2445 const result = await translator.performTranslation(targetLang, originalHTML); - // eslint-disable-next-line @typescript-eslint/unbound-method - expect(MockedOpenAIUtils.prototype.promptResponses).toHaveBeenCalledTimes(2); + expect(mockedPromptResponses).toHaveBeenCalledTimes(2); expect(result).toBe(validHTMLTranslation); }); @@ -80,7 +77,7 @@ describe('ChatGPTTranslator.performTranslation', () => { const translatedWithChineseBrackets = '【点击这里】(https://example.com)'; const expectedFixed = '[点击这里](https://example.com)'; - (MockedOpenAIUtils.prototype.promptResponses as jest.Mock).mockResolvedValueOnce(mockResponse(translatedWithChineseBrackets)); + mockedPromptResponses.mockResolvedValueOnce(mockResponse(translatedWithChineseBrackets)); // @ts-expect-error TS2445 const result = await translator.performTranslation(targetLang, originalText); @@ -91,7 +88,7 @@ describe('ChatGPTTranslator.performTranslation', () => { it('tracks failed translations after exhausting all retries', async () => { // Always throw an error const testError = new Error('Test API error'); - (MockedOpenAIUtils.prototype.promptResponses as jest.Mock).mockRejectedValue(testError); + mockedPromptResponses.mockRejectedValue(testError); // @ts-expect-error TS2445 await translator.performTranslation(targetLang, original); @@ -106,7 +103,7 @@ describe('ChatGPTTranslator.performTranslation', () => { }); it('returns empty array when no translations have failed', async () => { - (MockedOpenAIUtils.prototype.promptResponses as jest.Mock).mockResolvedValue(mockResponse(validTranslation)); + mockedPromptResponses.mockResolvedValue(mockResponse(validTranslation)); // @ts-expect-error TS2445 await translator.performTranslation(targetLang, original); diff --git a/tests/unit/DeeplinkRouteNormalizationTest.ts b/tests/unit/DeeplinkRouteNormalizationTest.ts index 9c1a4c1929be..7e422077c9bc 100644 --- a/tests/unit/DeeplinkRouteNormalizationTest.ts +++ b/tests/unit/DeeplinkRouteNormalizationTest.ts @@ -4,7 +4,6 @@ import getStateFromPath from '@libs/Navigation/helpers/getStateFromPath'; import normalizePath from '@libs/Navigation/helpers/normalizePath'; import {getRouteFromLink} from '@libs/ReportUtils'; -import type {Route} from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; jest.mock('@libs/Navigation/helpers/getStateFromPath', () => jest.fn()); @@ -57,39 +56,39 @@ describe('Deeplink route normalization', () => { }); describe('getAdaptedStateFromPath path pass-through', () => { - const mockGetStateFromPath = getStateFromPath as jest.Mock; - const mockGetMatchingNewRoute = getMatchingNewRoute as jest.Mock; + const mockGetStateFromPath = jest.mocked(getStateFromPath); + const mockGetMatchingNewRoute = jest.mocked(getMatchingNewRoute); beforeEach(() => { jest.clearAllMocks(); // Pass through unchanged so we can isolate what getAdaptedStateFromPath itself does to the path. - mockGetMatchingNewRoute.mockReturnValue(null); + mockGetMatchingNewRoute.mockReturnValue(undefined); // Return a minimal state with a full-screen route so getAdaptedState early-returns. mockGetStateFromPath.mockReturnValue({routes: [{name: SCREENS.HOME}], index: 0}); }); it('Should pass `/Home` through untouched, so the linking config alias can resolve it', () => { - getAdaptedStateFromPath('/Home' as Route, undefined, false); + getAdaptedStateFromPath('/Home', undefined, false); expect(mockGetStateFromPath).toHaveBeenCalledWith('/Home'); }); it('Should only add the leading slash to bare `Home` (no leading slash)', () => { - getAdaptedStateFromPath('Home' as Route, undefined, false); + getAdaptedStateFromPath('Home', undefined, false); expect(mockGetStateFromPath).toHaveBeenCalledWith('/Home'); }); it('Should NOT rewrite the lowercase `/home` route', () => { - getAdaptedStateFromPath('/home' as Route, undefined, false); + getAdaptedStateFromPath('/home', undefined, false); expect(mockGetStateFromPath).toHaveBeenCalledWith('/home'); }); it('Should NOT rewrite other paths that merely contain `Home`', () => { - getAdaptedStateFromPath('/Home/extra' as Route, undefined, false); + getAdaptedStateFromPath('/Home/extra', undefined, false); expect(mockGetStateFromPath).toHaveBeenCalledWith('/Home/extra'); }); it('Should leave unrelated paths untouched', () => { - getAdaptedStateFromPath('/r/123456789' as Route, undefined, false); + getAdaptedStateFromPath('/r/123456789', undefined, false); expect(mockGetStateFromPath).toHaveBeenCalledWith('/r/123456789'); }); }); diff --git a/tests/unit/FailureTrackingTest.ts b/tests/unit/FailureTrackingTest.ts index f86664a4f70d..c2aed67afbe9 100644 --- a/tests/unit/FailureTrackingTest.ts +++ b/tests/unit/FailureTrackingTest.ts @@ -2,8 +2,14 @@ import CONST from '@src/CONST'; import {getFailureCount, recordFailure, reset} from '@src/libs/FailureTracker'; import FailureTracking from '@src/libs/Middleware/FailureTracking'; +import type {OnyxKey} from 'react-native-onyx'; + +import type Request from '../../src/types/onyx/Request'; + jest.mock('@src/libs/Log'); +const request: Request = {command: 'FailureTrackingTest'}; + describe('FailureTracking middleware', () => { beforeEach(() => { reset(); @@ -12,7 +18,7 @@ describe('FailureTracking middleware', () => { test('calls recordSuccess on resolved response', async () => { const responseData = {jsonCode: 200}; - const result = await FailureTracking(Promise.resolve(responseData), {} as never, false); + const result = await FailureTracking(Promise.resolve(responseData), request, false); expect(result).toBe(responseData); }); @@ -20,7 +26,7 @@ describe('FailureTracking middleware', () => { test('calls recordFailure on FAILED_TO_FETCH error', async () => { const error = new Error(CONST.ERROR.FAILED_TO_FETCH); - await expect(FailureTracking(Promise.reject(error), {} as never, false)).rejects.toThrow(CONST.ERROR.FAILED_TO_FETCH); + await expect(FailureTracking(Promise.reject(error), request, false)).rejects.toThrow(CONST.ERROR.FAILED_TO_FETCH); expect(getFailureCount()).toBe(1); }); @@ -28,7 +34,7 @@ describe('FailureTracking middleware', () => { test('calls recordFailure on EXPENSIFY_SERVICE_INTERRUPTED error', async () => { const error = new Error(CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED); - await expect(FailureTracking(Promise.reject(error), {} as never, false)).rejects.toThrow(CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED); + await expect(FailureTracking(Promise.reject(error), request, false)).rejects.toThrow(CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED); expect(getFailureCount()).toBe(1); }); @@ -36,7 +42,7 @@ describe('FailureTracking middleware', () => { test('does NOT call recordFailure on other errors', async () => { const error = new Error('some random error'); - await expect(FailureTracking(Promise.reject(error), {} as never, false)).rejects.toThrow('some random error'); + await expect(FailureTracking(Promise.reject(error), request, false)).rejects.toThrow('some random error'); expect(getFailureCount()).toBe(0); }); @@ -46,15 +52,15 @@ describe('FailureTracking middleware', () => { expect(getFailureCount()).toBe(1); // A resolved response should reset via recordSuccess - await FailureTracking(Promise.resolve({jsonCode: 200}), {} as never, false); + await FailureTracking(Promise.resolve({jsonCode: 200}), request, false); expect(getFailureCount()).toBe(0); }); test('always re-throws errors', async () => { const connectivityError = new Error(CONST.ERROR.FAILED_TO_FETCH); - await expect(FailureTracking(Promise.reject(connectivityError), {} as never, false)).rejects.toThrow(connectivityError); + await expect(FailureTracking(Promise.reject(connectivityError), request, false)).rejects.toThrow(connectivityError); const otherError = new Error('timeout'); - await expect(FailureTracking(Promise.reject(otherError), {} as never, false)).rejects.toThrow(otherError); + await expect(FailureTracking(Promise.reject(otherError), request, false)).rejects.toThrow(otherError); }); }); diff --git a/tests/unit/PersistedRequests.ts b/tests/unit/PersistedRequests.ts index 18a66f009783..c889b71c2498 100644 --- a/tests/unit/PersistedRequests.ts +++ b/tests/unit/PersistedRequests.ts @@ -1,4 +1,4 @@ -import type {OnyxKey} from 'react-native-onyx'; +import type {OnyxInput, OnyxKey} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import OnyxUtils from 'react-native-onyx/dist/OnyxUtils'; @@ -17,6 +17,22 @@ const request: Request<'reportMetadata_1' | 'reportMetadata_2'> = { requestIndex: 1, }; +class MockFile extends Blob { + name = 'mock-file'; + + source = 'mock-file'; + + lastModified = 0; + + webkitRelativePath = ''; + + public constructor(fileBits: BlobPart[] = [], fileName = 'mock-file', options?: FilePropertyBag) { + super(fileBits, options); + this.name = fileName; + this.lastModified = options?.lastModified ?? 0; + } +} + beforeAll(() => Onyx.init({ keys: ONYXKEYS, @@ -95,12 +111,10 @@ describe('PersistedRequests', () => { await waitForBatchedUpdates(); const originalFile = global.File; - function MockFile() {} - global.File = MockFile as unknown as typeof File; + global.File = MockFile; try { - const mockFilePrototype = MockFile.prototype as Record; - const mockFile = Object.create(mockFilePrototype) as File; + const mockFile = new MockFile(); const newRequest: Request<'reportMetadata_1' | 'reportMetadata_2'> = { command: 'OpenReport', successData: [{key: 'reportMetadata_1', onyxMethod: 'set', value: {}}], @@ -205,12 +219,10 @@ describe('PersistedRequests persistence guarantees', () => { await waitForBatchedUpdates(); const originalFile = global.File; - function MockFile() {} - global.File = MockFile as unknown as typeof File; + global.File = MockFile; try { - const mockFilePrototype = MockFile.prototype as Record; - const mockFile = Object.create(mockFilePrototype) as File; + const mockFile = new MockFile(); const requestWithFile: Request<'reportMetadata_1' | 'reportMetadata_2'> = { command: 'OpenReport', successData: [{key: 'reportMetadata_1', onyxMethod: 'merge', value: {}}], @@ -246,15 +258,14 @@ describe('PersistedRequests persistence guarantees', () => { expect(PersistedRequests.getAll()).toHaveLength(0); // Intercept Onyx.set for PERSISTED_REQUESTS so we can control resolution order - type CapturedSet = {value: unknown; triggerRealSet: () => Promise}; + type CapturedSet = {triggerRealSet: () => Promise}; const capturedSets: CapturedSet[] = []; const originalSet = Onyx.set.bind(Onyx); - const setMock = jest.spyOn(Onyx, 'set').mockImplementation((key, value) => { + const setMock = jest.spyOn(Onyx, 'set').mockImplementation((key: TKey, value: OnyxInput) => { if (key === ONYXKEYS.PERSISTED_REQUESTS && Array.isArray(value) && value.length > 0) { return new Promise((resolvePromise) => { capturedSets.push({ - value, - triggerRealSet: () => originalSet(key, value as Array>).then(resolvePromise), + triggerRealSet: () => originalSet(key, value).then(resolvePromise), }); }); } diff --git a/tests/unit/QuickActionUtilsTest.ts b/tests/unit/QuickActionUtilsTest.ts index e2c7a3bbaef2..1d8ebf39efe5 100644 --- a/tests/unit/QuickActionUtilsTest.ts +++ b/tests/unit/QuickActionUtilsTest.ts @@ -9,13 +9,14 @@ import type {Participant} from '@src/types/onyx/Report'; import Onyx from 'react-native-onyx'; +import createMock from '../utils/createMock'; import * as LHNTestUtils from '../utils/LHNTestUtils'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; // Mock the PolicyUtils module jest.mock('@libs/PolicyUtils'); -const mockedPolicyUtils = PolicyUtils as jest.Mocked; +const mockedPolicyUtils = jest.mocked(PolicyUtils); describe('QuickActionUtils', () => { describe('isQuickActionAllowed', () => { @@ -150,13 +151,13 @@ describe('QuickActionUtils', () => { }, }; mockedPolicyUtils.getPerDiemCustomUnit.mockReturnValue(perDiemCustomUnit); - const policy = { + const policy = createMock({ id: '1', arePerDiemRatesEnabled: true, customUnits: { ABCDEF: perDiemCustomUnit, }, - } as unknown as Policy; + }); mockedPolicyUtils.isControlPolicy.mockReturnValue(true); mockedPolicyUtils.isPerDiemEnabled.mockReturnValue(true); @@ -164,19 +165,19 @@ describe('QuickActionUtils', () => { }); it("should not allow per diem action when policy doesn't have per diem rates", () => { mockedPolicyUtils.getPerDiemCustomUnit.mockReturnValue(undefined); - const policy = { + const policy = createMock({ id: '1', arePerDiemRatesEnabled: true, - } as unknown as Policy; + }); expect(isQuickActionAllowed(perDiemAction, report, policy, false, [CONST.BETAS.ALL], false)).toBe(false); }); it("should not allow per diem action when policy doesn't have per diem enabled", () => { mockedPolicyUtils.isControlPolicy.mockReturnValue(true); mockedPolicyUtils.isPerDiemEnabled.mockReturnValue(false); - const policy = { + const policy = createMock({ id: '1', arePerDiemRatesEnabled: false, - } as unknown as Policy; + }); expect(isQuickActionAllowed(perDiemAction, report, policy, false, [CONST.BETAS.ALL], false)).toBe(false); }); it('should not allow per diem action when policy is not a control workspace', () => { @@ -193,13 +194,13 @@ describe('QuickActionUtils', () => { }; mockedPolicyUtils.isControlPolicy.mockReturnValue(false); mockedPolicyUtils.getPerDiemCustomUnit.mockReturnValue(perDiemCustomUnit); - const policy = { + const policy = createMock({ id: '1', arePerDiemRatesEnabled: true, customUnits: { ABCDEF: perDiemCustomUnit, }, - } as unknown as Policy; + }); expect(isQuickActionAllowed(perDiemAction, report, policy, false, [CONST.BETAS.ALL], false)).toBe(false); }); @@ -219,10 +220,10 @@ describe('QuickActionUtils', () => { policyID: '1', ownerAccountID: 1, }, - { + createMock({ id: '1', units: {time: {enabled: true, rate: 1}}, - } as Policy, + }), false, [CONST.BETAS.ALL], false, @@ -242,9 +243,9 @@ describe('QuickActionUtils', () => { policyID: '1', ownerAccountID: 1, }, - { + createMock({ id: '1', - } as Policy, + }), false, [CONST.BETAS.ALL], false, diff --git a/tests/unit/chunkLoadErrorRecoveryTest.ts b/tests/unit/chunkLoadErrorRecoveryTest.ts index 28e136e92292..712211da6bb8 100644 --- a/tests/unit/chunkLoadErrorRecoveryTest.ts +++ b/tests/unit/chunkLoadErrorRecoveryTest.ts @@ -21,8 +21,6 @@ import lazyRetry from '@src/utils/lazyRetry'; import type {ComponentType} from 'react'; -type ComponentImport = () => Promise<{default: T}>; - const mockClearWorkboxRecoveryCaches = jest.fn(); jest.mock('@libs/clearWorkboxRecoveryCaches', () => ({ __esModule: true, @@ -133,7 +131,7 @@ describe('ChunkLoadError recovery', () => { it('plain-reloads on the first failure without clearing caches', async () => { sessionStorage.removeItem(stateKey); - const failingImport = jest.fn().mockRejectedValue(chunkError) as unknown as ComponentImport; + const failingImport = jest.fn, []>().mockRejectedValue(chunkError); lazyRetry(failingImport, RETRY_KEY); await flushMicrotasks(); @@ -146,7 +144,7 @@ describe('ChunkLoadError recovery', () => { it('clears SW caches before reloading on the second ChunkLoadError failure when online', async () => { sessionStorage.setItem(stateKey, 'true'); jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(true); - const failingImport = jest.fn().mockRejectedValue(chunkError) as unknown as ComponentImport; + const failingImport = jest.fn, []>().mockRejectedValue(chunkError); lazyRetry(failingImport, RETRY_KEY); await flushMicrotasks(); @@ -159,7 +157,7 @@ describe('ChunkLoadError recovery', () => { it('rejects to the error boundary on second ChunkLoadError failure when offline to preserve the offline cache', async () => { sessionStorage.setItem(stateKey, 'true'); jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false); - const failingImport = jest.fn().mockRejectedValue(chunkError) as unknown as ComponentImport; + const failingImport = jest.fn, []>().mockRejectedValue(chunkError); await expect(lazyRetry(failingImport, RETRY_KEY)).rejects.toBeDefined(); await flushMicrotasks(); @@ -171,7 +169,7 @@ describe('ChunkLoadError recovery', () => { it('rejects to the error boundary on second failure when the error is not a ChunkLoadError', async () => { sessionStorage.setItem(stateKey, 'true'); const networkError = new Error('Failed to fetch'); - const failingImport = jest.fn().mockRejectedValue(networkError) as unknown as ComponentImport; + const failingImport = jest.fn, []>().mockRejectedValue(networkError); await expect(lazyRetry(failingImport, RETRY_KEY)).rejects.toThrow('Failed to fetch'); await flushMicrotasks(); @@ -182,7 +180,7 @@ describe('ChunkLoadError recovery', () => { it('rejects to the error boundary on the third failure to prevent an infinite reload loop', async () => { sessionStorage.setItem(stateKey, 'cache-cleared'); - const failingImport = jest.fn().mockRejectedValue(chunkError) as unknown as ComponentImport; + const failingImport = jest.fn, []>().mockRejectedValue(chunkError); await expect(lazyRetry(failingImport, RETRY_KEY)).rejects.toBeDefined(); await flushMicrotasks(); @@ -194,7 +192,7 @@ describe('ChunkLoadError recovery', () => { it('keeps each import retry state isolated so a sibling success does not reset it', async () => { // 'other' chunk already reloaded once; a successful 'test' chunk import must not reset it. sessionStorage.setItem(`${CONST.SESSION_STORAGE_KEYS.RETRY_LAZY_REFRESHED}:other`, 'true'); - const successfulImport = jest.fn().mockResolvedValue({default: () => null}) as unknown as ComponentImport; + const successfulImport = jest.fn, []>().mockResolvedValue({default: () => null}); await lazyRetry(successfulImport, RETRY_KEY); await flushMicrotasks(); @@ -204,7 +202,7 @@ describe('ChunkLoadError recovery', () => { it('does not reload on successful import', async () => { sessionStorage.removeItem(stateKey); - const successfulImport = jest.fn().mockResolvedValue({default: () => null}) as unknown as ComponentImport; + const successfulImport = jest.fn, []>().mockResolvedValue({default: () => null}); await lazyRetry(successfulImport, RETRY_KEY); await flushMicrotasks(); diff --git a/tests/unit/hooks/useAllTransactions.test.ts b/tests/unit/hooks/useAllTransactions.test.ts index 36c3980b3198..522c926458c0 100644 --- a/tests/unit/hooks/useAllTransactions.test.ts +++ b/tests/unit/hooks/useAllTransactions.test.ts @@ -5,10 +5,12 @@ import useAllTransactions from '@hooks/useAllTransactions'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {SearchResults} from '@src/types/onyx'; +import type Report from '@src/types/onyx/Report'; import Onyx from 'react-native-onyx'; import createRandomTransaction from '../../utils/collections/transaction'; +import createMock from '../../utils/createMock'; let mockCurrentSearchResults: SearchResults | undefined; @@ -57,7 +59,7 @@ describe('useAllTransactions', () => { transaction1.transactionID = 'txn1'; await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`, transaction1); - mockCurrentSearchResults = { + mockCurrentSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -66,7 +68,7 @@ describe('useAllTransactions', () => { isLoading: false, }, data: undefined, - } as unknown as SearchResults; + }); const {result} = renderHook(() => useAllTransactions()); @@ -85,7 +87,7 @@ describe('useAllTransactions', () => { searchTransaction.transactionID = 'searchTxn1'; collectionTransaction.transactionID = 'collectionTxn1'; - mockCurrentSearchResults = { + const mockSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -93,10 +95,10 @@ describe('useAllTransactions', () => { hasResults: true, isLoading: false, }, - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}searchTxn1`]: searchTransaction, - }, - } as unknown as SearchResults; + data: {}, + }); + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}searchTxn1`] = searchTransaction; + mockCurrentSearchResults = mockSearchResults; await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}collectionTxn1`, collectionTransaction); const {result} = renderHook(() => useAllTransactions()); @@ -120,7 +122,7 @@ describe('useAllTransactions', () => { searchTransaction.amount = 1000; collectionTransaction.amount = 2000; - mockCurrentSearchResults = { + const mockSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -128,10 +130,10 @@ describe('useAllTransactions', () => { hasResults: true, isLoading: false, }, - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`]: searchTransaction, - }, - } as unknown as SearchResults; + data: {}, + }); + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`] = searchTransaction; + mockCurrentSearchResults = mockSearchResults; await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`, collectionTransaction); const {result} = renderHook(() => useAllTransactions()); @@ -148,7 +150,7 @@ describe('useAllTransactions', () => { const transaction = createRandomTransaction(1); transaction.transactionID = 'txn1'; - mockCurrentSearchResults = { + const mockSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -156,11 +158,11 @@ describe('useAllTransactions', () => { hasResults: true, isLoading: false, }, - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`]: transaction, - [`${ONYXKEYS.COLLECTION.REPORT}report1`]: {reportID: 'report1'}, - }, - } as unknown as SearchResults; + data: {}, + }); + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`] = transaction; + mockSearchResults.data[`${ONYXKEYS.COLLECTION.REPORT}report1`] = createMock({reportID: 'report1'}); + mockCurrentSearchResults = mockSearchResults; const {result} = renderHook(() => useAllTransactions()); @@ -176,7 +178,7 @@ describe('useAllTransactions', () => { }); it('should handle empty collection and empty search results', async () => { - mockCurrentSearchResults = { + mockCurrentSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -185,7 +187,7 @@ describe('useAllTransactions', () => { isLoading: false, }, data: {}, - } as unknown as SearchResults; + }); const {result} = renderHook(() => useAllTransactions()); @@ -200,7 +202,7 @@ describe('useAllTransactions', () => { const transaction = createRandomTransaction(1); transaction.transactionID = 'txn1'; - mockCurrentSearchResults = { + const mockSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -208,12 +210,14 @@ describe('useAllTransactions', () => { hasResults: true, isLoading: false, }, - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`]: transaction, - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn2`]: null, - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn3`]: undefined, - }, - } as unknown as SearchResults; + data: {}, + }); + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`] = transaction; + // @ts-expect-error Intentionally exercise the runtime guard with a null transaction entry. + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn2`] = null; + // @ts-expect-error Intentionally exercise the runtime guard with an undefined transaction entry. + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn3`] = undefined; + mockCurrentSearchResults = mockSearchResults; const {result} = renderHook(() => useAllTransactions()); @@ -264,7 +268,7 @@ describe('useAllTransactions', () => { transaction1.transactionID = 'txn1'; transaction2.transactionID = 'txn2'; - mockCurrentSearchResults = { + const mockSearchResults = createMock({ search: { offset: 0, type: CONST.SEARCH.DATA_TYPES.EXPENSE, @@ -272,11 +276,11 @@ describe('useAllTransactions', () => { hasResults: true, isLoading: false, }, - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`]: transaction1, - [`${ONYXKEYS.COLLECTION.TRANSACTION}txn2`]: transaction2, - }, - } as unknown as SearchResults; + data: {}, + }); + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn1`] = transaction1; + mockSearchResults.data[`${ONYXKEYS.COLLECTION.TRANSACTION}txn2`] = transaction2; + mockCurrentSearchResults = mockSearchResults; const {result} = renderHook(() => useAllTransactions());