Skip to content

Commit

Permalink
Merge pull request #37396 from ruben-rebelo/ts-migration/group3-tests
Browse files Browse the repository at this point in the history
[No QA][TS migration] Migrate multiple test to typescript
  • Loading branch information
mountiny authored Mar 27, 2024
2 parents 0509f8d + 3b081fd commit e10d4f7
Show file tree
Hide file tree
Showing 12 changed files with 368 additions and 383 deletions.
18 changes: 17 additions & 1 deletion src/types/onyx/Transaction.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type {KeysOfUnion, ValueOf} from 'type-fest';
import type CONST from '@src/CONST';
import type ONYXKEYS from '@src/ONYXKEYS';
import type CollectionDataSet from '@src/types/utils/CollectionDataSet';
import type {Participant, Split} from './IOU';
import type * as OnyxCommon from './OnyxCommon';
import type RecentWaypoint from './RecentWaypoint';
Expand Down Expand Up @@ -224,5 +226,19 @@ type AdditionalTransactionChanges = {

type TransactionChanges = Partial<Transaction> & AdditionalTransactionChanges;

type TransactionCollectionDataSet = CollectionDataSet<typeof ONYXKEYS.COLLECTION.TRANSACTION>;

export default Transaction;
export type {WaypointCollection, Comment, Receipt, Waypoint, ReceiptError, ReceiptErrors, TransactionPendingFieldsKey, TransactionChanges, TaxRate, ReceiptSource};
export type {
WaypointCollection,
Comment,
Receipt,
Waypoint,
ReceiptError,
ReceiptErrors,
TransactionPendingFieldsKey,
TransactionChanges,
TaxRate,
ReceiptSource,
TransactionCollectionDataSet,
};
84 changes: 29 additions & 55 deletions tests/e2e/compare/compare.js → tests/e2e/compare/compare.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import _ from 'underscore';
import type {Stats} from '../measure/math';
import getStats from '../measure/math';
import * as math from './math';
import type {Entry} from './output/console';
import printToConsole from './output/console';
import writeToMarkdown from './output/markdown';

type Metric = Record<string, number[]>;

/*
* base implementation from: https://github.com/callstack/reassure/blob/main/packages/reassure-compare/src/compare.ts
* This module reads from the baseline and compare files and compares the results.
Expand All @@ -25,14 +28,7 @@ const PROBABILITY_CONSIDERED_SIGNIFICANCE = 0.02;
*/
const DURATION_DIFF_THRESHOLD_SIGNIFICANCE = 100;

/**
*
* @param {string} name
* @param {Object} compare
* @param {Object} baseline
* @returns {Object}
*/
function buildCompareEntry(name, compare, baseline) {
function buildCompareEntry(name: string, compare: Stats, baseline: Stats): Entry {
const diff = compare.mean - baseline.mean;
const relativeDurationDiff = diff / baseline.mean;

Expand All @@ -53,62 +49,40 @@ function buildCompareEntry(name, compare, baseline) {

/**
* Compare results between baseline and current entries and categorize.
*
* @param {Object} compareEntries
* @param {Object} baselineEntries
* @returns {Object}
*/
function compareResults(compareEntries, baselineEntries) {
function compareResults(compareEntries: Metric | string, baselineEntries: Metric | string) {
// Unique test scenario names
const names = [...new Set([..._.keys(compareEntries), ..._.keys(baselineEntries || {})])];

const compared = [];
const added = [];
const removed = [];

names.forEach((name) => {
const current = compareEntries[name];
const baseline = baselineEntries[name];

const currentStats = getStats(baseline);
const deltaStats = getStats(current);

if (baseline && current) {
compared.push(buildCompareEntry(name, deltaStats, currentStats));
} else if (current) {
added.push({
name,
current,
});
} else if (baseline) {
removed.push({
name,
baseline,
});
}
});

const significance = _.chain(compared)
.filter((item) => item.isDurationDiffOfSignificance)
.value();
const meaningless = _.chain(compared)
.filter((item) => !item.isDurationDiffOfSignificance)
.value();

added.sort((a, b) => b.current.mean - a.current.mean);
removed.sort((a, b) => b.baseline.mean - a.baseline.mean);
const baselineKeys = Object.keys(baselineEntries ?? {});
const names = Array.from(new Set([...baselineKeys]));

const compared: Entry[] = [];

if (typeof compareEntries !== 'string' && typeof baselineEntries !== 'string') {
names.forEach((name: string) => {
const current = compareEntries[name];
const baseline = baselineEntries[name];

const currentStats = getStats(baseline);
const deltaStats = getStats(current);

if (baseline && current) {
compared.push(buildCompareEntry(name, deltaStats, currentStats));
}
});
}
const significance = compared.filter((item) => item.isDurationDiffOfSignificance);

const meaningless = compared.filter((item) => !item.isDurationDiffOfSignificance);

return {
significance,
meaningless,
added,
removed,
};
}

export default (main, delta, outputFile, outputFormat = 'all') => {
export default (main: Metric | string, delta: Metric | string, outputFile: string, outputFormat = 'all') => {
// IMPORTANT NOTE: make sure you are passing the delta/compare results first, then the main/baseline results:
const outputData = compareResults(delta, main);
const outputData = compareResults(main, main);

if (outputFormat === 'console' || outputFormat === 'all') {
printToConsole(outputData);
Expand Down
1 change: 0 additions & 1 deletion tests/e2e/measure/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,4 @@ const getStats = (entries: Entries): Stats => {
};

export default getStats;

export type {Stats};
2 changes: 0 additions & 2 deletions tests/perf-test/ReportScreen.perf-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,6 @@ const reportActions = ReportTestUtils.getMockedReportActionsMap(500);
const mockRoute = {params: {reportID: '1'}};

test('[ReportScreen] should render ReportScreen with composer interactions', () => {
// @ts-expect-error TODO: Remove this once TestHelper (https://github.com/Expensify/App/issues/25318) is migrated to TypeScript.
const {triggerTransitionEnd, addListener} = TestHelper.createAddListenerMock();
const scenario = async () => {
/**
Expand Down Expand Up @@ -232,7 +231,6 @@ test('[ReportScreen] should render ReportScreen with composer interactions', ()
});

test('[ReportScreen] should press of the report item', () => {
// @ts-expect-error TODO: Remove this once TestHelper (https://github.com/Expensify/App/issues/25318) is migrated to TypeScript.
const {triggerTransitionEnd, addListener} = TestHelper.createAddListenerMock();
const scenario = async () => {
/**
Expand Down
4 changes: 0 additions & 4 deletions tests/perf-test/SearchPage.perf-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ function SearchPageWrapper(args: SearchPageProps) {
}

test('[Search Page] should interact when text input changes', async () => {
// @ts-expect-error TODO: Remove this once TestHelper (https://github.com/Expensify/App/issues/25318) is migrated to TypeScript.
const {addListener} = TestHelper.createAddListenerMock();

const scenario = async () => {
Expand Down Expand Up @@ -165,7 +164,6 @@ test('[Search Page] should interact when text input changes', async () => {
});

test('[Search Page] should render selection list', async () => {
// @ts-expect-error TODO: Remove this once TestHelper (https://github.com/Expensify/App/issues/25318) is migrated to TypeScript.
const {triggerTransitionEnd, addListener} = TestHelper.createAddListenerMock();
const smallMockedPersonalDetails = getMockedPersonalDetails(5);

Expand Down Expand Up @@ -195,7 +193,6 @@ test('[Search Page] should render selection list', async () => {
});

test('[Search Page] should search in selection list', async () => {
// @ts-expect-error TODO: Remove this once TestHelper (https://github.com/Expensify/App/issues/25318) is migrated to TypeScript.
const {triggerTransitionEnd, addListener} = TestHelper.createAddListenerMock();

const scenario = async () => {
Expand Down Expand Up @@ -227,7 +224,6 @@ test('[Search Page] should search in selection list', async () => {
});

test('[Search Page] should click on list item', async () => {
// @ts-expect-error TODO: Remove this once TestHelper (https://github.com/Expensify/App/issues/25318) is migrated to TypeScript.
const {triggerTransitionEnd, addListener} = TestHelper.createAddListenerMock();

const scenario = async () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/UnreadIndicatorsTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ function signInAndGetAppWithUnreadChat(): Promise<void> {
lastActorAccountID: USER_B_ACCOUNT_ID,
type: CONST.REPORT.TYPE.CHAT,
});
const createdReportActionID = NumberUtils.rand64();
const createdReportActionID = NumberUtils.rand64().toString();
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {
[createdReportActionID]: {
actionName: CONST.REPORT.ACTIONS.TYPE.CREATED,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import Onyx from 'react-native-onyx';
import _ from 'underscore';
import CONST from '../../src/CONST';
import * as CurrencyUtils from '../../src/libs/CurrencyUtils';
import LocaleListener from '../../src/libs/Localize/LocaleListener';
import ONYXKEYS from '../../src/ONYXKEYS';
import CONST from '@src/CONST';
import * as CurrencyUtils from '@src/libs/CurrencyUtils';
import LocaleListener from '@src/libs/Localize/LocaleListener';
import ONYXKEYS from '@src/ONYXKEYS';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
// This file can get outdated. In that case, you can follow these steps to update it:
// - open your browser console and navigate to the Network tab
Expand All @@ -13,7 +12,7 @@ import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
// - update currencyList.json
import currencyList from './currencyList.json';

const currencyCodeList = _.keys(currencyList);
const currencyCodeList = Object.keys(currencyList);
const AVAILABLE_LOCALES = [CONST.LOCALES.EN, CONST.LOCALES.ES];

describe('CurrencyUtils', () => {
Expand All @@ -37,7 +36,7 @@ describe('CurrencyUtils', () => {
describe('getLocalizedCurrencySymbol', () => {
test.each(AVAILABLE_LOCALES)('Returns non empty string for all currencyCode with preferredLocale %s', (prefrredLocale) =>
Onyx.set(ONYXKEYS.NVP_PREFERRED_LOCALE, prefrredLocale).then(() => {
_.forEach(currencyCodeList, (currencyCode) => {
currencyCodeList.forEach((currencyCode: string) => {
const localizedSymbol = CurrencyUtils.getLocalizedCurrencySymbol(currencyCode);

expect(localizedSymbol).toBeTruthy();
Expand Down
42 changes: 22 additions & 20 deletions tests/unit/IOUUtilsTest.js → tests/unit/IOUUtilsTest.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import Onyx from 'react-native-onyx';
import * as IOUUtils from '../../src/libs/IOUUtils';
import * as ReportUtils from '../../src/libs/ReportUtils';
import * as TransactionUtils from '../../src/libs/TransactionUtils';
import ONYXKEYS from '../../src/ONYXKEYS';
import * as IOUUtils from '@src/libs/IOUUtils';
import * as ReportUtils from '@src/libs/ReportUtils';
import * as TransactionUtils from '@src/libs/TransactionUtils';
import ONYXKEYS from '@src/ONYXKEYS';
import type {TransactionCollectionDataSet} from '@src/types/onyx/Transaction';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
import currencyList from './currencyList.json';

Expand All @@ -25,34 +26,35 @@ describe('IOUUtils', () => {
});

test('Requesting money offline in a different currency will show the pending conversion message', () => {
const iouReport = ReportUtils.buildOptimisticIOUReport(1, 2, 100, 1, 'USD');
const iouReport = ReportUtils.buildOptimisticIOUReport(1, 2, 100, '1', 'USD');
const usdPendingTransaction = TransactionUtils.buildOptimisticTransaction(100, 'USD', iouReport.reportID);
const aedPendingTransaction = TransactionUtils.buildOptimisticTransaction(100, 'AED', iouReport.reportID);
const MergeQueries: TransactionCollectionDataSet = {};
MergeQueries[`${ONYXKEYS.COLLECTION.TRANSACTION}${usdPendingTransaction.transactionID}`] = usdPendingTransaction;
MergeQueries[`${ONYXKEYS.COLLECTION.TRANSACTION}${aedPendingTransaction.transactionID}`] = aedPendingTransaction;

return Onyx.mergeCollection(ONYXKEYS.COLLECTION.TRANSACTION, {
[`${ONYXKEYS.COLLECTION.TRANSACTION}${usdPendingTransaction.transactionID}`]: usdPendingTransaction,
[`${ONYXKEYS.COLLECTION.TRANSACTION}${aedPendingTransaction.transactionID}`]: aedPendingTransaction,
}).then(() => {
return Onyx.mergeCollection(ONYXKEYS.COLLECTION.TRANSACTION, MergeQueries).then(() => {
// We requested money offline in a different currency, we don't know the total of the iouReport until we're back online
expect(IOUUtils.isIOUReportPendingCurrencyConversion(iouReport)).toBe(true);
});
});

test('Requesting money online in a different currency will not show the pending conversion message', () => {
const iouReport = ReportUtils.buildOptimisticIOUReport(2, 3, 100, 1, 'USD');
const iouReport = ReportUtils.buildOptimisticIOUReport(2, 3, 100, '1', 'USD');
const usdPendingTransaction = TransactionUtils.buildOptimisticTransaction(100, 'USD', iouReport.reportID);
const aedPendingTransaction = TransactionUtils.buildOptimisticTransaction(100, 'AED', iouReport.reportID);

return Onyx.mergeCollection(ONYXKEYS.COLLECTION.TRANSACTION, {
[`${ONYXKEYS.COLLECTION.TRANSACTION}${usdPendingTransaction.transactionID}`]: {
...usdPendingTransaction,
pendingAction: null,
},
[`${ONYXKEYS.COLLECTION.TRANSACTION}${aedPendingTransaction.transactionID}`]: {
...aedPendingTransaction,
pendingAction: null,
},
}).then(() => {
const MergeQueries: TransactionCollectionDataSet = {};
MergeQueries[`${ONYXKEYS.COLLECTION.TRANSACTION}${usdPendingTransaction.transactionID}`] = {
...usdPendingTransaction,
pendingAction: null,
};
MergeQueries[`${ONYXKEYS.COLLECTION.TRANSACTION}${aedPendingTransaction.transactionID}`] = {
...aedPendingTransaction,
pendingAction: null,
};

return Onyx.mergeCollection(ONYXKEYS.COLLECTION.TRANSACTION, MergeQueries).then(() => {
// We requested money online in a different currency, we know the iouReport total and there's no need to show the pending conversion message
expect(IOUUtils.isIOUReportPendingCurrencyConversion(iouReport)).toBe(false);
});
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/MiddlewareTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('Middleware', () => {
},
{
command: 'AddComment',
data: {authToken: 'testToken', reportID: '1234', reportActionID: '5678', reportComment: 'foo'},
data: {authToken: 'testToken', reportID: '1234', reportActionID: '5678'},
},
];
for (const request of requests) {
Expand All @@ -50,7 +50,7 @@ describe('Middleware', () => {

expect(global.fetch).toHaveBeenCalledTimes(2);
expect(global.fetch).toHaveBeenLastCalledWith('https://www.expensify.com.dev/api/AddComment?', expect.anything());
TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body, {reportID: '1234', reportActionID: '5678', reportComment: 'foo'});
TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body, {reportID: '1234', reportActionID: '5678'});
expect(global.fetch).toHaveBeenNthCalledWith(1, 'https://www.expensify.com.dev/api/OpenReport?', expect.anything());
TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[0][1].body, {reportID: '1234'});
});
Expand All @@ -64,7 +64,7 @@ describe('Middleware', () => {
},
{
command: 'AddComment',
data: {authToken: 'testToken', reportID: '1234', reportActionID: '5678', reportComment: 'foo'},
data: {authToken: 'testToken', reportID: '1234', reportActionID: '5678'},
},
];
for (const request of requests) {
Expand Down Expand Up @@ -94,7 +94,7 @@ describe('Middleware', () => {

expect(global.fetch).toHaveBeenCalledTimes(2);
expect(global.fetch).toHaveBeenLastCalledWith('https://www.expensify.com.dev/api/AddComment?', expect.anything());
TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body, {reportID: '5555', reportActionID: '5678', reportComment: 'foo'});
TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[1][1].body, {reportID: '5555', reportActionID: '5678'});
expect(global.fetch).toHaveBeenNthCalledWith(1, 'https://www.expensify.com.dev/api/OpenReport?', expect.anything());
TestHelper.assertFormDataMatchesObject((global.fetch as jest.Mock).mock.calls[0][1].body, {reportID: '1234'});
});
Expand Down
Loading

0 comments on commit e10d4f7

Please sign in to comment.