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
26 changes: 19 additions & 7 deletions tests/ui/AuthScreensInitHandlerTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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(
<LocaleContextProvider>
Expand Down Expand Up @@ -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<ReportAttributesDerivedValue['reports']>({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});
Expand All @@ -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);
});

Expand All @@ -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();
});

Expand Down
27 changes: 12 additions & 15 deletions tests/ui/DynamicStateSelectionPageTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ jest.mock('@hooks/useLocalize', () =>
}

const [, stateKey, property] = key.split('.');
// stateKey is parsed from an `allStates.<key>.*` 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;
Expand Down Expand Up @@ -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));
Expand Down
18 changes: 11 additions & 7 deletions tests/ui/StateSelectorModalTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}`),
})),
);

Expand Down
27 changes: 12 additions & 15 deletions tests/unit/ChatGPTTranslatorTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type Locale from '@src/types/onyx/Locale';

jest.mock('@scripts/utils/OpenAIUtils');

const MockedOpenAIUtils = OpenAIUtils as jest.MockedClass<typeof OpenAIUtils>;
const mockedPromptResponses = jest.spyOn(OpenAIUtils.prototype, 'promptResponses');

/**
* Creates a mock response for promptResponses
Expand All @@ -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}!';
Expand All @@ -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);
});

Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
17 changes: 8 additions & 9 deletions tests/unit/DeeplinkRouteNormalizationTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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');
});
});
Expand Down
20 changes: 13 additions & 7 deletions tests/unit/FailureTrackingTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<OnyxKey> = {command: 'FailureTrackingTest'};

describe('FailureTracking middleware', () => {
beforeEach(() => {
reset();
Expand All @@ -12,31 +18,31 @@ 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);
});

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);
});

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);
});

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);
});
Expand All @@ -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);
});
});
Loading
Loading