From 82445012d0fb8f0a695b13df50409e5361dbdb2f Mon Sep 17 00:00:00 2001 From: Pedro Guerreiro Date: Thu, 28 Mar 2024 18:41:14 +0000 Subject: [PATCH 1/3] Reapply "[No QA] Migrate 'OptionsListUtilsTest.js', 'DateUtilsTest.js', 'SidebarLinks.perf-test.js', 'markdown.js' and 'ReportUtilsTest.js' to Typescript" This reverts commit 39aaa567d352e8a43538886ea614c745d1b8c03a. --- src/libs/DateUtils.ts | 2 +- src/libs/OptionsListUtils.ts | 2 +- src/libs/ReportUtils.ts | 6 +- tests/e2e/compare/output/console.ts | 4 +- .../output/{markdown.js => markdown.ts} | 65 +-- ...erf-test.js => SidebarLinks.perf-test.tsx} | 39 +- .../{DateUtilsTest.js => DateUtilsTest.ts} | 57 +-- ...stUtilsTest.js => OptionsListUtilsTest.ts} | 389 ++++++++++++------ ...{ReportUtilsTest.js => ReportUtilsTest.ts} | 202 +++++---- 9 files changed, 479 insertions(+), 287 deletions(-) rename tests/e2e/compare/output/{markdown.js => markdown.ts} (57%) rename tests/perf-test/{SidebarLinks.perf-test.js => SidebarLinks.perf-test.tsx} (79%) rename tests/unit/{DateUtilsTest.js => DateUtilsTest.ts} (85%) rename tests/unit/{OptionsListUtilsTest.js => OptionsListUtilsTest.ts} (86%) rename tests/unit/{ReportUtilsTest.js => ReportUtilsTest.ts} (84%) diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index 4d4f8d42568..44c7682b47f 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -267,7 +267,7 @@ function formatToLongDateWithWeekday(datetime: string | Date): string { * @returns Sunday */ function formatToDayOfWeek(datetime: Date): string { - return format(new Date(datetime), CONST.DATE.WEEKDAY_TIME_FORMAT); + return format(datetime, CONST.DATE.WEEKDAY_TIME_FORMAT); } /** diff --git a/src/libs/OptionsListUtils.ts b/src/libs/OptionsListUtils.ts index cf988eb8aef..ab057a4c10e 100644 --- a/src/libs/OptionsListUtils.ts +++ b/src/libs/OptionsListUtils.ts @@ -2095,4 +2095,4 @@ export { getTaxRatesSection, }; -export type {MemberForList, CategorySection, GetOptions, PayeePersonalDetails, Category}; +export type {MemberForList, CategorySection, CategoryTreeSection, GetOptions, PayeePersonalDetails, Category, Tag}; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index ea6f08a3a2b..a76967d00d2 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -28,6 +28,7 @@ import type { ReportMetadata, Session, Task, + TaxRate, Transaction, TransactionViolation, UserWallet, @@ -405,6 +406,9 @@ type OptionData = { isDisabled?: boolean | null; name?: string | null; isSelfDM?: boolean | null; + reportID?: string; + enabled?: boolean; + data?: Partial; } & Report; type OnyxDataTaskAssigneeChat = { @@ -959,7 +963,7 @@ function filterReportsByPolicyIDAndMemberAccountIDs(reports: Report[], policyMem /** * Given an array of reports, return them sorted by the last read timestamp. */ -function sortReportsByLastRead(reports: Report[], reportMetadata: OnyxCollection): Array> { +function sortReportsByLastRead(reports: Array>, reportMetadata: OnyxCollection): Array> { return reports .filter((report) => !!report?.reportID && !!(reportMetadata?.[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${report.reportID}`]?.lastVisitTime ?? report?.lastReadTime)) .sort((a, b) => { diff --git a/tests/e2e/compare/output/console.ts b/tests/e2e/compare/output/console.ts index de8e5d91389..3da0100b603 100644 --- a/tests/e2e/compare/output/console.ts +++ b/tests/e2e/compare/output/console.ts @@ -13,6 +13,8 @@ type Entry = { type Data = { significance: Entry[]; meaningless: Entry[]; + errors: string[]; + warnings: string[]; }; const printRegularLine = (entry: Entry) => { @@ -36,4 +38,4 @@ export default (data: Data) => { console.debug(''); }; -export type {Entry}; +export type {Data, Entry}; diff --git a/tests/e2e/compare/output/markdown.js b/tests/e2e/compare/output/markdown.ts similarity index 57% rename from tests/e2e/compare/output/markdown.js rename to tests/e2e/compare/output/markdown.ts index 119830a5bb2..34bc3251c42 100644 --- a/tests/e2e/compare/output/markdown.js +++ b/tests/e2e/compare/output/markdown.ts @@ -1,80 +1,85 @@ // From: https://raw.githubusercontent.com/callstack/reassure/main/packages/reassure-compare/src/output/markdown.ts import fs from 'node:fs/promises'; import path from 'path'; -import _ from 'underscore'; +import type {Stats} from 'tests/e2e/measure/math'; import * as Logger from '../../utils/logger'; +import type {Data, Entry} from './console'; import * as format from './format'; import markdownTable from './markdownTable'; const tableHeader = ['Name', 'Duration']; -const collapsibleSection = (title, content) => `
\n${title}\n\n${content}\n
\n\n`; +const collapsibleSection = (title: string, content: string) => `
\n${title}\n\n${content}\n
\n\n`; -const buildDurationDetails = (title, entry) => { +const buildDurationDetails = (title: string, entry: Stats) => { const relativeStdev = entry.stdev / entry.mean; - return _.filter( - [ - `**${title}**`, - `Mean: ${format.formatDuration(entry.mean)}`, - `Stdev: ${format.formatDuration(entry.stdev)} (${format.formatPercent(relativeStdev)})`, - entry.entries ? `Runs: ${entry.entries.join(' ')}` : '', - ], - Boolean, - ).join('
'); + return [ + `**${title}**`, + `Mean: ${format.formatDuration(entry.mean)}`, + `Stdev: ${format.formatDuration(entry.stdev)} (${format.formatPercent(relativeStdev)})`, + entry.entries ? `Runs: ${entry.entries.join(' ')}` : '', + ] + .filter(Boolean) + .join('
'); }; -const buildDurationDetailsEntry = (entry) => - _.filter(['baseline' in entry ? buildDurationDetails('Baseline', entry.baseline) : '', 'current' in entry ? buildDurationDetails('Current', entry.current) : ''], Boolean).join( - '

', - ); +const buildDurationDetailsEntry = (entry: Entry) => + ['baseline' in entry ? buildDurationDetails('Baseline', entry.baseline) : '', 'current' in entry ? buildDurationDetails('Current', entry.current) : ''] + .filter(Boolean) + .join('

'); + +const formatEntryDuration = (entry: Entry): string => { + let formattedDuration = ''; -const formatEntryDuration = (entry) => { if ('baseline' in entry && 'current' in entry) { - return format.formatDurationDiffChange(entry); + formattedDuration = format.formatDurationDiffChange(entry); } + if ('baseline' in entry) { - return format.formatDuration(entry.baseline.mean); + formattedDuration = format.formatDuration(entry.baseline.mean); } + if ('current' in entry) { - return format.formatDuration(entry.current.mean); + formattedDuration = format.formatDuration(entry.current.mean); } - return ''; + + return formattedDuration; }; -const buildDetailsTable = (entries) => { +const buildDetailsTable = (entries: Entry[]) => { if (!entries.length) { return ''; } - const rows = _.map(entries, (entry) => [entry.name, buildDurationDetailsEntry(entry)]); + const rows = entries.map((entry) => [entry.name, buildDurationDetailsEntry(entry)]); const content = markdownTable([tableHeader, ...rows]); return collapsibleSection('Show details', content); }; -const buildSummaryTable = (entries, collapse = false) => { +const buildSummaryTable = (entries: Entry[], collapse = false) => { if (!entries.length) { return '_There are no entries_'; } - const rows = _.map(entries, (entry) => [entry.name, formatEntryDuration(entry)]); + const rows = entries.map((entry) => [entry.name, formatEntryDuration(entry)]); const content = markdownTable([tableHeader, ...rows]); return collapse ? collapsibleSection('Show entries', content) : content; }; -const buildMarkdown = (data) => { +const buildMarkdown = (data: Data) => { let result = '## Performance Comparison Report πŸ“Š'; - if (data.errors && data.errors.length) { + if (data.errors?.length) { result += '\n\n### Errors\n'; data.errors.forEach((message) => { result += ` 1. πŸ›‘ ${message}\n`; }); } - if (data.warnings && data.warnings.length) { + if (data.warnings?.length) { result += '\n\n### Warnings\n'; data.warnings.forEach((message) => { result += ` 1. 🟑 ${message}\n`; @@ -92,7 +97,7 @@ const buildMarkdown = (data) => { return result; }; -const writeToFile = (filePath, content) => +const writeToFile = (filePath: string, content: string) => fs .writeFile(filePath, content) .then(() => { @@ -106,7 +111,7 @@ const writeToFile = (filePath, content) => throw error; }); -const writeToMarkdown = (filePath, data) => { +const writeToMarkdown = (filePath: string, data: Data) => { const markdown = buildMarkdown(data); return writeToFile(filePath, markdown).catch((error) => { console.error(error); diff --git a/tests/perf-test/SidebarLinks.perf-test.js b/tests/perf-test/SidebarLinks.perf-test.tsx similarity index 79% rename from tests/perf-test/SidebarLinks.perf-test.js rename to tests/perf-test/SidebarLinks.perf-test.tsx index 0b10718fd0c..2848015d5c6 100644 --- a/tests/perf-test/SidebarLinks.perf-test.js +++ b/tests/perf-test/SidebarLinks.perf-test.tsx @@ -1,32 +1,33 @@ import {fireEvent, screen} from '@testing-library/react-native'; import Onyx from 'react-native-onyx'; import {measurePerformance} from 'reassure'; -import _ from 'underscore'; -import CONST from '../../src/CONST'; -import ONYXKEYS from '../../src/ONYXKEYS'; -import variables from '../../src/styles/variables'; +import variables from '@styles/variables'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; import * as LHNTestUtils from '../utils/LHNTestUtils'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; import wrapOnyxWithWaitForBatchedUpdates from '../utils/wrapOnyxWithWaitForBatchedUpdates'; -jest.mock('../../src/libs/Permissions'); -jest.mock('../../src/hooks/usePermissions.ts'); -jest.mock('../../src/libs/Navigation/Navigation'); -jest.mock('../../src/components/Icon/Expensicons'); +jest.mock('@libs/Permissions'); +jest.mock('@hooks/usePermissions.ts'); +jest.mock('@libs/Navigation/Navigation'); +jest.mock('@components/Icon/Expensicons'); jest.mock('@react-navigation/native'); const getMockedReportsMap = (length = 100) => { - const mockReports = Array.from({length}, (__, i) => { - const reportID = i + 1; - const participants = [1, 2]; - const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${reportID}`; - const report = LHNTestUtils.getFakeReport(participants, 1, true); - - return {[reportKey]: report}; - }); - - return _.assign({}, ...mockReports); + const mockReports = Object.fromEntries( + Array.from({length}, (value, index) => { + const reportID = index + 1; + const participants = [1, 2]; + const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${reportID}`; + const report = LHNTestUtils.getFakeReport(participants, 1, true); + + return [reportKey, report]; + }), + ); + + return mockReports; }; const mockedResponseMap = getMockedReportsMap(500); @@ -36,11 +37,9 @@ describe('SidebarLinks', () => { Onyx.init({ keys: ONYXKEYS, safeEvictionKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS], - registerStorageEventListener: () => {}, }); Onyx.multiSet({ - [ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.DEFAULT, [ONYXKEYS.PERSONAL_DETAILS_LIST]: LHNTestUtils.fakePersonalDetails, [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS], [ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.GSD, diff --git a/tests/unit/DateUtilsTest.js b/tests/unit/DateUtilsTest.ts similarity index 85% rename from tests/unit/DateUtilsTest.js rename to tests/unit/DateUtilsTest.ts index a752eea1a99..a7f43ea8404 100644 --- a/tests/unit/DateUtilsTest.js +++ b/tests/unit/DateUtilsTest.ts @@ -1,9 +1,11 @@ +/* eslint-disable @typescript-eslint/naming-convention */ import {addDays, addMinutes, format, setHours, setMinutes, subDays, subHours, subMinutes, subSeconds} from 'date-fns'; import {format as tzFormat, utcToZonedTime} from 'date-fns-tz'; import Onyx from 'react-native-onyx'; -import CONST from '../../src/CONST'; -import DateUtils from '../../src/libs/DateUtils'; -import ONYXKEYS from '../../src/ONYXKEYS'; +import DateUtils from '@libs/DateUtils'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {SelectedTimezone} from '@src/types/onyx/PersonalDetails'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; const LOCALE = CONST.LOCALES.EN; @@ -14,13 +16,14 @@ describe('DateUtils', () => { keys: ONYXKEYS, initialKeyStates: { [ONYXKEYS.SESSION]: {accountID: 999}, - [ONYXKEYS.PERSONAL_DETAILS_LIST]: {999: {timezone: {selected: UTC}}}, + [ONYXKEYS.PERSONAL_DETAILS_LIST]: {'999': {accountID: 999, timezone: {selected: 'Europe/London'}}}, }, }); return waitForBatchedUpdates(); }); afterEach(() => { + jest.restoreAllMocks(); jest.useRealTimers(); Onyx.clear(); }); @@ -39,7 +42,7 @@ describe('DateUtils', () => { }); it('formatToDayOfWeek should return a weekday', () => { - const weekDay = DateUtils.formatToDayOfWeek(datetime); + const weekDay = DateUtils.formatToDayOfWeek(new Date(datetime)); expect(weekDay).toBe('Monday'); }); it('formatToLocalTime should return a date in a local format', () => { @@ -53,32 +56,35 @@ describe('DateUtils', () => { }); it('should fallback to current date when getLocalDateFromDatetime is failing', () => { - const localDate = DateUtils.getLocalDateFromDatetime(LOCALE, undefined, 'InvalidTimezone'); + const localDate = DateUtils.getLocalDateFromDatetime(LOCALE, undefined, 'InvalidTimezone' as SelectedTimezone); expect(localDate.getTime()).not.toBeNaN(); }); it('should return the date in calendar time when calling datetimeToCalendarTime', () => { - const today = setMinutes(setHours(new Date(), 14), 32); + const today = setMinutes(setHours(new Date(), 14), 32).toString(); expect(DateUtils.datetimeToCalendarTime(LOCALE, today)).toBe('Today at 2:32 PM'); - const tomorrow = addDays(setMinutes(setHours(new Date(), 14), 32), 1); + const tomorrow = addDays(setMinutes(setHours(new Date(), 14), 32), 1).toString(); expect(DateUtils.datetimeToCalendarTime(LOCALE, tomorrow)).toBe('Tomorrow at 2:32 PM'); - const yesterday = setMinutes(setHours(subDays(new Date(), 1), 7), 43); + const yesterday = setMinutes(setHours(subDays(new Date(), 1), 7), 43).toString(); expect(DateUtils.datetimeToCalendarTime(LOCALE, yesterday)).toBe('Yesterday at 7:43 AM'); - const date = setMinutes(setHours(new Date('2022-11-05'), 10), 17); + const date = setMinutes(setHours(new Date('2022-11-05'), 10), 17).toString(); expect(DateUtils.datetimeToCalendarTime(LOCALE, date)).toBe('Nov 5, 2022 at 10:17 AM'); - const todayLowercaseDate = setMinutes(setHours(new Date(), 14), 32); + const todayLowercaseDate = setMinutes(setHours(new Date(), 14), 32).toString(); expect(DateUtils.datetimeToCalendarTime(LOCALE, todayLowercaseDate, false, undefined, true)).toBe('today at 2:32 PM'); }); it('should update timezone if automatic and selected timezone do not match', () => { - Intl.DateTimeFormat = jest.fn(() => ({ - resolvedOptions: () => ({timeZone: 'America/Chicago'}), - })); - Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, {999: {timezone: {selected: UTC, automatic: true}}}).then(() => { + jest.spyOn(Intl, 'DateTimeFormat').mockImplementation( + () => + ({ + resolvedOptions: () => ({timeZone: 'America/Chicago'}), + } as Intl.DateTimeFormat), + ); + Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, {'999': {accountID: 999, timezone: {selected: 'Europe/London', automatic: true}}}).then(() => { const result = DateUtils.getCurrentTimezone(); expect(result).toEqual({ selected: 'America/Chicago', @@ -88,10 +94,13 @@ describe('DateUtils', () => { }); it('should not update timezone if automatic and selected timezone match', () => { - Intl.DateTimeFormat = jest.fn(() => ({ - resolvedOptions: () => ({timeZone: UTC}), - })); - Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, {999: {timezone: {selected: UTC, automatic: true}}}).then(() => { + jest.spyOn(Intl, 'DateTimeFormat').mockImplementation( + () => + ({ + resolvedOptions: () => ({timeZone: UTC}), + } as Intl.DateTimeFormat), + ); + Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, {'999': {accountID: 999, timezone: {selected: 'Europe/London', automatic: true}}}).then(() => { const result = DateUtils.getCurrentTimezone(); expect(result).toEqual({ selected: UTC, @@ -102,7 +111,7 @@ describe('DateUtils', () => { it('canUpdateTimezone should return true when lastUpdatedTimezoneTime is more than 5 minutes ago', () => { // Use fake timers to control the current time - jest.useFakeTimers('modern'); + jest.useFakeTimers(); jest.setSystemTime(addMinutes(new Date(), 6)); const isUpdateTimezoneAllowed = DateUtils.canUpdateTimezone(); expect(isUpdateTimezoneAllowed).toBe(true); @@ -110,20 +119,20 @@ describe('DateUtils', () => { it('canUpdateTimezone should return false when lastUpdatedTimezoneTime is less than 5 minutes ago', () => { // Use fake timers to control the current time - jest.useFakeTimers('modern'); + jest.useFakeTimers(); jest.setSystemTime(addMinutes(new Date(), 4)); const isUpdateTimezoneAllowed = DateUtils.canUpdateTimezone(); expect(isUpdateTimezoneAllowed).toBe(false); }); it('should return the date in calendar time when calling datetimeToRelative', () => { - const aFewSecondsAgo = subSeconds(new Date(), 10); + const aFewSecondsAgo = subSeconds(new Date(), 10).toString(); expect(DateUtils.datetimeToRelative(LOCALE, aFewSecondsAgo)).toBe('less than a minute ago'); - const aMinuteAgo = subMinutes(new Date(), 1); + const aMinuteAgo = subMinutes(new Date(), 1).toString(); expect(DateUtils.datetimeToRelative(LOCALE, aMinuteAgo)).toBe('1 minute ago'); - const anHourAgo = subHours(new Date(), 1); + const anHourAgo = subHours(new Date(), 1).toString(); expect(DateUtils.datetimeToRelative(LOCALE, anHourAgo)).toBe('about 1 hour ago'); }); diff --git a/tests/unit/OptionsListUtilsTest.js b/tests/unit/OptionsListUtilsTest.ts similarity index 86% rename from tests/unit/OptionsListUtilsTest.js rename to tests/unit/OptionsListUtilsTest.ts index 2f3e65c0c38..afa9b00ebc6 100644 --- a/tests/unit/OptionsListUtilsTest.js +++ b/tests/unit/OptionsListUtilsTest.ts @@ -1,30 +1,35 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; -import _ from 'underscore'; -import CONST from '../../src/CONST'; -import * as OptionsListUtils from '../../src/libs/OptionsListUtils'; -import * as ReportUtils from '../../src/libs/ReportUtils'; -import ONYXKEYS from '../../src/ONYXKEYS'; +import CONST from '@src/CONST'; +import type {Tag} from '@src/libs/OptionsListUtils'; +import * as OptionsListUtils from '@src/libs/OptionsListUtils'; +import * as ReportUtils from '@src/libs/ReportUtils'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {PersonalDetails, Policy, PolicyCategories, Report, TaxRatesWithDefault} from '@src/types/onyx'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; +type PersonalDetailsList = Record; + describe('OptionsListUtils', () => { // Given a set of reports with both single participants and multiple participants some pinned and some not - const REPORTS = { - 1: { + const REPORTS: OnyxCollection = { + '1': { lastReadTime: '2021-01-14 11:25:39.295', lastVisibleActionCreated: '2022-11-22 03:26:02.015', isPinned: false, - reportID: 1, + reportID: '1', participantAccountIDs: [2, 1], visibleChatMemberAccountIDs: [2, 1], reportName: 'Iron Man, Mister Fantastic', hasDraft: true, type: CONST.REPORT.TYPE.CHAT, }, - 2: { + '2': { lastReadTime: '2021-01-14 11:25:39.296', lastVisibleActionCreated: '2022-11-22 03:26:02.016', isPinned: false, - reportID: 2, + reportID: '2', participantAccountIDs: [3], visibleChatMemberAccountIDs: [3], reportName: 'Spider-Man', @@ -32,41 +37,41 @@ describe('OptionsListUtils', () => { }, // This is the only report we are pinning in this test - 3: { + '3': { lastReadTime: '2021-01-14 11:25:39.297', lastVisibleActionCreated: '2022-11-22 03:26:02.170', isPinned: true, - reportID: 3, + reportID: '3', participantAccountIDs: [1], visibleChatMemberAccountIDs: [1], reportName: 'Mister Fantastic', type: CONST.REPORT.TYPE.CHAT, }, - 4: { + '4': { lastReadTime: '2021-01-14 11:25:39.298', lastVisibleActionCreated: '2022-11-22 03:26:02.180', isPinned: false, - reportID: 4, + reportID: '4', participantAccountIDs: [4], visibleChatMemberAccountIDs: [4], reportName: 'Black Panther', type: CONST.REPORT.TYPE.CHAT, }, - 5: { + '5': { lastReadTime: '2021-01-14 11:25:39.299', lastVisibleActionCreated: '2022-11-22 03:26:02.019', isPinned: false, - reportID: 5, + reportID: '5', participantAccountIDs: [5], visibleChatMemberAccountIDs: [5], reportName: 'Invisible Woman', type: CONST.REPORT.TYPE.CHAT, }, - 6: { + '6': { lastReadTime: '2021-01-14 11:25:39.300', lastVisibleActionCreated: '2022-11-22 03:26:02.020', isPinned: false, - reportID: 6, + reportID: '6', participantAccountIDs: [6], visibleChatMemberAccountIDs: [6], reportName: 'Thor', @@ -74,11 +79,11 @@ describe('OptionsListUtils', () => { }, // Note: This report has the largest lastVisibleActionCreated - 7: { + '7': { lastReadTime: '2021-01-14 11:25:39.301', lastVisibleActionCreated: '2022-11-22 03:26:03.999', isPinned: false, - reportID: 7, + reportID: '7', participantAccountIDs: [7], visibleChatMemberAccountIDs: [7], reportName: 'Captain America', @@ -86,11 +91,11 @@ describe('OptionsListUtils', () => { }, // Note: This report has no lastVisibleActionCreated - 8: { + '8': { lastReadTime: '2021-01-14 11:25:39.301', lastVisibleActionCreated: '2022-11-22 03:26:02.000', isPinned: false, - reportID: 8, + reportID: '8', participantAccountIDs: [12], visibleChatMemberAccountIDs: [12], reportName: 'Silver Surfer', @@ -98,23 +103,23 @@ describe('OptionsListUtils', () => { }, // Note: This report has an IOU - 9: { + '9': { lastReadTime: '2021-01-14 11:25:39.302', lastVisibleActionCreated: '2022-11-22 03:26:02.998', isPinned: false, - reportID: 9, + reportID: '9', participantAccountIDs: [8], visibleChatMemberAccountIDs: [8], reportName: 'Mister Sinister', - iouReportID: 100, + iouReportID: '100', type: CONST.REPORT.TYPE.CHAT, }, // This report is an archived room – it does not have a name and instead falls back on oldPolicyName - 10: { + '10': { lastReadTime: '2021-01-14 11:25:39.200', lastVisibleActionCreated: '2022-11-22 03:26:02.001', - reportID: 10, + reportID: '10', isPinned: false, participantAccountIDs: [2, 7], visibleChatMemberAccountIDs: [2, 7], @@ -131,71 +136,81 @@ describe('OptionsListUtils', () => { }; // And a set of personalDetails some with existing reports and some without - const PERSONAL_DETAILS = { + const PERSONAL_DETAILS: PersonalDetailsList = { // These exist in our reports - 1: { + '1': { accountID: 1, displayName: 'Mister Fantastic', login: 'reedrichards@expensify.com', isSelected: true, + reportID: '1', }, - 2: { + '2': { accountID: 2, displayName: 'Iron Man', login: 'tonystark@expensify.com', + reportID: '1', }, - 3: { + '3': { accountID: 3, displayName: 'Spider-Man', login: 'peterparker@expensify.com', + reportID: '1', }, - 4: { + '4': { accountID: 4, displayName: 'Black Panther', login: 'tchalla@expensify.com', + reportID: '1', }, - 5: { + '5': { accountID: 5, displayName: 'Invisible Woman', login: 'suestorm@expensify.com', + reportID: '1', }, - 6: { + '6': { accountID: 6, displayName: 'Thor', login: 'thor@expensify.com', + reportID: '1', }, - 7: { + '7': { accountID: 7, displayName: 'Captain America', login: 'steverogers@expensify.com', + reportID: '1', }, - 8: { + '8': { accountID: 8, displayName: 'Mr Sinister', login: 'mistersinister@marauders.com', + reportID: '1', }, // These do not exist in reports at all - 9: { + '9': { accountID: 9, displayName: 'Black Widow', login: 'natasharomanoff@expensify.com', + reportID: '', }, - 10: { + '10': { accountID: 10, displayName: 'The Incredible Hulk', login: 'brucebanner@expensify.com', + reportID: '', }, }; - const REPORTS_WITH_CONCIERGE = { + const REPORTS_WITH_CONCIERGE: OnyxCollection = { ...REPORTS, - 11: { + '11': { lastReadTime: '2021-01-14 11:25:39.302', lastVisibleActionCreated: '2022-11-22 03:26:02.022', isPinned: false, - reportID: 11, + reportID: '11', participantAccountIDs: [999], visibleChatMemberAccountIDs: [999], reportName: 'Concierge', @@ -203,13 +218,13 @@ describe('OptionsListUtils', () => { }, }; - const REPORTS_WITH_CHRONOS = { + const REPORTS_WITH_CHRONOS: OnyxCollection = { ...REPORTS, - 12: { + '12': { lastReadTime: '2021-01-14 11:25:39.302', lastVisibleActionCreated: '2022-11-22 03:26:02.022', isPinned: false, - reportID: 12, + reportID: '12', participantAccountIDs: [1000], visibleChatMemberAccountIDs: [1000], reportName: 'Chronos', @@ -217,13 +232,13 @@ describe('OptionsListUtils', () => { }, }; - const REPORTS_WITH_RECEIPTS = { + const REPORTS_WITH_RECEIPTS: OnyxCollection = { ...REPORTS, - 13: { + '13': { lastReadTime: '2021-01-14 11:25:39.302', lastVisibleActionCreated: '2022-11-22 03:26:02.022', isPinned: false, - reportID: 13, + reportID: '13', participantAccountIDs: [1001], visibleChatMemberAccountIDs: [1001], reportName: 'Receipts', @@ -231,67 +246,77 @@ describe('OptionsListUtils', () => { }, }; - const REPORTS_WITH_WORKSPACE_ROOMS = { + const REPORTS_WITH_WORKSPACE_ROOMS: OnyxCollection = { ...REPORTS, - 14: { + '14': { lastReadTime: '2021-01-14 11:25:39.302', lastVisibleActionCreated: '2022-11-22 03:26:02.022', isPinned: false, - reportID: 14, + reportID: '14', participantAccountIDs: [1, 10, 3], visibleChatMemberAccountIDs: [1, 10, 3], reportName: '', oldPolicyName: 'Avengers Room', - isArchivedRoom: false, chatType: CONST.REPORT.CHAT_TYPE.POLICY_ADMINS, isOwnPolicyExpenseChat: true, type: CONST.REPORT.TYPE.CHAT, }, }; - const PERSONAL_DETAILS_WITH_CONCIERGE = { + const PERSONAL_DETAILS_WITH_CONCIERGE: PersonalDetailsList = { ...PERSONAL_DETAILS, - 999: { + '999': { accountID: 999, displayName: 'Concierge', login: 'concierge@expensify.com', + reportID: '', }, }; - const PERSONAL_DETAILS_WITH_CHRONOS = { + const PERSONAL_DETAILS_WITH_CHRONOS: PersonalDetailsList = { ...PERSONAL_DETAILS, - 1000: { + '1000': { accountID: 1000, displayName: 'Chronos', login: 'chronos@expensify.com', + reportID: '', }, }; - const PERSONAL_DETAILS_WITH_RECEIPTS = { + const PERSONAL_DETAILS_WITH_RECEIPTS: PersonalDetailsList = { ...PERSONAL_DETAILS, - 1001: { + '1001': { accountID: 1001, displayName: 'Receipts', login: 'receipts@expensify.com', + reportID: '', }, }; - const PERSONAL_DETAILS_WITH_PERIODS = { + const PERSONAL_DETAILS_WITH_PERIODS: PersonalDetailsList = { ...PERSONAL_DETAILS, - 1002: { + '1002': { accountID: 1002, displayName: 'The Flash', login: 'barry.allen@expensify.com', + reportID: '', }, }; - const POLICY = { - policyID: 'ABC123', + const policyID = 'ABC123'; + + const POLICY: Policy = { + id: policyID, name: 'Hero Policy', + role: 'user', + type: 'free', + owner: '', + outputCurrency: '', + isPolicyExpenseChatEnabled: false, }; // Set the currently logged in user, report data, and personal details @@ -300,11 +325,12 @@ describe('OptionsListUtils', () => { keys: ONYXKEYS, initialKeyStates: { [ONYXKEYS.SESSION]: {accountID: 2, email: 'tonystark@expensify.com'}, - [`${ONYXKEYS.COLLECTION.REPORT}100`]: { + [`${ONYXKEYS.COLLECTION.REPORT}100` as const]: { + reportID: '', ownerAccountID: 8, - total: '1000', + total: 1000, }, - [`${ONYXKEYS.COLLECTION.POLICY}${POLICY.policyID}`]: POLICY, + [`${ONYXKEYS.COLLECTION.POLICY}${policyID}` as const]: POLICY, }, }); Onyx.registerLogger(() => {}); @@ -319,7 +345,7 @@ describe('OptionsListUtils', () => { expect(results.personalDetails.length).toBe(2); // Then all of the reports should be shown including the archived rooms. - expect(results.recentReports.length).toBe(_.size(REPORTS)); + expect(results.recentReports.length).toBe(Object.values(REPORTS).length); // When we filter again but provide a searchValue results = OptionsListUtils.getSearchOptions(REPORTS, PERSONAL_DETAILS, 'spider'); @@ -360,7 +386,7 @@ describe('OptionsListUtils', () => { // We should expect all personalDetails to be returned, // minus the currently logged in user and recent reports count - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS) - 1 - MAX_RECENT_REPORTS); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS).length - 1 - MAX_RECENT_REPORTS); // We should expect personal details sorted alphabetically expect(results.personalDetails[0].text).toBe('Black Widow'); @@ -369,11 +395,11 @@ describe('OptionsListUtils', () => { expect(results.personalDetails[3].text).toBe('The Incredible Hulk'); // Then the result which has an existing report should also have the reportID attached - const personalDetailWithExistingReport = _.find(results.personalDetails, (personalDetail) => personalDetail.login === 'peterparker@expensify.com'); - expect(personalDetailWithExistingReport.reportID).toBe(2); + const personalDetailWithExistingReport = results.personalDetails.find((personalDetail) => personalDetail.login === 'peterparker@expensify.com'); + expect(personalDetailWithExistingReport?.reportID).toBe('2'); // When we only pass personal details - results = OptionsListUtils.getFilteredOptions([], PERSONAL_DETAILS, [], ''); + results = OptionsListUtils.getFilteredOptions({}, PERSONAL_DETAILS, [], ''); // We should expect personal details sorted alphabetically expect(results.personalDetails[0].text).toBe('Black Panther'); @@ -414,28 +440,28 @@ describe('OptionsListUtils', () => { // Concierge is included in the results by default. We should expect all the personalDetails to show // (minus the 5 that are already showing and the currently logged in user) - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_CONCIERGE) - 1 - MAX_RECENT_REPORTS); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_CONCIERGE).length - 1 - MAX_RECENT_REPORTS); expect(results.recentReports).toEqual(expect.arrayContaining([expect.objectContaining({login: 'concierge@expensify.com'})])); // Test by excluding Concierge from the results results = OptionsListUtils.getFilteredOptions(REPORTS_WITH_CONCIERGE, PERSONAL_DETAILS_WITH_CONCIERGE, [], '', [], [CONST.EMAIL.CONCIERGE]); // All the personalDetails should be returned minus the currently logged in user and Concierge - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_CONCIERGE) - 2 - MAX_RECENT_REPORTS); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_CONCIERGE).length - 2 - MAX_RECENT_REPORTS); expect(results.personalDetails).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'concierge@expensify.com'})])); // Test by excluding Chronos from the results results = OptionsListUtils.getFilteredOptions(REPORTS_WITH_CHRONOS, PERSONAL_DETAILS_WITH_CHRONOS, [], '', [], [CONST.EMAIL.CHRONOS]); // All the personalDetails should be returned minus the currently logged in user and Concierge - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_CHRONOS) - 2 - MAX_RECENT_REPORTS); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_CHRONOS).length - 2 - MAX_RECENT_REPORTS); expect(results.personalDetails).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'chronos@expensify.com'})])); // Test by excluding Receipts from the results results = OptionsListUtils.getFilteredOptions(REPORTS_WITH_RECEIPTS, PERSONAL_DETAILS_WITH_RECEIPTS, [], '', [], [CONST.EMAIL.RECEIPTS]); // All the personalDetails should be returned minus the currently logged in user and Concierge - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_RECEIPTS) - 2 - MAX_RECENT_REPORTS); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_RECEIPTS).length - 2 - MAX_RECENT_REPORTS); expect(results.personalDetails).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'receipts@expensify.com'})])); }); @@ -448,7 +474,7 @@ describe('OptionsListUtils', () => { // And we should expect all the personalDetails to show (minus the 5 that are already // showing and the currently logged in user) - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS) - 6); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS).length - 6); // We should expect personal details sorted alphabetically expect(results.personalDetails[0].text).toBe('Black Widow'); @@ -457,8 +483,8 @@ describe('OptionsListUtils', () => { expect(results.personalDetails[3].text).toBe('The Incredible Hulk'); // And none of our personalDetails should include any of the users with recent reports - const reportLogins = _.map(results.recentReports, (reportOption) => reportOption.login); - const personalDetailsOverlapWithReports = _.every(results.personalDetails, (personalDetailOption) => _.contains(reportLogins, personalDetailOption.login)); + const reportLogins = results.recentReports.map((reportOption) => reportOption.login); + const personalDetailsOverlapWithReports = results.personalDetails.every((personalDetailOption) => reportLogins.includes(personalDetailOption.login)); expect(personalDetailsOverlapWithReports).toBe(false); // When we search for an option that is only in a personalDetail with no existing report @@ -487,15 +513,15 @@ describe('OptionsListUtils', () => { // Then one of our older report options (not in our five most recent) should appear in the personalDetails // but not in recentReports - expect(_.every(results.recentReports, (option) => option.login !== 'peterparker@expensify.com')).toBe(true); - expect(_.every(results.personalDetails, (option) => option.login !== 'peterparker@expensify.com')).toBe(false); + expect(results.recentReports.every((option) => option.login !== 'peterparker@expensify.com')).toBe(true); + expect(results.personalDetails.every((option) => option.login !== 'peterparker@expensify.com')).toBe(false); // When we provide a "selected" option to getFilteredOptions() results = OptionsListUtils.getFilteredOptions(REPORTS, PERSONAL_DETAILS, [], '', [{login: 'peterparker@expensify.com'}]); // Then the option should not appear anywhere in either list - expect(_.every(results.recentReports, (option) => option.login !== 'peterparker@expensify.com')).toBe(true); - expect(_.every(results.personalDetails, (option) => option.login !== 'peterparker@expensify.com')).toBe(true); + expect(results.recentReports.every((option) => option.login !== 'peterparker@expensify.com')).toBe(true); + expect(results.personalDetails.every((option) => option.login !== 'peterparker@expensify.com')).toBe(true); // When we add a search term for which no options exist and the searchValue itself // is not a potential email or phone @@ -531,7 +557,7 @@ describe('OptionsListUtils', () => { expect(results.recentReports.length).toBe(0); expect(results.personalDetails.length).toBe(0); expect(results.userToInvite).not.toBe(null); - expect(results.userToInvite.login).toBe('+15005550006'); + expect(results.userToInvite?.login).toBe('+15005550006'); // When we add a search term for which no options exist and the searchValue itself // is a potential phone number with country code added @@ -542,7 +568,7 @@ describe('OptionsListUtils', () => { expect(results.recentReports.length).toBe(0); expect(results.personalDetails.length).toBe(0); expect(results.userToInvite).not.toBe(null); - expect(results.userToInvite.login).toBe('+15005550006'); + expect(results.userToInvite?.login).toBe('+15005550006'); // When we add a search term for which no options exist and the searchValue itself // is a potential phone number with special characters added @@ -553,7 +579,7 @@ describe('OptionsListUtils', () => { expect(results.recentReports.length).toBe(0); expect(results.personalDetails.length).toBe(0); expect(results.userToInvite).not.toBe(null); - expect(results.userToInvite.login).toBe('+18003243233'); + expect(results.userToInvite?.login).toBe('+18003243233'); // When we use a search term for contact number that contains alphabet characters results = OptionsListUtils.getFilteredOptions(REPORTS, PERSONAL_DETAILS, [], '998243aaaa'); @@ -568,7 +594,7 @@ describe('OptionsListUtils', () => { // Concierge is included in the results by default. We should expect all the personalDetails to show // (minus the 5 that are already showing and the currently logged in user) - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_CONCIERGE) - 6); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_CONCIERGE).length - 6); expect(results.recentReports).toEqual(expect.arrayContaining([expect.objectContaining({login: 'concierge@expensify.com'})])); // Test by excluding Concierge from the results @@ -576,7 +602,7 @@ describe('OptionsListUtils', () => { // We should expect all the personalDetails to show (minus the 5 that are already showing, // the currently logged in user and Concierge) - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_CONCIERGE) - 7); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_CONCIERGE).length - 7); expect(results.personalDetails).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'concierge@expensify.com'})])); expect(results.recentReports).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'concierge@expensify.com'})])); @@ -585,7 +611,7 @@ describe('OptionsListUtils', () => { // We should expect all the personalDetails to show (minus the 5 that are already showing, // the currently logged in user and Concierge) - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_CHRONOS) - 7); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_CHRONOS).length - 7); expect(results.personalDetails).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'chronos@expensify.com'})])); expect(results.recentReports).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'chronos@expensify.com'})])); @@ -594,26 +620,27 @@ describe('OptionsListUtils', () => { // We should expect all the personalDetails to show (minus the 5 that are already showing, // the currently logged in user and Concierge) - expect(results.personalDetails.length).toBe(_.size(PERSONAL_DETAILS_WITH_RECEIPTS) - 7); + expect(results.personalDetails.length).toBe(Object.values(PERSONAL_DETAILS_WITH_RECEIPTS).length - 7); expect(results.personalDetails).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'receipts@expensify.com'})])); expect(results.recentReports).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'receipts@expensify.com'})])); }); it('getShareDestinationsOptions()', () => { // Filter current REPORTS as we do in the component, before getting share destination options - const filteredReports = {}; - _.keys(REPORTS).forEach((reportKey) => { - if (!ReportUtils.canUserPerformWriteAction(REPORTS[reportKey]) || ReportUtils.isExpensifyOnlyParticipantInReport(REPORTS[reportKey])) { - return; + const filteredReports = Object.entries(REPORTS).reduce>>((reports, [reportKey, report]) => { + if (!ReportUtils.canUserPerformWriteAction(report) || ReportUtils.isExpensifyOnlyParticipantInReport(report)) { + return reports; } - filteredReports[reportKey] = REPORTS[reportKey]; - }); + // eslint-disable-next-line no-param-reassign + reports[reportKey] = report; + return reports; + }, {}); // When we pass an empty search value let results = OptionsListUtils.getShareDestinationOptions(filteredReports, PERSONAL_DETAILS, [], ''); // Then we should expect all the recent reports to show but exclude the archived rooms - expect(results.recentReports.length).toBe(_.size(REPORTS) - 1); + expect(results.recentReports.length).toBe(Object.values(REPORTS).length - 1); // When we pass a search value that doesn't match the group chat name results = OptionsListUtils.getShareDestinationOptions(filteredReports, PERSONAL_DETAILS, [], 'mutants'); @@ -628,20 +655,19 @@ describe('OptionsListUtils', () => { expect(results.recentReports.length).toBe(1); // Filter current REPORTS_WITH_WORKSPACE_ROOMS as we do in the component, before getting share destination options - const filteredReportsWithWorkspaceRooms = {}; - _.keys(REPORTS_WITH_WORKSPACE_ROOMS).forEach((reportKey) => { - if (!ReportUtils.canUserPerformWriteAction(REPORTS_WITH_WORKSPACE_ROOMS[reportKey]) || ReportUtils.isExpensifyOnlyParticipantInReport(REPORTS_WITH_WORKSPACE_ROOMS[reportKey])) { - return; + const filteredReportsWithWorkspaceRooms = Object.entries(REPORTS_WITH_WORKSPACE_ROOMS).reduce>>((reports, [reportKey, report]) => { + if (!ReportUtils.canUserPerformWriteAction(report) || ReportUtils.isExpensifyOnlyParticipantInReport(report)) { + return reports; } - filteredReportsWithWorkspaceRooms[reportKey] = REPORTS_WITH_WORKSPACE_ROOMS[reportKey]; - }); + return {...reports, [reportKey]: report}; + }, {}); // When we also have a policy to return rooms in the results results = OptionsListUtils.getShareDestinationOptions(filteredReportsWithWorkspaceRooms, PERSONAL_DETAILS, [], ''); // Then we should expect the DMS, the group chats and the workspace room to show // We should expect all the recent reports to show, excluding the archived rooms - expect(results.recentReports.length).toBe(_.size(REPORTS_WITH_WORKSPACE_ROOMS) - 1); + expect(results.recentReports.length).toBe(Object.values(REPORTS_WITH_WORKSPACE_ROOMS).length - 1); // When we search for a workspace room results = OptionsListUtils.getShareDestinationOptions(filteredReportsWithWorkspaceRooms, PERSONAL_DETAILS, [], 'Avengers Room'); @@ -685,31 +711,51 @@ describe('OptionsListUtils', () => { const emptySearch = ''; const wrongSearch = 'bla bla'; const recentlyUsedCategories = ['Taxi', 'Restaurant']; - const selectedOptions = [ + const selectedOptions: Array> = [ { name: 'Medical', enabled: true, }, ]; - const smallCategoriesList = { + const smallCategoriesList: PolicyCategories = { Taxi: { enabled: false, name: 'Taxi', + unencodedName: 'Taxi', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, Restaurant: { enabled: true, name: 'Restaurant', + unencodedName: 'Restaurant', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, Food: { enabled: true, name: 'Food', + unencodedName: 'Food', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Food: Meat': { enabled: true, name: 'Food: Meat', + unencodedName: 'Food: Meat', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, }; - const smallResultList = [ + const smallResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: false, @@ -742,7 +788,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const smallSearchResultList = [ + const smallSearchResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: true, @@ -767,7 +813,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const smallWrongSearchResultList = [ + const smallWrongSearchResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: true, @@ -775,65 +821,135 @@ describe('OptionsListUtils', () => { data: [], }, ]; - const largeCategoriesList = { + const largeCategoriesList: PolicyCategories = { Taxi: { enabled: false, name: 'Taxi', + unencodedName: 'Taxi', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, Restaurant: { enabled: true, name: 'Restaurant', + unencodedName: 'Restaurant', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, Food: { enabled: true, name: 'Food', + unencodedName: 'Food', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Food: Meat': { enabled: true, name: 'Food: Meat', + unencodedName: 'Food: Meat', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Food: Milk': { enabled: true, name: 'Food: Milk', + unencodedName: 'Food: Milk', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Food: Vegetables': { enabled: false, name: 'Food: Vegetables', + unencodedName: 'Food: Vegetables', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Cars: Audi': { enabled: true, name: 'Cars: Audi', + unencodedName: 'Cars: Audi', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Cars: BMW': { enabled: false, name: 'Cars: BMW', + unencodedName: 'Cars: BMW', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Cars: Mercedes-Benz': { enabled: true, name: 'Cars: Mercedes-Benz', + unencodedName: 'Cars: Mercedes-Benz', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, Medical: { enabled: false, name: 'Medical', + unencodedName: 'Medical', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Travel: Meals': { enabled: true, name: 'Travel: Meals', + unencodedName: 'Travel: Meals', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Travel: Meals: Breakfast': { enabled: true, name: 'Travel: Meals: Breakfast', + unencodedName: 'Travel: Meals: Breakfast', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Travel: Meals: Dinner': { enabled: false, name: 'Travel: Meals: Dinner', + unencodedName: 'Travel: Meals: Dinner', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, 'Travel: Meals: Lunch': { enabled: true, name: 'Travel: Meals: Lunch', + unencodedName: 'Travel: Meals: Lunch', + areCommentsRequired: false, + 'GL Code': '', + externalID: '', + origin: '', }, }; - const largeResultList = [ + const largeResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: false, @@ -960,7 +1076,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const largeSearchResultList = [ + const largeSearchResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: true, @@ -993,7 +1109,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const largeWrongSearchResultList = [ + const largeWrongSearchResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: true, @@ -1002,7 +1118,7 @@ describe('OptionsListUtils', () => { }, ]; const emptyCategoriesList = {}; - const emptySelectedResultList = [ + const emptySelectedResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: false, @@ -1089,25 +1205,29 @@ describe('OptionsListUtils', () => { name: 'Medical', }, ]; - const smallTagsList = { + const smallTagsList: Record = { Engineering: { enabled: false, name: 'Engineering', + accountID: null, }, Medical: { enabled: true, name: 'Medical', + accountID: null, }, Accounting: { enabled: true, name: 'Accounting', + accountID: null, }, HR: { enabled: true, name: 'HR', + accountID: null, }, }; - const smallResultList = [ + const smallResultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: false, @@ -1138,7 +1258,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const smallSearchResultList = [ + const smallSearchResultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: true, @@ -1154,7 +1274,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const smallWrongSearchResultList = [ + const smallWrongSearchResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: true, @@ -1162,53 +1282,64 @@ describe('OptionsListUtils', () => { data: [], }, ]; - const largeTagsList = { + const largeTagsList: Record = { Engineering: { enabled: false, name: 'Engineering', + accountID: null, }, Medical: { enabled: true, name: 'Medical', + accountID: null, }, Accounting: { enabled: true, name: 'Accounting', + accountID: null, }, HR: { enabled: true, name: 'HR', + accountID: null, }, Food: { enabled: true, name: 'Food', + accountID: null, }, Traveling: { enabled: false, name: 'Traveling', + accountID: null, }, Cleaning: { enabled: true, name: 'Cleaning', + accountID: null, }, Software: { enabled: true, name: 'Software', + accountID: null, }, OfficeSupplies: { enabled: false, name: 'Office Supplies', + accountID: null, }, Taxes: { enabled: true, name: 'Taxes', + accountID: null, }, Benefits: { enabled: true, name: 'Benefits', + accountID: null, }, }; - const largeResultList = [ + const largeResultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: true, @@ -1295,7 +1426,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const largeSearchResultList = [ + const largeSearchResultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: true, @@ -1318,7 +1449,7 @@ describe('OptionsListUtils', () => { ], }, ]; - const largeWrongSearchResultList = [ + const largeWrongSearchResultList: OptionsListUtils.CategoryTreeSection[] = [ { title: '', shouldShow: true, @@ -2287,7 +2418,7 @@ describe('OptionsListUtils', () => { const emptySearch = ''; const wrongSearch = 'bla bla'; - const taxRatesWithDefault = { + const taxRatesWithDefault: TaxRatesWithDefault = { name: 'Tax', defaultExternalID: 'CODE1', defaultValue: '0%', @@ -2296,19 +2427,25 @@ describe('OptionsListUtils', () => { CODE2: { name: 'Tax rate 2', value: '3%', + code: 'CODE2', + modifiedName: 'Tax rate 2 (3%)', }, CODE3: { name: 'Tax option 3', value: '5%', + code: 'CODE3', + modifiedName: 'Tax option 3 (5%)', }, CODE1: { name: 'Tax exempt 1', value: '0%', + code: 'CODE1', + modifiedName: 'Tax exempt 1 (0%) β€’ Default', }, }, }; - const resultList = [ + const resultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: false, @@ -2361,7 +2498,7 @@ describe('OptionsListUtils', () => { }, ]; - const searchResultList = [ + const searchResultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: true, @@ -2385,7 +2522,7 @@ describe('OptionsListUtils', () => { }, ]; - const wrongSearchResultList = [ + const wrongSearchResultList: OptionsListUtils.CategorySection[] = [ { title: '', shouldShow: true, @@ -2406,7 +2543,7 @@ describe('OptionsListUtils', () => { }); it('formatMemberForList()', () => { - const formattedMembers = _.map(PERSONAL_DETAILS, (personalDetail) => OptionsListUtils.formatMemberForList(personalDetail)); + const formattedMembers = Object.values(PERSONAL_DETAILS).map((personalDetail) => OptionsListUtils.formatMemberForList(personalDetail)); // We're only formatting items inside the array, so the order should be the same as the original PERSONAL_DETAILS array expect(formattedMembers[0].text).toBe('Mister Fantastic'); @@ -2417,9 +2554,9 @@ describe('OptionsListUtils', () => { expect(formattedMembers[0].isSelected).toBe(true); // And all the others to be unselected - expect(_.every(formattedMembers.slice(1), (personalDetail) => !personalDetail.isSelected)).toBe(true); + expect(formattedMembers.slice(1).every((personalDetail) => !personalDetail.isSelected)).toBe(true); // `isDisabled` is always false - expect(_.every(formattedMembers, (personalDetail) => !personalDetail.isDisabled)).toBe(true); + expect(formattedMembers.every((personalDetail) => !personalDetail.isDisabled)).toBe(true); }); }); diff --git a/tests/unit/ReportUtilsTest.js b/tests/unit/ReportUtilsTest.ts similarity index 84% rename from tests/unit/ReportUtilsTest.js rename to tests/unit/ReportUtilsTest.ts index ffd5c9147dc..2daefdc0657 100644 --- a/tests/unit/ReportUtilsTest.js +++ b/tests/unit/ReportUtilsTest.ts @@ -1,42 +1,45 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import type {OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; -import _ from 'underscore'; -import CONST from '../../src/CONST'; +import * as ReportUtils from '@libs/ReportUtils'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {PersonalDetailsList, Policy, Report, ReportAction} from '@src/types/onyx'; +import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; import * as NumberUtils from '../../src/libs/NumberUtils'; -import * as ReportUtils from '../../src/libs/ReportUtils'; -import ONYXKEYS from '../../src/ONYXKEYS'; import * as LHNTestUtils from '../utils/LHNTestUtils'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; // Be sure to include the mocked permissions library or else the beta tests won't work -jest.mock('../../src/libs/Permissions'); +jest.mock('@libs/Permissions'); const currentUserEmail = 'bjorn@vikings.net'; const currentUserAccountID = 5; -const participantsPersonalDetails = { - 1: { +const participantsPersonalDetails: PersonalDetailsList = { + '1': { accountID: 1, displayName: 'Ragnar Lothbrok', firstName: 'Ragnar', login: 'ragnar@vikings.net', }, - 2: { + '2': { accountID: 2, login: 'floki@vikings.net', displayName: 'floki@vikings.net', }, - 3: { + '3': { accountID: 3, displayName: 'Lagertha Lothbrok', firstName: 'Lagertha', login: 'lagertha@vikings.net', pronouns: 'She/her', }, - 4: { + '4': { accountID: 4, login: '+18332403627@expensify.sms', displayName: '(833) 240-3627', }, - 5: { + '5': { accountID: 5, displayName: 'Lagertha Lothbrok', firstName: 'Lagertha', @@ -44,20 +47,27 @@ const participantsPersonalDetails = { pronouns: 'She/her', }, }; -const policy = { - policyID: 1, + +const policy: Policy = { + id: '1', name: 'Vikings Policy', + role: 'user', + type: 'free', + owner: '', + outputCurrency: '', + isPolicyExpenseChatEnabled: false, }; Onyx.init({keys: ONYXKEYS}); describe('ReportUtils', () => { beforeAll(() => { + const policyCollectionDataSet = toCollectionDataSet(ONYXKEYS.COLLECTION.POLICY, [policy], (current) => current.id); Onyx.multiSet({ [ONYXKEYS.PERSONAL_DETAILS_LIST]: participantsPersonalDetails, [ONYXKEYS.SESSION]: {email: currentUserEmail, accountID: currentUserAccountID}, [ONYXKEYS.COUNTRY_CODE]: 1, - [`${ONYXKEYS.COLLECTION.POLICY}${policy.policyID}`]: policy, + ...policyCollectionDataSet, }); return waitForBatchedUpdates(); }); @@ -107,6 +117,7 @@ describe('ReportUtils', () => { test('with displayName', () => { expect( ReportUtils.getReportName({ + reportID: '', participantAccountIDs: [currentUserAccountID, 1], }), ).toBe('Ragnar Lothbrok'); @@ -115,6 +126,7 @@ describe('ReportUtils', () => { test('no displayName', () => { expect( ReportUtils.getReportName({ + reportID: '', participantAccountIDs: [currentUserAccountID, 2], }), ).toBe('floki@vikings.net'); @@ -123,6 +135,7 @@ describe('ReportUtils', () => { test('SMS', () => { expect( ReportUtils.getReportName({ + reportID: '', participantAccountIDs: [currentUserAccountID, 4], }), ).toBe('(833) 240-3627'); @@ -132,6 +145,7 @@ describe('ReportUtils', () => { test('Group DM', () => { expect( ReportUtils.getReportName({ + reportID: '', participantAccountIDs: [currentUserAccountID, 1, 2, 3, 4], }), ).toBe('Ragnar, floki@vikings.net, Lagertha, (833) 240-3627'); @@ -139,6 +153,7 @@ describe('ReportUtils', () => { describe('Default Policy Room', () => { const baseAdminsRoom = { + reportID: '', chatType: CONST.REPORT.CHAT_TYPE.POLICY_ADMINS, reportName: '#admins', }; @@ -162,6 +177,7 @@ describe('ReportUtils', () => { describe('User-Created Policy Room', () => { const baseUserCreatedRoom = { + reportID: '', chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, reportName: '#VikingsChat', }; @@ -188,8 +204,9 @@ describe('ReportUtils', () => { test('as member', () => { expect( ReportUtils.getReportName({ + reportID: '', chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, - policyID: policy.policyID, + policyID: policy.id, isOwnPolicyExpenseChat: true, ownerAccountID: 1, }), @@ -199,8 +216,9 @@ describe('ReportUtils', () => { test('as admin', () => { expect( ReportUtils.getReportName({ + reportID: '', chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, - policyID: policy.policyID, + policyID: policy.id, isOwnPolicyExpenseChat: false, ownerAccountID: 1, }), @@ -210,9 +228,10 @@ describe('ReportUtils', () => { describe('Archived', () => { const baseArchivedPolicyExpenseChat = { + reportID: '', chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, ownerAccountID: 1, - policyID: policy.policyID, + policyID: policy.id, oldPolicyName: policy.name, statusNum: CONST.REPORT.STATUS_NUM.CLOSED, stateNum: CONST.REPORT.STATE_NUM.APPROVED, @@ -249,7 +268,7 @@ describe('ReportUtils', () => { describe('requiresAttentionFromCurrentUser', () => { it('returns false when there is no report', () => { - expect(ReportUtils.requiresAttentionFromCurrentUser()).toBe(false); + expect(ReportUtils.requiresAttentionFromCurrentUser(null)).toBe(false); }); it('returns false when the matched IOU report does not have an owner accountID', () => { const report = { @@ -324,7 +343,7 @@ describe('ReportUtils', () => { }); describe('getMoneyRequestOptions', () => { - const participantsAccountIDs = _.keys(participantsPersonalDetails); + const participantsAccountIDs = Object.keys(participantsPersonalDetails).map(Number); beforeAll(() => { Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, { @@ -339,8 +358,8 @@ describe('ReportUtils', () => { describe('return empty iou options if', () => { it('participants aray contains excluded expensify iou emails', () => { - const allEmpty = _.every(CONST.EXPENSIFY_ACCOUNT_IDS, (accountID) => { - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions({}, {}, [currentUserAccountID, accountID]); + const allEmpty = CONST.EXPENSIFY_ACCOUNT_IDS.every((accountID) => { + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(null, null, [currentUserAccountID, accountID]); return moneyRequestOptions.length === 0; }); expect(allEmpty).toBe(true); @@ -351,7 +370,7 @@ describe('ReportUtils', () => { ...LHNTestUtils.getFakeReport(), chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(0); }); @@ -361,7 +380,7 @@ describe('ReportUtils', () => { chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, isOwnPolicyExpenseChat: false, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(0); }); @@ -371,7 +390,7 @@ describe('ReportUtils', () => { type: CONST.REPORT.TYPE.IOU, statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(0); }); @@ -382,7 +401,7 @@ describe('ReportUtils', () => { stateNum: CONST.REPORT.STATE_NUM.APPROVED, statusNum: CONST.REPORT.STATUS_NUM.APPROVED, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(0); }); @@ -392,7 +411,7 @@ describe('ReportUtils', () => { type: CONST.REPORT.TYPE.EXPENSE, statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(0); }); @@ -406,15 +425,20 @@ describe('ReportUtils', () => { parentReportID: '100', type: CONST.REPORT.TYPE.EXPENSE, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(0); }); }); it("it is a submitted report tied to user's own policy expense chat and the policy does not have Instant Submit frequency", () => { - const paidPolicy = { + const paidPolicy: Policy = { id: '3f54cca8', type: CONST.POLICY.TYPE.TEAM, + name: '', + role: 'user', + owner: '', + outputCurrency: '', + isPolicyExpenseChatEnabled: false, }; Promise.all([ Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${paidPolicy.id}`, paidPolicy), @@ -440,17 +464,19 @@ describe('ReportUtils', () => { describe('return only iou split option if', () => { it('it is a chat room with more than one participant', () => { - const onlyHaveSplitOption = _.every( - [CONST.REPORT.CHAT_TYPE.POLICY_ADMINS, CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, CONST.REPORT.CHAT_TYPE.DOMAIN_ALL, CONST.REPORT.CHAT_TYPE.POLICY_ROOM], - (chatType) => { - const report = { - ...LHNTestUtils.getFakeReport(), - chatType, - }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, participantsAccountIDs[0]]); - return moneyRequestOptions.length === 1 && moneyRequestOptions.includes(CONST.IOU.TYPE.SPLIT); - }, - ); + const onlyHaveSplitOption = [ + CONST.REPORT.CHAT_TYPE.POLICY_ADMINS, + CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, + CONST.REPORT.CHAT_TYPE.DOMAIN_ALL, + CONST.REPORT.CHAT_TYPE.POLICY_ROOM, + ].every((chatType) => { + const report = { + ...LHNTestUtils.getFakeReport(), + chatType, + }; + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, participantsAccountIDs[0]]); + return moneyRequestOptions.length === 1 && moneyRequestOptions.includes(CONST.IOU.TYPE.SPLIT); + }); expect(onlyHaveSplitOption).toBe(true); }); @@ -459,7 +485,7 @@ describe('ReportUtils', () => { ...LHNTestUtils.getFakeReport(), chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, ...participantsAccountIDs]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, ...participantsAccountIDs]); expect(moneyRequestOptions.length).toBe(1); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.SPLIT)).toBe(true); }); @@ -469,7 +495,7 @@ describe('ReportUtils', () => { ...LHNTestUtils.getFakeReport(), chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, ...participantsAccountIDs]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, ...participantsAccountIDs]); expect(moneyRequestOptions.length).toBe(1); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.SPLIT)).toBe(true); }); @@ -480,7 +506,7 @@ describe('ReportUtils', () => { type: CONST.REPORT.TYPE.CHAT, participantsAccountIDs: [currentUserAccountID, ...participantsAccountIDs], }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, ...participantsAccountIDs]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, ...participantsAccountIDs.map(Number)]); expect(moneyRequestOptions.length).toBe(1); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.SPLIT)).toBe(true); }); @@ -498,7 +524,7 @@ describe('ReportUtils', () => { parentReportID: '102', type: CONST.REPORT.TYPE.EXPENSE, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID]); expect(moneyRequestOptions.length).toBe(1); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)).toBe(true); }); @@ -519,8 +545,14 @@ describe('ReportUtils', () => { }; const paidPolicy = { type: CONST.POLICY.TYPE.TEAM, - }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, paidPolicy, [currentUserAccountID, participantsAccountIDs[0]], true); + id: '', + name: '', + role: 'user', + owner: '', + outputCurrency: '', + isPolicyExpenseChatEnabled: false, + } as const; + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, paidPolicy, [currentUserAccountID, participantsAccountIDs[0]]); expect(moneyRequestOptions.length).toBe(1); }); }); @@ -532,7 +564,7 @@ describe('ReportUtils', () => { stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, participantsAccountIDs[0]]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, participantsAccountIDs[0]]); expect(moneyRequestOptions.length).toBe(1); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)).toBe(true); }); @@ -544,17 +576,22 @@ describe('ReportUtils', () => { stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, participantsAccountIDs[0]]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, participantsAccountIDs[0]]); expect(moneyRequestOptions.length).toBe(1); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)).toBe(true); }); it("it is a submitted expense report in user's own policyExpenseChat and the policy has Instant Submit frequency", () => { - const paidPolicy = { + const paidPolicy: Policy = { id: 'ef72dfeb', type: CONST.POLICY.TYPE.TEAM, autoReporting: true, autoReportingFrequency: CONST.POLICY.AUTO_REPORTING_FREQUENCIES.INSTANT, + name: '', + role: 'user', + owner: '', + outputCurrency: '', + isPolicyExpenseChatEnabled: false, }; Promise.all([ Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${paidPolicy.id}`, paidPolicy), @@ -585,7 +622,7 @@ describe('ReportUtils', () => { chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, isOwnPolicyExpenseChat: true, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, ...participantsAccountIDs]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, ...participantsAccountIDs]); expect(moneyRequestOptions.length).toBe(2); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)).toBe(true); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.SPLIT)).toBe(true); @@ -596,7 +633,7 @@ describe('ReportUtils', () => { ...LHNTestUtils.getFakeReport(), type: CONST.REPORT.TYPE.CHAT, }; - const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, {}, [currentUserAccountID, participantsAccountIDs[0]]); + const moneyRequestOptions = ReportUtils.getMoneyRequestOptions(report, null, [currentUserAccountID, participantsAccountIDs[0]]); expect(moneyRequestOptions.length).toBe(2); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)).toBe(true); expect(moneyRequestOptions.includes(CONST.IOU.TYPE.SEND)).toBe(true); @@ -622,21 +659,21 @@ describe('ReportUtils', () => { describe('sortReportsByLastRead', () => { it('should filter out report without reportID & lastReadTime and sort lastReadTime in ascending order', () => { - const reports = [ - {reportID: 1, lastReadTime: '2023-07-08 07:15:44.030'}, - {reportID: 2, lastReadTime: null}, - {reportID: 3, lastReadTime: '2023-07-06 07:15:44.030'}, - {reportID: 4, lastReadTime: '2023-07-07 07:15:44.030', type: CONST.REPORT.TYPE.IOU}, - {lastReadTime: '2023-07-09 07:15:44.030'}, - {reportID: 6}, - {}, + const reports: Array> = [ + {reportID: '1', lastReadTime: '2023-07-08 07:15:44.030'}, + {reportID: '2', lastReadTime: undefined}, + {reportID: '3', lastReadTime: '2023-07-06 07:15:44.030'}, + {reportID: '4', lastReadTime: '2023-07-07 07:15:44.030', type: CONST.REPORT.TYPE.IOU}, + {lastReadTime: '2023-07-09 07:15:44.030'} as Report, + {reportID: '6'}, + null, ]; - const sortedReports = [ - {reportID: 3, lastReadTime: '2023-07-06 07:15:44.030'}, - {reportID: 4, lastReadTime: '2023-07-07 07:15:44.030', type: CONST.REPORT.TYPE.IOU}, - {reportID: 1, lastReadTime: '2023-07-08 07:15:44.030'}, + const sortedReports: Array> = [ + {reportID: '3', lastReadTime: '2023-07-06 07:15:44.030'}, + {reportID: '4', lastReadTime: '2023-07-07 07:15:44.030', type: CONST.REPORT.TYPE.IOU}, + {reportID: '1', lastReadTime: '2023-07-08 07:15:44.030'}, ]; - expect(ReportUtils.sortReportsByLastRead(reports)).toEqual(sortedReports); + expect(ReportUtils.sortReportsByLastRead(reports, null)).toEqual(sortedReports); }); }); @@ -656,7 +693,7 @@ describe('ReportUtils', () => { '', [{login: 'email1@test.com'}, {login: 'email2@test.com'}], NumberUtils.rand64(), - ); + ) as ReportAction; expect(ReportUtils.shouldDisableThread(reportAction, reportID)).toBeTruthy(); }); @@ -672,7 +709,7 @@ describe('ReportUtils', () => { }, ], childVisibleActionCount: 1, - }; + } as ReportAction; expect(ReportUtils.shouldDisableThread(reportAction, reportID)).toBeFalsy(); reportAction.childVisibleActionCount = 0; @@ -688,7 +725,7 @@ describe('ReportUtils', () => { .then(() => { const reportAction = { childVisibleActionCount: 1, - }; + } as ReportAction; expect(ReportUtils.shouldDisableThread(reportAction, reportID)).toBeFalsy(); reportAction.childVisibleActionCount = 0; @@ -700,20 +737,20 @@ describe('ReportUtils', () => { const reportAction = { actionName: CONST.REPORT.ACTIONS.TYPE.MODIFIEDEXPENSE, whisperedToAccountIDs: [123456], - }; + } as ReportAction; expect(ReportUtils.shouldDisableThread(reportAction, reportID)).toBeTruthy(); }); it('should disable on thread first chat', () => { const reportAction = { childReportID: reportID, - }; + } as ReportAction; expect(ReportUtils.shouldDisableThread(reportAction, reportID)).toBeTruthy(); }); }); describe('getAllAncestorReportActions', () => { - const reports = [ + const reports: Report[] = [ {reportID: '1', lastReadTime: '2024-02-01 04:56:47.233', reportName: 'Report'}, {reportID: '2', lastReadTime: '2024-02-01 04:56:47.233', parentReportActionID: '1', parentReportID: '1', reportName: 'Report'}, {reportID: '3', lastReadTime: '2024-02-01 04:56:47.233', parentReportActionID: '2', parentReportID: '2', reportName: 'Report'}, @@ -721,24 +758,23 @@ describe('ReportUtils', () => { {reportID: '5', lastReadTime: '2024-02-01 04:56:47.233', parentReportActionID: '4', parentReportID: '4', reportName: 'Report'}, ]; - const reportActions = [ - {reportActionID: '1', created: '2024-02-01 04:42:22.965'}, - {reportActionID: '2', created: '2024-02-01 04:42:28.003'}, - {reportActionID: '3', created: '2024-02-01 04:42:31.742'}, - {reportActionID: '4', created: '2024-02-01 04:42:35.619'}, + const reportActions: ReportAction[] = [ + {reportActionID: '1', created: '2024-02-01 04:42:22.965', actionName: 'MARKEDREIMBURSED'}, + {reportActionID: '2', created: '2024-02-01 04:42:28.003', actionName: 'MARKEDREIMBURSED'}, + {reportActionID: '3', created: '2024-02-01 04:42:31.742', actionName: 'MARKEDREIMBURSED'}, + {reportActionID: '4', created: '2024-02-01 04:42:35.619', actionName: 'MARKEDREIMBURSED'}, ]; beforeAll(() => { + const reportCollectionDataSet = toCollectionDataSet(ONYXKEYS.COLLECTION.REPORT, reports, (report) => report.reportID); + const reportActionCollectionDataSet = toCollectionDataSet( + ONYXKEYS.COLLECTION.REPORT_ACTIONS, + reportActions.map((reportAction) => ({[reportAction.reportActionID]: reportAction})), + (actions) => Object.values(actions)[0].reportActionID, + ); Onyx.multiSet({ - [`${ONYXKEYS.COLLECTION.REPORT}${reports[0].reportID}`]: reports[0], - [`${ONYXKEYS.COLLECTION.REPORT}${reports[1].reportID}`]: reports[1], - [`${ONYXKEYS.COLLECTION.REPORT}${reports[2].reportID}`]: reports[2], - [`${ONYXKEYS.COLLECTION.REPORT}${reports[3].reportID}`]: reports[3], - [`${ONYXKEYS.COLLECTION.REPORT}${reports[4].reportID}`]: reports[4], - [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reports[0].reportID}`]: {[reportActions[0].reportActionID]: reportActions[0]}, - [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reports[1].reportID}`]: {[reportActions[1].reportActionID]: reportActions[1]}, - [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reports[2].reportID}`]: {[reportActions[2].reportActionID]: reportActions[2]}, - [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reports[3].reportID}`]: {[reportActions[3].reportActionID]: reportActions[3]}, + ...reportCollectionDataSet, + ...reportActionCollectionDataSet, }); return waitForBatchedUpdates(); }); From 8fc529a1712ff73b65fa637c77e9d7bdede36c0d Mon Sep 17 00:00:00 2001 From: Pedro Guerreiro Date: Thu, 28 Mar 2024 19:05:02 +0000 Subject: [PATCH 2/3] fix(typescript): jest tests and types --- src/libs/OptionsListUtils.ts | 2 +- tests/e2e/compare/output/console.ts | 4 ++-- tests/unit/OptionsListUtilsTest.ts | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/libs/OptionsListUtils.ts b/src/libs/OptionsListUtils.ts index ab057a4c10e..bf7ebf42f1a 100644 --- a/src/libs/OptionsListUtils.ts +++ b/src/libs/OptionsListUtils.ts @@ -2095,4 +2095,4 @@ export { getTaxRatesSection, }; -export type {MemberForList, CategorySection, CategoryTreeSection, GetOptions, PayeePersonalDetails, Category, Tag}; +export type {MemberForList, CategorySection, CategoryTreeSection, GetOptions, PayeePersonalDetails, Category}; diff --git a/tests/e2e/compare/output/console.ts b/tests/e2e/compare/output/console.ts index 3da0100b603..77170e43f4a 100644 --- a/tests/e2e/compare/output/console.ts +++ b/tests/e2e/compare/output/console.ts @@ -13,8 +13,8 @@ type Entry = { type Data = { significance: Entry[]; meaningless: Entry[]; - errors: string[]; - warnings: string[]; + errors?: string[]; + warnings?: string[]; }; const printRegularLine = (entry: Entry) => { diff --git a/tests/unit/OptionsListUtilsTest.ts b/tests/unit/OptionsListUtilsTest.ts index afa9b00ebc6..72f40ea5d98 100644 --- a/tests/unit/OptionsListUtilsTest.ts +++ b/tests/unit/OptionsListUtilsTest.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/naming-convention */ import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; +import type {SelectedTagOption} from '@components/TagPicker'; import CONST from '@src/CONST'; -import type {Tag} from '@src/libs/OptionsListUtils'; import * as OptionsListUtils from '@src/libs/OptionsListUtils'; import * as ReportUtils from '@src/libs/ReportUtils'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -1205,7 +1205,7 @@ describe('OptionsListUtils', () => { name: 'Medical', }, ]; - const smallTagsList: Record = { + const smallTagsList: Record = { Engineering: { enabled: false, name: 'Engineering', @@ -1282,7 +1282,7 @@ describe('OptionsListUtils', () => { data: [], }, ]; - const largeTagsList: Record = { + const largeTagsList: Record = { Engineering: { enabled: false, name: 'Engineering', @@ -2190,7 +2190,7 @@ describe('OptionsListUtils', () => { }); it('sortTags', () => { - const createTagObjects = (names) => _.map(names, (name) => ({name, enabled: true})); + const createTagObjects = (names: string[]) => names.map((name) => ({name, enabled: true})); const unorderedTagNames = ['10bc', 'b', '0a', '1', 'δΈ­ε›½', 'b10', '!', '2', '0', '@', 'a1', 'a', '3', 'b1', 'ζ—₯本', '$', '20', '20a', '#', 'a20', 'c', '10']; const expectedOrderNames = ['!', '#', '$', '0', '0a', '1', '10', '10bc', '2', '20', '20a', '3', '@', 'a', 'a1', 'a20', 'b', 'b1', 'b10', 'c', 'δΈ­ε›½', 'ζ—₯本']; From cf08e809cc19379cfe390f6ca082543aad09476c Mon Sep 17 00:00:00 2001 From: Pedro Guerreiro Date: Wed, 3 Apr 2024 09:49:48 +0100 Subject: [PATCH 3/3] chore(dateutilstest): revert selected timezone change to prevent tests failing because of daylight saving time --- tests/unit/DateUtilsTest.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/unit/DateUtilsTest.ts b/tests/unit/DateUtilsTest.ts index a7f43ea8404..9df0113168e 100644 --- a/tests/unit/DateUtilsTest.ts +++ b/tests/unit/DateUtilsTest.ts @@ -15,8 +15,20 @@ describe('DateUtils', () => { Onyx.init({ keys: ONYXKEYS, initialKeyStates: { - [ONYXKEYS.SESSION]: {accountID: 999}, - [ONYXKEYS.PERSONAL_DETAILS_LIST]: {'999': {accountID: 999, timezone: {selected: 'Europe/London'}}}, + [ONYXKEYS.SESSION]: { + accountID: 999, + }, + [ONYXKEYS.PERSONAL_DETAILS_LIST]: { + '999': { + accountID: 999, + timezone: { + // UTC is not recognized as a valid timezone but + // in these tests we want to use it to avoid issues + // because of daylight saving time + selected: UTC as SelectedTimezone, + }, + }, + }, }, }); return waitForBatchedUpdates();