From b199711695ef50814fc1ed80b68204b33ad7a410 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Fri, 9 Sep 2022 11:20:36 +0100 Subject: [PATCH 01/17] add new test files and mocks Add mock Fix UrbanAirship mock Get main drawer to render rename to navigation test Just render the sidebar links for now Fix tests and make ReportScreen render Add report action and verify the action renders Test for report-action-item visibility Mock disconnect for Pusher add way to set initial url for testing; Test for drawer status Test for the unread indicator Mock local notification and make sure only one notification appears upgrade test library dependencies and use act to get rid of weird warning undo test version bumps Fix tests Add comment Test behavior of unread indicator in report and sidebar Rename back to unread indicators Test new messages badge indicator refactor and improve Report screen visibility check Update mock for AppState Clear new line indicator when report page is in view and we return from background remove extra logs add JSDocs Check the LHN lastMessageText Fix ReportTest Check for pendingAction when deleting comment Fix deleted comments not showing strikethrough while offline Stop allowing deletion or editing of pendingAction add comments as users cannot be updated correctly via sequenceNumber Rollback some changes Use sequenceNumber for handledReportActions for now Remove log add doc --- .../@react-native-firebase/crashlytics.js | 1 + __mocks__/pusher-js/react-native.js | 8 +- __mocks__/react-native-safe-area-context.js | 44 ++ __mocks__/react-native.js | 66 +++ __mocks__/urbanairship-react-native.js | 12 +- jest/setup.js | 140 ++++++- package-lock.json | 2 +- package.json | 1 + src/components/Checkbox.js | 3 +- src/components/DisplayNames/index.native.js | 2 +- src/components/OptionRow.js | 9 +- src/components/OptionsList/BaseOptionsList.js | 1 + src/components/ReportWelcomeText.js | 3 +- src/components/Text.js | 4 + src/components/UnreadActionIndicator.js | 2 +- src/libs/ReportActionsUtils.js | 71 +++- src/libs/ReportUtils.js | 2 + src/libs/actions/Report.js | 69 ++- src/libs/actions/ReportActions.js | 101 ----- src/pages/home/HeaderView.js | 18 +- src/pages/home/ReportHeaderViewBackButton.js | 30 ++ src/pages/home/ReportScreen.js | 6 + .../FloatingMessageCounterContainer/index.js | 2 +- .../report/FloatingMessageCounter/index.js | 2 +- src/pages/home/report/ReportActionCompose.js | 3 +- src/pages/home/report/ReportActionItem.js | 4 +- .../home/report/ReportActionItemCreated.js | 13 +- .../home/report/ReportActionItemMessage.js | 45 +- src/pages/home/report/ReportActionsList.js | 12 +- src/pages/home/report/ReportActionsView.js | 11 +- src/pages/home/sidebar/SidebarLinks.js | 2 +- src/pages/signin/LoginForm.js | 2 +- src/setup/platformSetup/index.native.js | 2 +- src/styles/styles.js | 4 - tests/actions/ReportTest.js | 18 +- tests/ui/UnreadIndicatorsTest.js | 395 ++++++++++++++++++ tests/unit/LHNOrderTest.js | 7 - tests/unit/loginTest.js | 12 - tests/utils/TestHelper.js | 78 +++- 39 files changed, 951 insertions(+), 256 deletions(-) create mode 100644 __mocks__/@react-native-firebase/crashlytics.js create mode 100644 __mocks__/react-native-safe-area-context.js create mode 100644 __mocks__/react-native.js create mode 100644 src/pages/home/ReportHeaderViewBackButton.js create mode 100644 tests/ui/UnreadIndicatorsTest.js diff --git a/__mocks__/@react-native-firebase/crashlytics.js b/__mocks__/@react-native-firebase/crashlytics.js new file mode 100644 index 000000000000..ff8b4c56321a --- /dev/null +++ b/__mocks__/@react-native-firebase/crashlytics.js @@ -0,0 +1 @@ +export default {}; diff --git a/__mocks__/pusher-js/react-native.js b/__mocks__/pusher-js/react-native.js index 0cb6afb4bb1d..1edec34ffb14 100644 --- a/__mocks__/pusher-js/react-native.js +++ b/__mocks__/pusher-js/react-native.js @@ -1,3 +1,9 @@ import {PusherMock} from 'pusher-js-mock'; -export default PusherMock; +class PusherMockWithDisconnect extends PusherMock { + disconnect() { + return jest.fn(); + } +} + +export default PusherMockWithDisconnect; diff --git a/__mocks__/react-native-safe-area-context.js b/__mocks__/react-native-safe-area-context.js new file mode 100644 index 000000000000..82152de8de11 --- /dev/null +++ b/__mocks__/react-native-safe-area-context.js @@ -0,0 +1,44 @@ +import React, {forwardRef} from 'react'; +import {View} from 'react-native'; + +const insets = { + top: 0, right: 0, bottom: 0, left: 0, +}; + +function withSafeAreaInsets(WrappedComponent) { + const WithSafeAreaInsets = props => ( + + ); + return forwardRef((props, ref) => ( + // eslint-disable-next-line react/jsx-props-no-spreading + + )); +} + +const SafeAreaView = View; +const SafeAreaProvider = props => props.children; +const SafeAreaConsumer = props => props.children(insets); +const SafeAreaInsetsContext = { + Consumer: SafeAreaConsumer, +}; + +const useSafeAreaFrame = jest.fn(() => ({ + x: 0, y: 0, width: 390, height: 844, +})); +const useSafeAreaInsets = jest.fn(() => insets); + +export { + SafeAreaProvider, + SafeAreaConsumer, + SafeAreaInsetsContext, + withSafeAreaInsets, + SafeAreaView, + useSafeAreaFrame, + useSafeAreaInsets, +}; diff --git a/__mocks__/react-native.js b/__mocks__/react-native.js new file mode 100644 index 000000000000..3e407252dc78 --- /dev/null +++ b/__mocks__/react-native.js @@ -0,0 +1,66 @@ +/* eslint-disable arrow-body-style */ +// eslint-disable-next-line no-restricted-imports +import * as ReactNative from 'react-native'; +import _ from 'underscore'; + +jest.doMock('react-native', () => { + let url = 'https://new.expensify.com/'; + const getInitialURL = () => { + return Promise.resolve(url); + }; + + let appState = 'active'; + let count = 0; + const changeListeners = {}; + return Object.setPrototypeOf( + { + NativeModules: { + ...ReactNative.NativeModules, + BootSplash: { + getVisibilityStatus: jest.fn(), + hide: jest.fn(), + }, + StartupTimer: {stop: jest.fn()}, + }, + Linking: { + ...ReactNative.Linking, + getInitialURL, + setInitialURL(newUrl) { + url = newUrl; + }, + }, + AppState: { + ...ReactNative.AppState, + get currentState() { + return appState; + }, + emitCurrentTestState(state) { + appState = state; + _.each(changeListeners, listener => listener(appState)); + }, + addEventListener(type, listener) { + if (type === 'change') { + const originalCount = count; + changeListeners[originalCount] = listener; + ++count; + return { + remove: () => { + delete changeListeners[originalCount]; + }, + }; + } + + return ReactNative.AppState.addEventListener(type, listener); + }, + }, + Dimensions: { + ...ReactNative.Dimensions, + addEventListener: jest.fn(), + get: () => ({ + width: 300, height: 700, scale: 1, fontScale: 1, + }), + }, + }, + ReactNative, + ); +}); diff --git a/__mocks__/urbanairship-react-native.js b/__mocks__/urbanairship-react-native.js index c4e8a3939325..efbb5d87f92b 100644 --- a/__mocks__/urbanairship-react-native.js +++ b/__mocks__/urbanairship-react-native.js @@ -3,10 +3,20 @@ const EventType = { PushReceived: 'pushReceived', }; -export default { +const UrbanAirship = { setUserNotificationsEnabled: jest.fn(), + clearNotifications: jest.fn(), + addListener: jest.fn(), + getNamedUser: jest.fn(), + enableUserPushNotifications: () => Promise.resolve(false), + setNamedUser: jest.fn(), + removeAllListeners: jest.fn(), + setBadgeNumber: jest.fn(), }; +export default UrbanAirship; + export { EventType, + UrbanAirship, }; diff --git a/jest/setup.js b/jest/setup.js index c380ebb56669..627d43466b74 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -1,15 +1,143 @@ +import fs from 'fs'; +import path from 'path'; import 'react-native-gesture-handler/jestSetup'; +import _ from 'underscore'; require('react-native-reanimated/lib/reanimated2/jestUtils').setUpTests(); // Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper'); -// Set up manual mocks for methods used in the actions so our test does not fail. -jest.mock('../src/libs/Notification/PushNotification', () => ({ - // There is no need for a jest.fn() since we don't need to make assertions against it. - register: () => {}, - deregister: () => {}, +jest.mock('react-native-blob-util', () => ({})); + +jest.mock('react-native-reanimated', () => { + const Reanimated = require('react-native-reanimated/mock'); + + // The mock for `call` immediately calls the callback which is incorrect + // So we override it with a no-op + Reanimated.default.call = () => {}; + return Reanimated; +}); + +// uses and we need to mock the imported crashlytics module +// due to an error that happens otherwise https://github.com/invertase/react-native-firebase/issues/2475 +jest.mock('@react-native-firebase/crashlytics', () => () => ({ + log: jest.fn(), + recordError: jest.fn(), })); -jest.mock('react-native-blob-util', () => ({})); +jest.mock('../src/libs/BootSplash', () => ({ + hide: jest.fn(), + getVisibilityStatus: jest.fn().mockResolvedValue('hidden'), +})); + +jest.mock('../src/libs/Notification/LocalNotification', () => ({ + showCommentNotification: jest.fn(), +})); + +/** + * @param {String} imagePath + */ +function mockImages(imagePath) { + const imageFilenames = fs.readdirSync(path.resolve(__dirname, `../assets/${imagePath}/`)); + // eslint-disable-next-line rulesdir/prefer-early-return + _.each(imageFilenames, (fileName) => { + if (/\.svg/.test(fileName)) { + jest.mock(`../assets/${imagePath}/${fileName}`, () => () => ''); + } + }); +} + +// Mock all images so that Icons and other assets cannot break tests +mockImages('images'); +mockImages('images/avatars'); +mockImages('images/bankicons'); +mockImages('images/product-illustrations'); +jest.mock('../src/components/Icon/Expensicons', () => ({ + ActiveRoomAvatar: () => '', + AdminRoomAvatar: () => '', + Android: () => '', + AnnounceRoomAvatar: () => '', + Apple: () => '', + ArrowRight: () => '', + BackArrow: () => '', + Bank: () => '', + Bill: () => '', + Bolt: () => '', + Briefcase: () => '', + Bug: () => '', + Building: () => '', + Camera: () => '', + Cash: () => '', + ChatBubble: () => '', + Checkmark: () => '', + CircleHourglass: () => '', + Clipboard: () => '', + Close: () => '', + ClosedSign: () => '', + Collapse: () => '', + Concierge: () => '', + Connect: () => '', + CreditCard: () => '', + DeletedRoomAvatar: () => '', + DomainRoomAvatar: () => '', + DotIndicator: () => '', + DownArrow: () => '', + Download: () => '', + Emoji: () => '', + Exclamation: () => '', + Exit: () => '', + ExpensifyCard: () => '', + Expand: () => '', + Eye: () => '', + EyeDisabled: () => '', + FallbackAvatar: () => '', + FallbackWorkspaceAvatar: () => '', + Gallery: () => '', + Gear: () => '', + Hashtag: () => '', + ImageCropMask: () => '', + Info: () => '', + Invoice: () => '', + Key: () => '', + Keyboard: () => '', + Link: () => '', + LinkCopy: () => '', + Lock: () => '', + Luggage: () => '', + MagnifyingGlass: () => '', + Mail: () => '', + MoneyBag: () => '', + MoneyCircle: () => '', + Monitor: () => '', + NewWindow: () => '', + NewWorkspace: () => '', + Offline: () => '', + OfflineCloud: () => '', + Paperclip: () => '', + PayPal: () => '', + Paycheck: () => '', + Pencil: () => '', + Phone: () => '', + Pin: () => '', + PinCircle: () => '', + Plus: () => '', + Printer: () => '', + Profile: () => '', + QuestionMark: () => '', + Receipt: () => '', + ReceiptSearch: () => '', + Rotate: () => '', + RotateLeft: () => '', + Send: () => '', + Sync: () => '', + ThreeDots: () => '', + Transfer: () => '', + Trashcan: () => '', + UpArrow: () => '', + Upload: () => '', + Users: () => '', + Wallet: () => '', + Workspace: () => '', + Zoom: () => '', +})); diff --git a/package-lock.json b/package-lock.json index b13378e833d2..1662a0358d53 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44475,7 +44475,7 @@ "@oguzhnatly/react-native-image-manipulator": { "version": "git+ssh://git@github.com/Expensify/react-native-image-manipulator.git#c5f654fc9d0ad7cc5b89d50b34ecf8b0e3f4d050", "integrity": "sha512-PvrSoCq5PS1MA5ZWUpB0khfzH6sM8SI6YiVl4i2SItPr7IeRxiWfI4n45VhBCCElc1z5GhAwTZOBaIzXTX7/og==", - "from": "@oguzhnatly/react-native-image-manipulator@https://github.com/Expensify/react-native-image-manipulator#c5f654fc9d0ad7cc5b89d50b34ecf8b0e3f4d050" + "from": "@oguzhnatly/react-native-image-manipulator@github:Expensify/react-native-image-manipulator#c5f654fc9d0ad7cc5b89d50b34ecf8b0e3f4d050" }, "@onfido/active-video-capture": { "version": "0.0.1", diff --git a/package.json b/package.json index f9a67bfa8cee..272255fac56d 100644 --- a/package.json +++ b/package.json @@ -201,6 +201,7 @@ "/node_modules/" ], "testMatch": [ + "**/tests/ui/**/*.[jt]s?(x)", "**/tests/unit/**/*.[jt]s?(x)", "**/tests/actions/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" diff --git a/src/components/Checkbox.js b/src/components/Checkbox.js index ab5dde69f505..cc94b2e842a1 100644 --- a/src/components/Checkbox.js +++ b/src/components/Checkbox.js @@ -8,7 +8,7 @@ import * as Expensicons from './Icon/Expensicons'; const propTypes = { /** Whether checkbox is checked */ - isChecked: PropTypes.bool.isRequired, + isChecked: PropTypes.bool, /** A function that is called when the box/label is pressed */ onPress: PropTypes.func.isRequired, @@ -33,6 +33,7 @@ const propTypes = { }; const defaultProps = { + isChecked: false, hasError: false, disabled: false, style: [], diff --git a/src/components/DisplayNames/index.native.js b/src/components/DisplayNames/index.native.js index 6ccb53888fd6..91ed0406a0d7 100644 --- a/src/components/DisplayNames/index.native.js +++ b/src/components/DisplayNames/index.native.js @@ -4,7 +4,7 @@ import Text from '../Text'; // As we don't have to show tooltips of the Native platform so we simply render the full display names list. const DisplayNames = props => ( - + {props.fullTitle} ); diff --git a/src/components/OptionRow.js b/src/components/OptionRow.js index cadae24e801e..40471941aba4 100644 --- a/src/components/OptionRow.js +++ b/src/components/OptionRow.js @@ -128,7 +128,10 @@ const OptionRow = (props) => { touchableRef = el} onPress={(e) => { - e.preventDefault(); + if (e) { + e.preventDefault(); + } + props.onSelectRow(props.option, touchableRef); }} disabled={props.isDisabled} @@ -145,7 +148,7 @@ const OptionRow = (props) => { props.isDisabled && styles.cursorDisabled, ]} > - + { } { /> {props.option.alternateText ? ( diff --git a/src/components/OptionsList/BaseOptionsList.js b/src/components/OptionsList/BaseOptionsList.js index 17ce25e26551..e5524c49dab5 100644 --- a/src/components/OptionsList/BaseOptionsList.js +++ b/src/components/OptionsList/BaseOptionsList.js @@ -223,6 +223,7 @@ class BaseOptionsList extends Component { ) : null} { diff --git a/src/components/Text.js b/src/components/Text.js index 84a78d3e37c5..47a037ae735f 100644 --- a/src/components/Text.js +++ b/src/components/Text.js @@ -26,6 +26,9 @@ const propTypes = { /** Any additional styles to apply */ // eslint-disable-next-line react/forbid-prop-types style: PropTypes.any, + + /** Optional testID for testing library */ + testID: PropTypes.string, }; const defaultProps = { color: themeColors.text, @@ -34,6 +37,7 @@ const defaultProps = { textAlign: 'left', children: null, style: {}, + testID: undefined, }; const Text = React.forwardRef(({ diff --git a/src/components/UnreadActionIndicator.js b/src/components/UnreadActionIndicator.js index 389413e4f38e..32a48b650fe3 100755 --- a/src/components/UnreadActionIndicator.js +++ b/src/components/UnreadActionIndicator.js @@ -5,7 +5,7 @@ import Text from './Text'; import withLocalize, {withLocalizePropTypes} from './withLocalize'; const UnreadActionIndicator = props => ( - + {props.translate('common.new')} diff --git a/src/libs/ReportActionsUtils.js b/src/libs/ReportActionsUtils.js index 29f22e0f68c0..a86027cb35ef 100644 --- a/src/libs/ReportActionsUtils.js +++ b/src/libs/ReportActionsUtils.js @@ -1,6 +1,25 @@ import lodashGet from 'lodash/get'; import _ from 'underscore'; +import lodashMerge from 'lodash/merge'; +import ExpensiMark from 'expensify-common/lib/ExpensiMark'; +import Onyx from 'react-native-onyx'; +import * as CollectionUtils from './CollectionUtils'; import CONST from '../CONST'; +import ONYXKEYS from '../ONYXKEYS'; +import * as ReportUtils from './ReportUtils'; + +const allReportActions = {}; +Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + callback: (actions, key) => { + if (!key || !actions) { + return; + } + + const reportID = CollectionUtils.extractCollectionItemID(key); + allReportActions[reportID] = actions; + }, +}); /** * @param {Object} reportAction @@ -22,7 +41,9 @@ function getSortedReportActions(reportActions) { return _.chain(reportActions) .sortBy('sequenceNumber') .filter(action => action.actionName === CONST.REPORT.ACTIONS.TYPE.IOU - || (action.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT && !isDeletedAction(action)) + + // All comment actions are shown unless they are deleted and non-pending + || (action.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT && (!isDeletedAction(action) || !_.isEmpty(action.pendingAction))) || action.actionName === CONST.REPORT.ACTIONS.TYPE.RENAMED || action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) .map((item, index) => ({action: item, index})) @@ -76,7 +97,55 @@ function isConsecutiveActionMadeByPreviousActor(reportActions, actionIndex) { return currentAction.action.actorEmail === previousAction.action.actorEmail; } +/** + * Get the message text for the last action that was not deleted + * @param {Number} reportID + * @param {Object} [actionsToMerge] + * @return {String} + */ +function getLastVisibleMessageText(reportID, actionsToMerge = {}) { + const parser = new ExpensiMark(); + const actions = _.toArray(lodashMerge({}, allReportActions[reportID], actionsToMerge)); + const sortedActions = _.sortBy(actions, 'sequenceNumber'); + const lastMessageIndex = _.findLastIndex(sortedActions, action => ( + !isDeletedAction(action) + )); + const htmlText = lodashGet(actions, [lastMessageIndex, 'message', 0, 'html'], ''); + const messageText = parser.htmlToText(htmlText); + return ReportUtils.formatReportLastMessageText(messageText); +} + +/** + * @param {Number} reportID + * @param {Object} [actionsToMerge] + * @param {Number} deletedSequenceNumber + * @param {Number} lastReadSequenceNumber + * @return {String} + */ +function getNewLastReadSequenceNumberForDeletedAction(reportID, actionsToMerge = {}, deletedSequenceNumber, lastReadSequenceNumber) { + // If the action we are deleting is unread then just return the current last read sequence number + if (deletedSequenceNumber > lastReadSequenceNumber) { + return lastReadSequenceNumber; + } + + // Otherwise, we must find the first previous index of an action that is not deleted and less than the lastReadSequenceNumber + const actions = _.toArray(lodashMerge({}, allReportActions[reportID], actionsToMerge)); + const sortedActions = _.sortBy(actions, 'sequenceNumber'); + const lastMessageIndex = _.findLastIndex(sortedActions, action => ( + !isDeletedAction(action) && action.sequenceNumber <= lastReadSequenceNumber + )); + + // It's possible we won't find any and in that case the last read should be reset + if (lastMessageIndex < 0) { + return 0; + } + + return actions[lastMessageIndex].sequenceNumber; +} + export { + getNewLastReadSequenceNumberForDeletedAction, + getLastVisibleMessageText, getSortedReportActions, getMostRecentIOUReportSequenceNumber, isDeletedAction, diff --git a/src/libs/ReportUtils.js b/src/libs/ReportUtils.js index e48939c5e7e9..1cc13e65c7f7 100644 --- a/src/libs/ReportUtils.js +++ b/src/libs/ReportUtils.js @@ -101,6 +101,7 @@ function canEditReportAction(reportAction) { && reportAction.reportActionID && reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT && !isReportMessageAttachment(lodashGet(reportAction, ['message', 0], {})) + && reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD && reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE; } @@ -116,6 +117,7 @@ function canDeleteReportAction(reportAction) { return reportAction.actorEmail === sessionEmail && reportAction.reportActionID && reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT + && reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD && reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE; } diff --git a/src/libs/actions/Report.js b/src/libs/actions/Report.js index 3d9d75cda781..9d977290278d 100644 --- a/src/libs/actions/Report.js +++ b/src/libs/actions/Report.js @@ -11,7 +11,6 @@ import PushNotification from '../Notification/PushNotification'; import * as PersonalDetails from './PersonalDetails'; import Navigation from '../Navigation/Navigation'; import * as ActiveClientManager from '../ActiveClientManager'; -import Visibility from '../Visibility'; import ROUTES from '../../ROUTES'; import Timing from './Timing'; import * as DeprecatedAPI from '../deprecatedAPI'; @@ -21,12 +20,12 @@ import CONST from '../../CONST'; import Log from '../Log'; import * as LoginUtils from '../LoginUtils'; import * as ReportUtils from '../ReportUtils'; -import * as ReportActions from './ReportActions'; import Growl from '../Growl'; import * as Localize from '../Localize'; import DateUtils from '../DateUtils'; import * as ReportActionsUtils from '../ReportActionsUtils'; import * as NumberUtils from '../NumberUtils'; +import Visibility from '../Visibility'; let currentUserEmail; let currentUserAccountID; @@ -802,10 +801,20 @@ function addActions(reportID, text = '', file) { const lastAction = attachmentAction || reportCommentAction; // We need a newSequenceNumber that is n larger than the current depending on how many actions we are adding. - const actionCount = text && file ? 2 : 1; const highestSequenceNumber = getMaxSequenceNumber(reportID); + const actionCount = text && file ? 2 : 1; const newSequenceNumber = highestSequenceNumber + actionCount; + // We guess at what these sequenceNumbers are to enable marking as unread while offline + if (text && file) { + reportCommentAction.sequenceNumber = highestSequenceNumber + 1; + attachmentAction.sequenceNumber = highestSequenceNumber + 2; + } else if (file) { + attachmentAction.sequenceNumber = highestSequenceNumber + 1; + } else { + reportCommentAction.sequenceNumber = highestSequenceNumber + 1; + } + // Update the report in Onyx to have the new sequence number const optimisticReport = { maxSequenceNumber: newSequenceNumber, @@ -815,13 +824,14 @@ function addActions(reportID, text = '', file) { lastReadSequenceNumber: newSequenceNumber, }; - // Optimistically add the new actions to the store before waiting to save them to the server + // Optimistically add the new actions to the store before waiting to save them to the server. We use the clientID + // so that we can later unset these messages via the server by sending {[clientID]: null} const optimisticReportActions = {}; if (text) { - optimisticReportActions[reportCommentAction.sequenceNumber] = reportCommentAction; + optimisticReportActions[reportCommentAction.clientID] = reportCommentAction; } if (file) { - optimisticReportActions[attachmentAction.sequenceNumber] = attachmentAction; + optimisticReportActions[attachmentAction.clientID] = attachmentAction; } const parameters = { @@ -1159,26 +1169,32 @@ Onyx.connect({ */ function deleteReportComment(reportID, reportAction) { const sequenceNumber = reportAction.sequenceNumber; - - // We are not updating the message content here so the message can re-appear as strike-throughed - // if the user goes offline. The API will update the message content to empty strings on success. + const deletedMessage = [{ + type: 'COMMENT', + html: '', + text: '', + isEdited: true, + }]; const optimisticReportActions = { [sequenceNumber]: { pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + previousMessage: reportAction.message, + message: deletedMessage, }, }; - // If we are deleting the last visible message, let's find the previous visible one - // and update the lastMessageText in the chat preview. + // If we are deleting the last visible message, let's find the previous visible one and update the lastMessageText in the LHN. + // Similarly, we are deleting the last read comment will want to update the lastReadSequenceNumber to use the previous visible message. + const lastMessageText = ReportActionsUtils.getLastVisibleMessageText(reportID, optimisticReportActions); + const lastReadSequenceNumber = ReportActionsUtils.getNewLastReadSequenceNumberForDeletedAction( + reportID, + optimisticReportActions, + reportAction.sequenceNumber, + getLastReadSequenceNumber(reportID), + ); const optimisticReport = { - lastMessageText: ReportActions.getLastVisibleMessageText(reportID, { - [sequenceNumber]: { - message: [{ - html: '', - text: '', - }], - }, - }), + lastMessageText, + lastReadSequenceNumber, }; // If the API call fails we must show the original message again, so we revert the message content back to how it was @@ -1191,6 +1207,7 @@ function deleteReportComment(reportID, reportAction) { [sequenceNumber]: { message: reportAction.message, pendingAction: null, + previousMessage: null, }, }, }, @@ -1203,6 +1220,7 @@ function deleteReportComment(reportID, reportAction) { value: { [sequenceNumber]: { pendingAction: null, + previousMessage: null, }, }, }, @@ -1511,11 +1529,14 @@ function viewNewReportAction(reportID, action) { const lastReadSequenceNumber = getLastReadSequenceNumber(reportID); const updatedReportObject = {}; - // When handling an action from the current user we can assume that their last read actionID has been updated in the server, but not necessarily reflected - // locally so we will update the lastReadSequenceNumber to mark the report as read. + // When handling an action from the current user we can assume that their last read actionID has been updated in the server, + // but not necessarily reflected locally so we will update the lastReadSequenceNumber to mark the report as read. if (isFromCurrentUser) { updatedReportObject.lastVisitedTimestamp = Date.now(); updatedReportObject.lastReadSequenceNumber = action.pendingAction ? lastReadSequenceNumber : action.sequenceNumber; + updatedReportObject.maxSequenceNumber = action.sequenceNumber; + } else { + updatedReportObject.maxSequenceNumber = action.sequenceNumber; } Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, updatedReportObject); @@ -1589,7 +1610,9 @@ Onyx.connect({ return; } - if (action.isLoading) { + // We don't want to process any new actions that have a pendingAction field as this means they are "optimistic" and no notifications + // should be created for them + if (!_.isEmpty(action.pendingAction)) { return; } @@ -1599,6 +1622,8 @@ Onyx.connect({ // If we are past the deadline to notify for this comment don't do it if (moment.utc(action.timestamp * 1000).isBefore(moment.utc().subtract(10, 'seconds'))) { + handledReportActions[reportID] = handledReportActions[reportID] || {}; + handledReportActions[reportID][action.sequenceNumber] = true; return; } diff --git a/src/libs/actions/ReportActions.js b/src/libs/actions/ReportActions.js index 504e915ef76b..f1b7c3380acc 100644 --- a/src/libs/actions/ReportActions.js +++ b/src/libs/actions/ReportActions.js @@ -1,103 +1,5 @@ -import _ from 'underscore'; import Onyx from 'react-native-onyx'; -import lodashGet from 'lodash/get'; -import lodashMerge from 'lodash/merge'; -import ExpensiMark from 'expensify-common/lib/ExpensiMark'; import ONYXKEYS from '../../ONYXKEYS'; -import * as CollectionUtils from '../CollectionUtils'; -import CONST from '../../CONST'; -import * as ReportUtils from '../ReportUtils'; -import * as ReportActionsUtils from '../ReportActionsUtils'; - -/** - * Map of the most recent non-loading sequenceNumber for a reportActions_* key in Onyx by reportID. - * - * What's the difference between reportMaxSequenceNumbers and reportActionsMaxSequenceNumbers? - * - * Knowing the maxSequenceNumber for a report does not necessarily mean we have stored the report actions for that - * report. To understand and optimize which reportActions we need to fetch we also keep track of the max sequenceNumber - * for the stored reportActions in reportActionsMaxSequenceNumbers. This allows us to initially download all - * reportActions when the app starts up and then only download the actions that we need when the app reconnects. - * - * This information should only be used in the correct contexts. In most cases, reportMaxSequenceNumbers should be - * referenced and not the locally stored reportAction's max sequenceNumber. - */ -const reportActionsMaxSequenceNumbers = {}; -const reportActions = {}; - -Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, - callback: (actions, key) => { - if (!key || !actions) { - return; - } - - const reportID = CollectionUtils.extractCollectionItemID(key); - const actionsArray = _.toArray(actions); - reportActions[reportID] = actionsArray; - const mostRecentNonLoadingActionIndex = _.findLastIndex(actionsArray, action => !action.isLoading); - const mostRecentAction = actionsArray[mostRecentNonLoadingActionIndex]; - if (!mostRecentAction || _.isUndefined(mostRecentAction.sequenceNumber)) { - return; - } - - reportActionsMaxSequenceNumbers[reportID] = mostRecentAction.sequenceNumber; - }, -}); - -/** - * Get the count of deleted messages after a sequence number of a report - * @param {Number|String} reportID - * @param {Number} sequenceNumber - * @return {Number} - */ -function getDeletedCommentsCount(reportID, sequenceNumber) { - if (!reportActions[reportID]) { - return 0; - } - - return _.reduce(reportActions[reportID], (numDeletedMessages, action) => { - if (action.actionName !== CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT || action.sequenceNumber <= sequenceNumber) { - return numDeletedMessages; - } - - // Empty ADDCOMMENT actions typically mean they have been deleted - const message = _.first(lodashGet(action, 'message', null)); - const html = lodashGet(message, 'html', ''); - return _.isEmpty(html) ? numDeletedMessages + 1 : numDeletedMessages; - }, 0); -} - -/** - * Get the message text for the last action that was not deleted - * @param {Number} reportID - * @param {Object} [actionsToMerge] - * @return {String} - */ -function getLastVisibleMessageText(reportID, actionsToMerge = {}) { - const parser = new ExpensiMark(); - const existingReportActions = _.indexBy(reportActions[reportID], 'sequenceNumber'); - const actions = _.toArray(lodashMerge({}, existingReportActions, actionsToMerge)); - const lastMessageIndex = _.findLastIndex(actions, action => ( - !ReportActionsUtils.isDeletedAction(action) - )); - const htmlText = lodashGet(actions, [lastMessageIndex, 'message', 0, 'html'], ''); - const messageText = parser.htmlToText(htmlText); - return ReportUtils.formatReportLastMessageText(messageText); -} - -/** - * @param {Number} reportID - * @param {Number} sequenceNumber - * @param {Number} currentUserAccountID - * @param {Object} [actionsToMerge] - * @returns {Boolean} - */ -function isFromCurrentUser(reportID, sequenceNumber, currentUserAccountID, actionsToMerge = {}) { - const existingReportActions = _.indexBy(reportActions[reportID], 'sequenceNumber'); - const action = lodashMerge({}, existingReportActions, actionsToMerge)[sequenceNumber]; - return action.actorAccountID === currentUserAccountID; -} /** * @param {Number} reportID @@ -122,9 +24,6 @@ function clearReportActionErrors(reportID, sequenceNumber) { } export { - getDeletedCommentsCount, - getLastVisibleMessageText, clearReportActionErrors, - isFromCurrentUser, deleteOptimisticReportAction, }; diff --git a/src/pages/home/HeaderView.js b/src/pages/home/HeaderView.js index 93cd78ea63c5..ea5db9406a7e 100644 --- a/src/pages/home/HeaderView.js +++ b/src/pages/home/HeaderView.js @@ -26,6 +26,7 @@ import Text from '../../components/Text'; import Tooltip from '../../components/Tooltip'; import variables from '../../styles/variables'; import colors from '../../styles/colors'; +import ReportHeaderViewBackButton from './ReportHeaderViewBackButton'; const propTypes = { /** Toggles the navigationMenu open and closed */ @@ -49,7 +50,7 @@ const propTypes = { policies: PropTypes.shape({ /** Name of the policy */ name: PropTypes.string, - }).isRequired, + }), /** Personal details of all the users */ personalDetails: PropTypes.objectOf(participantPropTypes), @@ -60,6 +61,7 @@ const propTypes = { const defaultProps = { personalDetails: {}, + policies: {}, report: null, }; @@ -89,17 +91,13 @@ const HeaderView = (props) => { const icons = ReportUtils.getIcons(props.report, props.personalDetails, props.policies); const brickRoadIndicator = ReportUtils.hasReportNameError(props.report) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : ''; return ( - + {props.isSmallScreenWidth && ( - - - - - + )} {Boolean(props.report && title) && ( ( + + + + + +); + +ReportHeaderViewBackButton.displayName = 'ReportHeaderViewBackButton'; +ReportHeaderViewBackButton.propTypes = propTypes; +export default ReportHeaderViewBackButton; diff --git a/src/pages/home/ReportScreen.js b/src/pages/home/ReportScreen.js index f852dfb2626f..4e43bb06956c 100644 --- a/src/pages/home/ReportScreen.js +++ b/src/pages/home/ReportScreen.js @@ -26,6 +26,7 @@ import addViewportResizeListener from '../../libs/VisualViewport'; import {withNetwork} from '../../components/OnyxProvider'; import compose from '../../libs/compose'; import networkPropTypes from '../../components/networkPropTypes'; +import withDrawerState, {withDrawerPropTypes} from '../../components/withDrawerState'; const propTypes = { /** Navigation route context info provided by react navigation */ @@ -80,6 +81,8 @@ const propTypes = { /** Information about the network */ network: networkPropTypes.isRequired, + + ...withDrawerPropTypes, }; const defaultProps = { @@ -234,6 +237,7 @@ class ReportScreen extends React.Component { /> this.setState({skeletonViewContainerHeight: event.nativeEvent.layout.height})} @@ -250,6 +254,7 @@ class ReportScreen extends React.Component { report={this.props.report} session={this.props.session} isComposerFullSize={this.props.isComposerFullSize} + isDrawerOpen={this.props.isDrawerOpen} /> )} {(isArchivedRoom || this.props.session.shouldShowComposeInput) && ( @@ -285,6 +290,7 @@ ReportScreen.propTypes = propTypes; ReportScreen.defaultProps = defaultProps; export default compose( + withDrawerState, withNetwork(), withOnyx({ isSidebarLoaded: { diff --git a/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js b/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js index c5a9ed5078eb..a367eea5f602 100644 --- a/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js +++ b/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js @@ -4,7 +4,7 @@ import styles from '../../../../../styles/styles'; import floatingMessageCounterContainerPropTypes from './floatingMessageCounterContainerPropTypes'; const FloatingMessageCounterContainer = props => ( - + {props.children} ); diff --git a/src/pages/home/report/FloatingMessageCounter/index.js b/src/pages/home/report/FloatingMessageCounter/index.js index 7025d5a67a4f..8af8266b0a87 100644 --- a/src/pages/home/report/FloatingMessageCounter/index.js +++ b/src/pages/home/report/FloatingMessageCounter/index.js @@ -62,7 +62,7 @@ class FloatingMessageCounter extends PureComponent { render() { return ( - + {hovered => ( - + {this.props.shouldDisplayNewIndicator && ( - + )} { const isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(props.report); const icons = ReportUtils.getIcons(props.report, props.personalDetails, props.policies); - return ( - ReportUtils.navigateToDetailsPage(props.report)}> diff --git a/src/pages/home/report/ReportActionItemMessage.js b/src/pages/home/report/ReportActionItemMessage.js index a066b2be34f8..d226ac9ced90 100644 --- a/src/pages/home/report/ReportActionItemMessage.js +++ b/src/pages/home/report/ReportActionItemMessage.js @@ -6,18 +6,12 @@ import lodashGet from 'lodash/get'; import styles from '../../../styles/styles'; import ReportActionItemFragment from './ReportActionItemFragment'; import reportActionPropTypes from './reportActionPropTypes'; -import {withNetwork} from '../../../components/OnyxProvider'; import withLocalize, {withLocalizePropTypes} from '../../../components/withLocalize'; -import compose from '../../../libs/compose'; -import networkPropTypes from '../../../components/networkPropTypes'; const propTypes = { /** The report action */ action: PropTypes.shape(reportActionPropTypes).isRequired, - /** Information about the network */ - network: networkPropTypes.isRequired, - /** Additional styles to add after local styles. */ style: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.object), @@ -32,31 +26,24 @@ const defaultProps = { style: [], }; -const ReportActionItemMessage = (props) => { - const isUnsent = props.network.isOffline && props.action.isLoading; - - return ( - - {_.map(_.compact(props.action.message), (fragment, index) => ( - - ))} - - ); -}; +const ReportActionItemMessage = props => ( + + {_.map(_.compact(props.action.previousMessage || props.action.message), (fragment, index) => ( + + ))} + +); ReportActionItemMessage.propTypes = propTypes; ReportActionItemMessage.defaultProps = defaultProps; ReportActionItemMessage.displayName = 'ReportActionItemMessage'; -export default compose( - withNetwork(), - withLocalize, -)(ReportActionItemMessage); +export default withLocalize(ReportActionItemMessage); diff --git a/src/pages/home/report/ReportActionsList.js b/src/pages/home/report/ReportActionsList.js index bdfe34ce2d1c..77e54bd39162 100644 --- a/src/pages/home/report/ReportActionsList.js +++ b/src/pages/home/report/ReportActionsList.js @@ -106,14 +106,14 @@ class ReportActionsList extends React.Component { } /** - * Create a unique key for Each Action in the FlatList. - * We use the reportActionId that is a string representation of a random 64-bit int, which should be - * random enought to avoid colisions + * Create a unique key for each action in the FlatList. + * We use the reportActionID that is a string representation of a random 64-bit int, which should be + * random enough to avoid collisions * @param {Object} item * @return {String} */ keyExtractor(item) { - return `${item.action.reportActionID}${item.action.sequenceNumber}`; + return `${item.action.clientID}${item.action.reportActionID}${item.action.sequenceNumber}`; } /** @@ -135,7 +135,8 @@ class ReportActionsList extends React.Component { // When the new indicator should not be displayed we explicitly set it to 0. The marker should never be shown above the // created action (which will have sequenceNumber of 0) so we use 0 to indicate "hidden". const shouldDisplayNewIndicator = this.props.newMarkerSequenceNumber > 0 - && item.action.sequenceNumber === this.props.newMarkerSequenceNumber; + && item.action.sequenceNumber === this.props.newMarkerSequenceNumber + && !ReportActionsUtils.isDeletedAction(item.action); return ( { + this.appStateChangeListener = AppState.addEventListener('change', () => { if (!this.getIsReportFullyVisible()) { return; } // If the app user becomes active and they have no unread actions we clear the new marker to sync their device // e.g. they could have read these messages on another device and only just become active here - if (state === 'active' && !ReportUtils.isUnread(this.props.report)) { - this.setState({newMarkerSequenceNumber: 0}); - } - Report.openReport(this.props.report.reportID); + this.setState({newMarkerSequenceNumber: 0}); }); Report.subscribeToReportTypingEvents(this.props.report.reportID); @@ -383,7 +381,6 @@ ReportActionsView.defaultProps = defaultProps; export default compose( Performance.withRenderTrace({id: ' rendering'}), withWindowDimensions, - withDrawerState, withLocalize, withNetwork(), )(ReportActionsView); diff --git a/src/pages/home/sidebar/SidebarLinks.js b/src/pages/home/sidebar/SidebarLinks.js index 7028b796a0ea..417c4030a11b 100644 --- a/src/pages/home/sidebar/SidebarLinks.js +++ b/src/pages/home/sidebar/SidebarLinks.js @@ -253,7 +253,7 @@ class SidebarLinks extends React.Component { }]; return ( - + - + this.input = el} label={this.props.translate('loginForm.phoneOrEmail')} diff --git a/src/setup/platformSetup/index.native.js b/src/setup/platformSetup/index.native.js index cd55b6a280a4..02a0629db1d4 100644 --- a/src/setup/platformSetup/index.native.js +++ b/src/setup/platformSetup/index.native.js @@ -23,7 +23,7 @@ export default function () { Report.subscribeToReportCommentPushNotifications(); // Setup Flipper plugins when on dev - if (__DEV__) { + if (__DEV__ && typeof jest === 'undefined') { require('flipper-plugin-bridgespy-client'); } diff --git a/src/styles/styles.js b/src/styles/styles.js index 467a5609a4bf..8ee0006b18fe 100644 --- a/src/styles/styles.js +++ b/src/styles/styles.js @@ -1330,10 +1330,6 @@ const styles = { ...wordBreak.breakWord, }, - chatItemUnsentMessage: { - opacity: 0.6, - }, - chatItemMessageLink: { color: colors.blue, fontSize: variables.fontSizeNormal, diff --git a/tests/actions/ReportTest.js b/tests/actions/ReportTest.js index c8d95f9dcabb..cbf04d3adb58 100644 --- a/tests/actions/ReportTest.js +++ b/tests/actions/ReportTest.js @@ -74,7 +74,7 @@ describe('actions/Report', () => { callback: val => reportActions = val, }); - let sequenceNumber; + let clientID; // Set up Onyx with some test user data return TestHelper.signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN) @@ -92,8 +92,8 @@ describe('actions/Report', () => { .then(() => { const resultAction = _.first(_.values(reportActions)); - // Store the generated sequenceNumber so that we can send it with our mock Pusher update - sequenceNumber = resultAction.sequenceNumber; + // Store the generated clientID so that we can send it with our mock Pusher update + clientID = resultAction.clientID; expect(resultAction.message).toEqual(REPORT_ACTION.message); expect(resultAction.person).toEqual(REPORT_ACTION.person); expect(resultAction.pendingAction).toEqual(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); @@ -120,7 +120,7 @@ describe('actions/Report', () => { onyxMethod: CONST.ONYX.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, value: { - [sequenceNumber]: null, + [clientID]: null, [ACTION_ID]: actionWithoutLoading, }, }, @@ -348,9 +348,9 @@ describe('actions/Report', () => { onyxMethod: CONST.ONYX.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, value: { - [_.toArray(reportActions)[1].sequenceNumber]: null, - [_.toArray(reportActions)[2].sequenceNumber]: null, - [_.toArray(reportActions)[3].sequenceNumber]: null, + [_.toArray(reportActions)[1].clientID]: null, + [_.toArray(reportActions)[2].clientID]: null, + [_.toArray(reportActions)[3].clientID]: null, 2: { ...USER_1_BASE_ACTION, message: [{type: 'COMMENT', html: 'Current User Comment 1', text: 'Current User Comment 1'}], @@ -374,7 +374,7 @@ describe('actions/Report', () => { }) .then(() => { // If the user deletes a comment that is before the last read - Report.deleteReportComment(REPORT_ID, reportActions[2]); + Report.deleteReportComment(REPORT_ID, {...reportActions[2], sequenceNumber: 2, clientID: null}); return waitForPromisesToResolve(); }) .then(() => { @@ -392,7 +392,7 @@ describe('actions/Report', () => { expect(report.lastReadSequenceNumber).toBe(2); // If the user deletes the last comment after the last read the lastMessageText will reflect the new last comment - Report.deleteReportComment(REPORT_ID, reportActions[4]); + Report.deleteReportComment(REPORT_ID, {...reportActions[4], sequenceNumber: 4, clientID: null}); return waitForPromisesToResolve(); }) .then(() => { diff --git a/tests/ui/UnreadIndicatorsTest.js b/tests/ui/UnreadIndicatorsTest.js new file mode 100644 index 000000000000..d26b6bae09d5 --- /dev/null +++ b/tests/ui/UnreadIndicatorsTest.js @@ -0,0 +1,395 @@ +/* eslint-disable @lwc/lwc/no-async-await */ +import React from 'react'; +import Onyx from 'react-native-onyx'; +import {Linking, AppState} from 'react-native'; +import {fireEvent, render, act} from '@testing-library/react-native'; +import lodashGet from 'lodash/get'; +import moment from 'moment'; +import App from '../../src/App'; +import CONST from '../../src/CONST'; +import ONYXKEYS from '../../src/ONYXKEYS'; +import waitForPromisesToResolve from '../utils/waitForPromisesToResolve'; +import * as TestHelper from '../utils/TestHelper'; +import appSetup from '../../src/setup'; +import fontWeightBold from '../../src/styles/fontWeight/bold'; +import * as AppActions from '../../src/libs/actions/App'; +import ReportHeaderViewBackButton from '../../src/pages/home/ReportHeaderViewBackButton'; +import ReportActionsView from '../../src/pages/home/report/ReportActionsView'; +import * as NumberUtils from '../../src/libs/NumberUtils'; +import LocalNotification from '../../src/libs/Notification/LocalNotification'; +import * as Report from '../../src/libs/actions/Report'; + +beforeAll(() => { + global.fetch = TestHelper.getGlobalFetchMock(); + + // We need a bit more time for this test in some places + jest.setTimeout(30000); + Linking.setInitialURL('https://new.expensify.com/r/1'); + appSetup(); +}); + +/** + * @param {RenderAPI} renderedApp + */ +function scrollUpToRevealNewMessagesBadge(renderedApp) { + fireEvent.scroll(renderedApp.getByTestId('report-actions-list'), { + nativeEvent: { + contentOffset: { + y: 250, + }, + contentSize: { + // Dimensions of the scrollable content + height: 500, + width: 100, + }, + layoutMeasurement: { + // Dimensions of the device + height: 700, + width: 300, + }, + }, + }); + + // We advance the timer since we must wait for the animation to end + // and the new style to be reflected + jest.advanceTimersByTime(100); +} + +/** + * @param {RenderAPI} renderedApp + * @return {Boolean} + */ +function isNewMessagesBadgeVisible(renderedApp) { + const badge = renderedApp.getByTestId('new-messages-badge'); + return badge.props.style.transform[0].translateY === 10; +} + +/** + * @param {RenderAPI} renderedApp + * @return {Promise} + */ +async function navigateToSidebar(renderedApp) { + const reportHeader = renderedApp.getByTestId('report-header'); + const reportHeaderBackButton = reportHeader.findByType(ReportHeaderViewBackButton); + fireEvent(reportHeaderBackButton, 'press'); + return waitForPromisesToResolve(); +} + +/** + * @param {RenderAPI} renderedApp + * @param {Number} index + * @return {Promise} + */ +async function navigateToSidebarOption(renderedApp, index) { + const optionRows = renderedApp.getAllByTestId('option-row'); + fireEvent(optionRows[index], 'press'); + await waitForPromisesToResolve(); +} + +/** + * @param {RenderAPI} renderedApp + * @return {Boolean} + */ +function isDrawerOpen(renderedApp) { + const reportScreen = renderedApp.getByTestId('report-screen'); + return reportScreen.findByType(ReportActionsView).props.isDrawerOpen; +} + +test('Unread LHN Status, “New Messages” badge, and New Line Indicator', async () => { + const REPORT_ID = 1; + const USER_A_ACCOUNT_ID = 1; + const USER_A_EMAIL = 'user_a@test.com'; + const USER_B_ACCOUNT_ID = 2; + const USER_B_EMAIL = 'user_b@test.com'; + const USER_C_ACCOUNT_ID = 3; + const USER_C_EMAIL = 'user_c@test.com'; + + // Render the App and sign in as a test user. + const renderedApp = render(); + + // Note: act() is necessary since react-navigation's NavigationContainer has an internal state update that will throw some + // warnings related to async code. See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act + await act(async () => { + await waitForPromisesToResolve(); + await waitForPromisesToResolve(); + }); + + const loginForm = renderedApp.getByTestId('login-form'); + expect(loginForm).toBeTruthy(); + + TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); + await waitForPromisesToResolve(); + + const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); + + // Simulate setting an unread report and personal details + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + reportID: REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 9, + lastReadSequenceNumber: 1, + lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), // Ten minutes ago + lastMessageText: 'Test', + participants: [USER_B_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: MOMENT_TEN_MINUTES_AGO.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), + 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), + 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), + 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), + 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), + 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), + 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), + 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), + 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), + }); + await waitForPromisesToResolve(); + + // Verify no notifications are created for these older messages + expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); + + // Verify the sidebar links are rendered + const sidebarLinks = renderedApp.getByTestId('sidebar-links'); + expect(sidebarLinks).toBeTruthy(); + + // And verify that the Report screen is rendered after manually setting the sidebar as loaded + // since the onLayout event does not fire in tests + AppActions.setSidebarLoaded(true); + await waitForPromisesToResolve(); + + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Verify there is only one option in the sidebar + let optionRows = renderedApp.getAllByTestId('option-row'); + expect(optionRows.length).toBe(1); + + // And that the text is bold + const displayNameText = renderedApp.getByTestId('option-row-display-name'); + expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + await navigateToSidebarOption(renderedApp, 0); + + // Verify that the report screen is rendered and the drawer is closed + expect(isDrawerOpen(renderedApp)).toBe(false); + + // That the report actions are visible along with the created action + const createdAction = renderedApp.getByTestId('report-action-created'); + expect(createdAction).toBeTruthy(); + const reportComments = renderedApp.getAllByTestId('report-action-item'); + expect(reportComments.length).toBe(9); + + // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will + // have a sequenceNumber of 2 + let unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + let sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + expect(sequenceNumber).toBe(2); + + // Scroll up and verify that the "New messages" badge appears + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + + // And that the option row in the LHN is no longer bold (since OpenReport marked it as read) + const updatedDisplayNameText = renderedApp.getByTestId('option-row-display-name'); + expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + + // Tap on the back button to return to the sidebar + await navigateToSidebar(renderedApp); + + // Verify the LHN is now open + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Navigate to the report again + await navigateToSidebarOption(renderedApp, 0); + + // Verify the unread indicator is no longer present + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + expect(isDrawerOpen(renderedApp)).toBe(false); + + // Scroll and verify that the new messages badge is hidden + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + + // Simulate a new report arriving via Pusher along with reportActions and personalDetails for the other participant + const NEW_REPORT_ID = 2; + const NEW_REPORT_CREATED_MOMENT = moment(); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${NEW_REPORT_ID}`, { + reportID: NEW_REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 1, + lastReadSequenceNumber: 0, + lastMessageTimestamp: NEW_REPORT_CREATED_MOMENT.utc(), + lastMessageText: 'Comment 1', + participants: [USER_C_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${NEW_REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: NEW_REPORT_CREATED_MOMENT.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: { + actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT, + actorEmail: USER_C_EMAIL, + person: [{type: 'TEXT', style: 'strong', text: 'User C'}], + sequenceNumber: 1, + timestamp: NEW_REPORT_CREATED_MOMENT.add(5, 'seconds').unix(), + message: [{type: 'COMMENT', html: 'Comment 1', text: 'Comment 1'}], + reportActionID: NumberUtils.rand64(), + }, + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_C_EMAIL]: TestHelper.buildPersonalDetails(USER_C_EMAIL, USER_C_ACCOUNT_ID, 'C'), + }); + await waitForPromisesToResolve(); + + // Verify notification was created as the new message that has arrived is very recent + expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); + + // Navigate back to the sidebar + await navigateToSidebar(renderedApp); + + // Verify the new report option appears in the LHN + optionRows = renderedApp.getAllByTestId('option-row'); + expect(optionRows.length).toBe(2); + + // Verify the text for the new chat is bold and above the previous indicating it has not yet been read + let displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + const firstReportOption = displayNameTexts[0]; + expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); + + const secondReportOption = displayNameTexts[1]; + expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(secondReportOption, ['props', 'children'])).toBe('B User'); + + // Tap the new report option and navigate back to the sidebar again via the back button + await navigateToSidebarOption(renderedApp, 0); + + // Verify that all report options appear in a "read" state + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + + // Tap the previous report between User A and User B + await navigateToSidebarOption(renderedApp, 1); + + // It's difficult to trigger marking a report comment as unread since we would have to mock the long press event and then + // another press on the context menu item so we will do it via the action directly and then test if the UI has updated properly + Report.markCommentAsUnread(REPORT_ID, 3); + await waitForPromisesToResolve(); + + // Verify the indicator appears above the last action + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + expect(sequenceNumber).toBe(3); + + // Scroll up and verify the new messages badge appears + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + + // Navigate to the sidebar + await navigateToSidebar(renderedApp); + + // Verify the report is marked as unread in the sidebar + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + + // Navigate to the report again and back to the sidebar + await navigateToSidebarOption(renderedApp, 1); + await navigateToSidebar(renderedApp); + + // Verify the report is now marked as read + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + + // Navigate to the report again and verify the new line indicator is missing + await navigateToSidebarOption(renderedApp, 1); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + + // Scroll up and verify the badge is hidden + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + expect(isDrawerOpen(renderedApp)).toBe(false); + + // Navigate to the LHN + await navigateToSidebar(renderedApp); + + // Simulate another new message on the report with User B + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + 10: TestHelper.buildTestReportComment(USER_B_EMAIL, 10, moment().unix()), + }); + await waitForPromisesToResolve(); + + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + // Navigate to the report again and verify the indicator exists + await navigateToSidebarOption(renderedApp, 1); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + + // Leave a comment as the current user and verify the indicator is removed + Report.addComment(REPORT_ID, 'Current User Comment 1'); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + + // Mark a previous comment as unread and verify the unread action indicator returns + Report.markCommentAsUnread(REPORT_ID, 9); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + + // Trigger the app going inactive and active again + AppState.emitCurrentTestState('background'); + AppState.emitCurrentTestState('active'); + + // Verify the new line is cleared + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + + // As the current user add several comments + Report.addComment(REPORT_ID, 'Current User Comment 2'); + await waitForPromisesToResolve(); + + Report.addComment(REPORT_ID, 'Current User Comment 3'); + await waitForPromisesToResolve(); + + Report.addComment(REPORT_ID, 'Current User Comment 4'); + await waitForPromisesToResolve(); + + // Mark the last comment as "unread" and verify the unread indicator appears + Report.markCommentAsUnread(REPORT_ID, 14); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); +}); diff --git a/tests/unit/LHNOrderTest.js b/tests/unit/LHNOrderTest.js index 3e411f7ca251..d705761a8c20 100644 --- a/tests/unit/LHNOrderTest.js +++ b/tests/unit/LHNOrderTest.js @@ -174,13 +174,6 @@ function getDefaultRenderedSidebarLinks() { )); } -// Icons need to be explicitly mocked. The testing library throws an error when trying to render them -jest.mock('../../src/components/Icon/Expensicons', () => ({ - MagnifyingGlass: () => '', - Pencil: () => '', - Pin: () => '', -})); - describe('Sidebar', () => { describe('in default mode', () => { // Clear out Onyx after each test so that each test starts with a clean slate diff --git a/tests/unit/loginTest.js b/tests/unit/loginTest.js index 830378294c30..c8bcc6c6f00f 100644 --- a/tests/unit/loginTest.js +++ b/tests/unit/loginTest.js @@ -9,18 +9,6 @@ import React from 'react'; import renderer from 'react-test-renderer'; import App from '../../src/App'; -/* uses and we need to mock the imported crashlytics module -* due to an error that happens otherwise https://github.com/invertase/react-native-firebase/issues/2475 */ -jest.mock('@react-native-firebase/crashlytics', () => () => ({ - log: jest.fn(), - recordError: jest.fn(), -})); - -jest.mock('../../src/libs/BootSplash', () => ({ - hide: jest.fn(), - getVisibilityStatus: jest.fn().mockResolvedValue('hidden'), -})); - describe('AppComponent', () => { it('renders correctly', () => { renderer.create(); diff --git a/tests/utils/TestHelper.js b/tests/utils/TestHelper.js index 92af57ba2c2c..319732eca13e 100644 --- a/tests/utils/TestHelper.js +++ b/tests/utils/TestHelper.js @@ -5,18 +5,43 @@ import HttpUtils from '../../src/libs/HttpUtils'; import ONYXKEYS from '../../src/ONYXKEYS'; import waitForPromisesToResolve from './waitForPromisesToResolve'; import * as ReportUtils from '../../src/libs/ReportUtils'; +import * as NumberUtils from '../../src/libs/NumberUtils'; + +/** + * @param {String} login + * @param {Number} accountID + * @param {String} [firstName] + * @returns {Promise} + */ +function buildPersonalDetails(login, accountID, firstName = 'Test') { + const avatar = ReportUtils.getDefaultAvatar(login); + return { + accountID, + login, + avatar, + avatarThumbnail: avatar, + displayName: `${firstName} User`, + firstName, + lastName: 'User', + pronouns: '', + timezone: CONST.DEFAULT_TIME_ZONE, + payPalMeAddress: '', + phoneNumber: '', + }; +} /** * Simulate signing in and make sure all API calls in this flow succeed. Every time we add * a mockImplementationOnce() we are altering what Network.post() will return. * - * @param {Number} accountID - * @param {String} login - * @param {String} password - * @param {String} authToken + * @param {Number} [accountID] + * @param {String} [login] + * @param {String} [password] + * @param {String} [authToken] + * @param {String} [firstName] * @return {Promise} */ -function signInWithTestUser(accountID = 1, login = 'test@user.com', password = 'Password1', authToken = 'asdfqwerty') { +function signInWithTestUser(accountID = 1, login = 'test@user.com', password = 'Password1', authToken = 'asdfqwerty', firstName = 'Test') { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn(); HttpUtils.xhr.mockImplementation(() => Promise.resolve({ @@ -35,6 +60,13 @@ function signInWithTestUser(accountID = 1, login = 'test@user.com', password = ' validated: true, }, }, + { + onyxMethod: CONST.ONYX.METHOD.MERGE, + key: ONYXKEYS.PERSONAL_DETAILS, + value: { + [login]: buildPersonalDetails(login, accountID, firstName), + }, + }, ], jsonCode: 200, })); @@ -86,28 +118,34 @@ function getGlobalFetchMock() { * @returns {Promise} */ function setPersonalDetails(login, accountID) { - const avatar = ReportUtils.getDefaultAvatar(login); - const details = { - accountID, - login, - avatar, - avatarThumbnail: avatar, - displayName: 'Test User', - firstName: 'Test', - lastName: 'User', - pronouns: '', - timezone: CONST.DEFAULT_TIME_ZONE, - payPalMeAddress: '', - phoneNumber: '', - }; Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { - [login]: details, + [login]: buildPersonalDetails(login, accountID), }); return waitForPromisesToResolve(); } +/** + * @param {String} actorEmail + * @param {Number} sequenceNumber + * @param {Number} timestamp + * @returns {Object} + */ +function buildTestReportComment(actorEmail, sequenceNumber, timestamp) { + return { + actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT, + actorEmail, + person: [{type: 'TEXT', style: 'strong', text: 'User B'}], + sequenceNumber, + timestamp, + message: [{type: 'COMMENT', html: 'Comment 1', text: `Comment ${sequenceNumber}`}], + reportActionID: NumberUtils.rand64(), + }; +} + export { getGlobalFetchMock, signInWithTestUser, setPersonalDetails, + buildPersonalDetails, + buildTestReportComment, }; From f1dc53487835f580eb7e6c1c69a3082c5848e9ce Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Tue, 13 Sep 2022 12:08:41 -0400 Subject: [PATCH 02/17] remove unused import --- src/pages/home/report/ReportActionsView.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pages/home/report/ReportActionsView.js b/src/pages/home/report/ReportActionsView.js index 96808af88280..b60ac8acb975 100755 --- a/src/pages/home/report/ReportActionsView.js +++ b/src/pages/home/report/ReportActionsView.js @@ -30,7 +30,6 @@ import CopySelectionHelper from '../../../components/CopySelectionHelper'; import EmojiPicker from '../../../components/EmojiPicker/EmojiPicker'; import * as ReportActionsUtils from '../../../libs/ReportActionsUtils'; import * as ReportUtils from '../../../libs/ReportUtils'; -import Log from '../../../libs/Log'; const propTypes = { /* Onyx Props */ From 3e90f5e54daca1ca60dd57bcca35624907e2ecc4 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Wed, 14 Sep 2022 11:31:18 -0400 Subject: [PATCH 03/17] Make requested changes --- contributingGuides/STYLE.md | 2 +- jest/setup.js | 10 +- src/libs/ReportActionsUtils.js | 8 +- tests/ui/UnreadIndicatorsTest.js | 591 ++++++++++++++++--------------- tests/utils/TestHelper.js | 2 +- 5 files changed, 315 insertions(+), 298 deletions(-) diff --git a/contributingGuides/STYLE.md b/contributingGuides/STYLE.md index 62e64bede72c..6402d27e2e85 100644 --- a/contributingGuides/STYLE.md +++ b/contributingGuides/STYLE.md @@ -388,7 +388,7 @@ So, if a new language feature isn't something we have agreed to support it's off Here are a couple of things we would ask that you *avoid* to help maintain consistency in our codebase: -- **Async/Await** - Use the native `Promise` instead +- **Async/Await** - Use the native `Promise` instead. Async/Await is permitted in test files only. - **Optional Chaining** - Use `lodashGet()` to fetch a nested value instead - **Null Coalescing Operator** - Use `lodashGet()` or `||` to set a default value for a possibly `undefined` or `null` variable diff --git a/jest/setup.js b/jest/setup.js index 627d43466b74..d6911480710d 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -26,11 +26,16 @@ jest.mock('@react-native-firebase/crashlytics', () => () => ({ recordError: jest.fn(), })); +// The main app uses a NativeModule called BootSplash to show/hide a splash screen. Since we can't use this in the node environment +// where tests run we simulate a behavior where the splash screen is always hidden (similar to web which has no splash screen at all). jest.mock('../src/libs/BootSplash', () => ({ hide: jest.fn(), getVisibilityStatus: jest.fn().mockResolvedValue('hidden'), })); +// Local notifications (a.k.a. browser notifications) do not run in native code. Our jest tests will also run against +// any index.native.js files as they are using a react-native plugin. However, it is useful to mock this behavior so that we +// can test the expected web behavior and see if a browser notification would be shown or not. jest.mock('../src/libs/Notification/LocalNotification', () => ({ showCommentNotification: jest.fn(), })); @@ -48,7 +53,10 @@ function mockImages(imagePath) { }); } -// Mock all images so that Icons and other assets cannot break tests +// We are mock all images so that Icons and other assets cannot break tests. In the testing environment, importing things like .svg +// directly will lead to undefined variables instead of a component or string (which is what React expects). Loading these assets is +// not required as the test environment does not actually render any UI anywhere and just needs them to noop so the test renderer +// (which is a virtual implemented DOM) can do it's thing. mockImages('images'); mockImages('images/avatars'); mockImages('images/bankicons'); diff --git a/src/libs/ReportActionsUtils.js b/src/libs/ReportActionsUtils.js index a86027cb35ef..157891dd8aaa 100644 --- a/src/libs/ReportActionsUtils.js +++ b/src/libs/ReportActionsUtils.js @@ -110,7 +110,11 @@ function getLastVisibleMessageText(reportID, actionsToMerge = {}) { const lastMessageIndex = _.findLastIndex(sortedActions, action => ( !isDeletedAction(action) )); - const htmlText = lodashGet(actions, [lastMessageIndex, 'message', 0, 'html'], ''); + if (lastMessageIndex < 0) { + return ''; + } + + const htmlText = lodashGet(sortedActions, [lastMessageIndex, 'message', 0, 'html'], ''); const messageText = parser.htmlToText(htmlText); return ReportUtils.formatReportLastMessageText(messageText); } @@ -140,7 +144,7 @@ function getNewLastReadSequenceNumberForDeletedAction(reportID, actionsToMerge = return 0; } - return actions[lastMessageIndex].sequenceNumber; + return sortedActions[lastMessageIndex].sequenceNumber; } export { diff --git a/tests/ui/UnreadIndicatorsTest.js b/tests/ui/UnreadIndicatorsTest.js index d26b6bae09d5..cc0defa51e62 100644 --- a/tests/ui/UnreadIndicatorsTest.js +++ b/tests/ui/UnreadIndicatorsTest.js @@ -20,6 +20,11 @@ import LocalNotification from '../../src/libs/Notification/LocalNotification'; import * as Report from '../../src/libs/actions/Report'; beforeAll(() => { + // In this test, we are generically mocking the responses of all API requests by mocking fetch() and having it + // return 200. In other tests, we might mock HttpUtils.xhr() with a more specific mock data response (which means + // fetch() never gets called so it does not need mocking) or we might have fetch throw an error to test error handling + // behavior. But here we just want to treat all API requests as a generic "success" and in the cases where we need to + // simulate data arriving we will just set it into Onyx directly with Onyx.merge() or Onyx.set() etc. global.fetch = TestHelper.getGlobalFetchMock(); // We need a bit more time for this test in some places @@ -70,7 +75,7 @@ function isNewMessagesBadgeVisible(renderedApp) { */ async function navigateToSidebar(renderedApp) { const reportHeader = renderedApp.getByTestId('report-header'); - const reportHeaderBackButton = reportHeader.findByType(ReportHeaderViewBackButton); + const reportHeaderBackButton = await reportHeader.findByType(ReportHeaderViewBackButton); fireEvent(reportHeaderBackButton, 'press'); return waitForPromisesToResolve(); } @@ -80,10 +85,10 @@ async function navigateToSidebar(renderedApp) { * @param {Number} index * @return {Promise} */ -async function navigateToSidebarOption(renderedApp, index) { +function navigateToSidebarOption(renderedApp, index) { const optionRows = renderedApp.getAllByTestId('option-row'); fireEvent(optionRows[index], 'press'); - await waitForPromisesToResolve(); + return waitForPromisesToResolve(); } /** @@ -95,301 +100,301 @@ function isDrawerOpen(renderedApp) { return reportScreen.findByType(ReportActionsView).props.isDrawerOpen; } -test('Unread LHN Status, “New Messages” badge, and New Line Indicator', async () => { - const REPORT_ID = 1; - const USER_A_ACCOUNT_ID = 1; - const USER_A_EMAIL = 'user_a@test.com'; - const USER_B_ACCOUNT_ID = 2; - const USER_B_EMAIL = 'user_b@test.com'; - const USER_C_ACCOUNT_ID = 3; - const USER_C_EMAIL = 'user_c@test.com'; - - // Render the App and sign in as a test user. - const renderedApp = render(); - - // Note: act() is necessary since react-navigation's NavigationContainer has an internal state update that will throw some - // warnings related to async code. See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act - await act(async () => { +describe('Unread Indicators', () => { + it('Shows correct LHN Status, “New Messages” badge, and New Line Indicators', async () => { + const REPORT_ID = 1; + const USER_A_ACCOUNT_ID = 1; + const USER_A_EMAIL = 'user_a@test.com'; + const USER_B_ACCOUNT_ID = 2; + const USER_B_EMAIL = 'user_b@test.com'; + const USER_C_ACCOUNT_ID = 3; + const USER_C_EMAIL = 'user_c@test.com'; + + // Render the App and sign in as a test user. + const renderedApp = render(); + + // Note: act() is necessary since react-navigation's NavigationContainer has an internal state update that will throw some + // warnings related to async code. See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act + await act(async () => { + await waitForPromisesToResolve(); + }); + + const loginForm = renderedApp.queryAllByTestId('login-form'); + expect(loginForm.length).toBe(1); + + await TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); + + const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); + + // Simulate setting an unread report and personal details + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + reportID: REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 9, + lastReadSequenceNumber: 1, + lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), + lastMessageText: 'Test', + participants: [USER_B_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: MOMENT_TEN_MINUTES_AGO.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), + 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), + 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), + 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), + 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), + 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), + 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), + 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), + 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), + }); await waitForPromisesToResolve(); + + // Verify no notifications are created for these older messages + expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); + + // Verify the sidebar links are rendered + const sidebarLinks = renderedApp.queryAllByTestId('sidebar-links'); + expect(sidebarLinks.length).toBe(1); + + // And verify that the Report screen is rendered after manually setting the sidebar as loaded + // since the onLayout event does not fire in tests + AppActions.setSidebarLoaded(true); await waitForPromisesToResolve(); - }); - const loginForm = renderedApp.getByTestId('login-form'); - expect(loginForm).toBeTruthy(); + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Verify there is only one option in the sidebar + let optionRows = renderedApp.getAllByTestId('option-row'); + expect(optionRows.length).toBe(1); + + // And that the text is bold + const displayNameText = renderedApp.getByTestId('option-row-display-name'); + expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + await navigateToSidebarOption(renderedApp, 0); + + // Verify that the report screen is rendered and the drawer is closed + expect(isDrawerOpen(renderedApp)).toBe(false); + + // That the report actions are visible along with the created action + const createdAction = renderedApp.getByTestId('report-action-created'); + expect(createdAction).toBeTruthy(); + const reportComments = renderedApp.getAllByTestId('report-action-item'); + expect(reportComments.length).toBe(9); + + // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will + // have a sequenceNumber of 2 + let unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + let sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + expect(sequenceNumber).toBe(2); + + // Scroll up and verify that the "New messages" badge appears + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + + // And that the option row in the LHN is no longer bold (since OpenReport marked it as read) + const updatedDisplayNameText = renderedApp.getByTestId('option-row-display-name'); + expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + + // Tap on the back button to return to the sidebar + await navigateToSidebar(renderedApp); + + // Verify the LHN is now open + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Navigate to the report again + await navigateToSidebarOption(renderedApp, 0); + + // Verify the unread indicator is no longer present + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + expect(isDrawerOpen(renderedApp)).toBe(false); + + // Scroll and verify that the new messages badge is hidden + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + + // Simulate a new report arriving via Pusher along with reportActions and personalDetails for the other participant + const NEW_REPORT_ID = 2; + const NEW_REPORT_CREATED_MOMENT = moment(); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${NEW_REPORT_ID}`, { + reportID: NEW_REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 1, + lastReadSequenceNumber: 0, + lastMessageTimestamp: NEW_REPORT_CREATED_MOMENT.utc(), + lastMessageText: 'Comment 1', + participants: [USER_C_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${NEW_REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: NEW_REPORT_CREATED_MOMENT.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: { + actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT, + actorEmail: USER_C_EMAIL, + person: [{type: 'TEXT', style: 'strong', text: 'User C'}], + sequenceNumber: 1, + timestamp: NEW_REPORT_CREATED_MOMENT.add(5, 'seconds').unix(), + message: [{type: 'COMMENT', html: 'Comment 1', text: 'Comment 1'}], + reportActionID: NumberUtils.rand64(), + }, + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_C_EMAIL]: TestHelper.buildPersonalDetails(USER_C_EMAIL, USER_C_ACCOUNT_ID, 'C'), + }); + await waitForPromisesToResolve(); - TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); - await waitForPromisesToResolve(); + // Verify notification was created as the new message that has arrived is very recent + expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); - const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); + // Navigate back to the sidebar + await navigateToSidebar(renderedApp); - // Simulate setting an unread report and personal details - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { - reportID: REPORT_ID, - reportName: 'Chat Report', - maxSequenceNumber: 9, - lastReadSequenceNumber: 1, - lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), // Ten minutes ago - lastMessageText: 'Test', - participants: [USER_B_EMAIL], - }); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { - 0: { - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - automatic: false, - sequenceNumber: 0, - timestamp: MOMENT_TEN_MINUTES_AGO.unix(), - reportActionID: NumberUtils.rand64(), - }, - 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), - 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), - 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), - 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), - 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), - 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), - 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), - 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), - 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), - }); - Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { - [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), - }); - await waitForPromisesToResolve(); - - // Verify no notifications are created for these older messages - expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); - - // Verify the sidebar links are rendered - const sidebarLinks = renderedApp.getByTestId('sidebar-links'); - expect(sidebarLinks).toBeTruthy(); - - // And verify that the Report screen is rendered after manually setting the sidebar as loaded - // since the onLayout event does not fire in tests - AppActions.setSidebarLoaded(true); - await waitForPromisesToResolve(); - - expect(isDrawerOpen(renderedApp)).toBe(true); - - // Verify there is only one option in the sidebar - let optionRows = renderedApp.getAllByTestId('option-row'); - expect(optionRows.length).toBe(1); - - // And that the text is bold - const displayNameText = renderedApp.getByTestId('option-row-display-name'); - expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - - await navigateToSidebarOption(renderedApp, 0); - - // Verify that the report screen is rendered and the drawer is closed - expect(isDrawerOpen(renderedApp)).toBe(false); - - // That the report actions are visible along with the created action - const createdAction = renderedApp.getByTestId('report-action-created'); - expect(createdAction).toBeTruthy(); - const reportComments = renderedApp.getAllByTestId('report-action-item'); - expect(reportComments.length).toBe(9); - - // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will - // have a sequenceNumber of 2 - let unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(1); - let sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); - expect(sequenceNumber).toBe(2); - - // Scroll up and verify that the "New messages" badge appears - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); - - // And that the option row in the LHN is no longer bold (since OpenReport marked it as read) - const updatedDisplayNameText = renderedApp.getByTestId('option-row-display-name'); - expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - - // Tap on the back button to return to the sidebar - await navigateToSidebar(renderedApp); - - // Verify the LHN is now open - expect(isDrawerOpen(renderedApp)).toBe(true); - - // Navigate to the report again - await navigateToSidebarOption(renderedApp, 0); - - // Verify the unread indicator is no longer present - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(0); - expect(isDrawerOpen(renderedApp)).toBe(false); - - // Scroll and verify that the new messages badge is hidden - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); - - // Simulate a new report arriving via Pusher along with reportActions and personalDetails for the other participant - const NEW_REPORT_ID = 2; - const NEW_REPORT_CREATED_MOMENT = moment(); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${NEW_REPORT_ID}`, { - reportID: NEW_REPORT_ID, - reportName: 'Chat Report', - maxSequenceNumber: 1, - lastReadSequenceNumber: 0, - lastMessageTimestamp: NEW_REPORT_CREATED_MOMENT.utc(), - lastMessageText: 'Comment 1', - participants: [USER_C_EMAIL], - }); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${NEW_REPORT_ID}`, { - 0: { - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - automatic: false, - sequenceNumber: 0, - timestamp: NEW_REPORT_CREATED_MOMENT.unix(), - reportActionID: NumberUtils.rand64(), - }, - 1: { - actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT, - actorEmail: USER_C_EMAIL, - person: [{type: 'TEXT', style: 'strong', text: 'User C'}], - sequenceNumber: 1, - timestamp: NEW_REPORT_CREATED_MOMENT.add(5, 'seconds').unix(), - message: [{type: 'COMMENT', html: 'Comment 1', text: 'Comment 1'}], - reportActionID: NumberUtils.rand64(), - }, - }); - Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { - [USER_C_EMAIL]: TestHelper.buildPersonalDetails(USER_C_EMAIL, USER_C_ACCOUNT_ID, 'C'), - }); - await waitForPromisesToResolve(); - - // Verify notification was created as the new message that has arrived is very recent - expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); - - // Navigate back to the sidebar - await navigateToSidebar(renderedApp); - - // Verify the new report option appears in the LHN - optionRows = renderedApp.getAllByTestId('option-row'); - expect(optionRows.length).toBe(2); - - // Verify the text for the new chat is bold and above the previous indicating it has not yet been read - let displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); - expect(displayNameTexts.length).toBe(2); - const firstReportOption = displayNameTexts[0]; - expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); - - const secondReportOption = displayNameTexts[1]; - expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(secondReportOption, ['props', 'children'])).toBe('B User'); - - // Tap the new report option and navigate back to the sidebar again via the back button - await navigateToSidebarOption(renderedApp, 0); - - // Verify that all report options appear in a "read" state - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); - - // Tap the previous report between User A and User B - await navigateToSidebarOption(renderedApp, 1); - - // It's difficult to trigger marking a report comment as unread since we would have to mock the long press event and then - // another press on the context menu item so we will do it via the action directly and then test if the UI has updated properly - Report.markCommentAsUnread(REPORT_ID, 3); - await waitForPromisesToResolve(); - - // Verify the indicator appears above the last action - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(1); - sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); - expect(sequenceNumber).toBe(3); - - // Scroll up and verify the new messages badge appears - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); - - // Navigate to the sidebar - await navigateToSidebar(renderedApp); - - // Verify the report is marked as unread in the sidebar - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); - - // Navigate to the report again and back to the sidebar - await navigateToSidebarOption(renderedApp, 1); - await navigateToSidebar(renderedApp); - - // Verify the report is now marked as read - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); - - // Navigate to the report again and verify the new line indicator is missing - await navigateToSidebarOption(renderedApp, 1); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(0); - - // Scroll up and verify the badge is hidden - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); - expect(isDrawerOpen(renderedApp)).toBe(false); - - // Navigate to the LHN - await navigateToSidebar(renderedApp); - - // Simulate another new message on the report with User B - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { - 10: TestHelper.buildTestReportComment(USER_B_EMAIL, 10, moment().unix()), + // Verify the new report option appears in the LHN + optionRows = renderedApp.getAllByTestId('option-row'); + expect(optionRows.length).toBe(2); + + // Verify the text for the new chat is bold and above the previous indicating it has not yet been read + let displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + const firstReportOption = displayNameTexts[0]; + expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); + + const secondReportOption = displayNameTexts[1]; + expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(secondReportOption, ['props', 'children'])).toBe('B User'); + + // Tap the new report option and navigate back to the sidebar again via the back button + await navigateToSidebarOption(renderedApp, 0); + + // Verify that all report options appear in a "read" state + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + + // Tap the previous report between User A and User B + await navigateToSidebarOption(renderedApp, 1); + + // It's difficult to trigger marking a report comment as unread since we would have to mock the long press event and then + // another press on the context menu item so we will do it via the action directly and then test if the UI has updated properly + Report.markCommentAsUnread(REPORT_ID, 3); + await waitForPromisesToResolve(); + + // Verify the indicator appears above the last action + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + expect(sequenceNumber).toBe(3); + + // Scroll up and verify the new messages badge appears + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + + // Navigate to the sidebar + await navigateToSidebar(renderedApp); + + // Verify the report is marked as unread in the sidebar + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + + // Navigate to the report again and back to the sidebar + await navigateToSidebarOption(renderedApp, 1); + await navigateToSidebar(renderedApp); + + // Verify the report is now marked as read + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + + // Navigate to the report again and verify the new line indicator is missing + await navigateToSidebarOption(renderedApp, 1); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + + // Scroll up and verify the badge is hidden + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + expect(isDrawerOpen(renderedApp)).toBe(false); + + // Navigate to the LHN + await navigateToSidebar(renderedApp); + + // Simulate another new message on the report with User B + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + 10: TestHelper.buildTestReportComment(USER_B_EMAIL, 10, moment().unix()), + }); + await waitForPromisesToResolve(); + + displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + // Navigate to the report again and verify the indicator exists + await navigateToSidebarOption(renderedApp, 1); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + + // Leave a comment as the current user and verify the indicator is removed + Report.addComment(REPORT_ID, 'Current User Comment 1'); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + + // Mark a previous comment as unread and verify the unread action indicator returns + Report.markCommentAsUnread(REPORT_ID, 9); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); + + // Trigger the app going inactive and active again + AppState.emitCurrentTestState('background'); + AppState.emitCurrentTestState('active'); + + // Verify the new line is cleared + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(0); + + // As the current user add several comments + Report.addComment(REPORT_ID, 'Current User Comment 2'); + await waitForPromisesToResolve(); + + Report.addComment(REPORT_ID, 'Current User Comment 3'); + await waitForPromisesToResolve(); + + Report.addComment(REPORT_ID, 'Current User Comment 4'); + await waitForPromisesToResolve(); + + // Mark the last comment as "unread" and verify the unread indicator appears + Report.markCommentAsUnread(REPORT_ID, 14); + await waitForPromisesToResolve(); + unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + expect(unreadIndicator.length).toBe(1); }); - await waitForPromisesToResolve(); - - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - - // Navigate to the report again and verify the indicator exists - await navigateToSidebarOption(renderedApp, 1); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(1); - - // Leave a comment as the current user and verify the indicator is removed - Report.addComment(REPORT_ID, 'Current User Comment 1'); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(0); - - // Mark a previous comment as unread and verify the unread action indicator returns - Report.markCommentAsUnread(REPORT_ID, 9); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(1); - - // Trigger the app going inactive and active again - AppState.emitCurrentTestState('background'); - AppState.emitCurrentTestState('active'); - - // Verify the new line is cleared - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(0); - - // As the current user add several comments - Report.addComment(REPORT_ID, 'Current User Comment 2'); - await waitForPromisesToResolve(); - - Report.addComment(REPORT_ID, 'Current User Comment 3'); - await waitForPromisesToResolve(); - - Report.addComment(REPORT_ID, 'Current User Comment 4'); - await waitForPromisesToResolve(); - - // Mark the last comment as "unread" and verify the unread indicator appears - Report.markCommentAsUnread(REPORT_ID, 14); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); - expect(unreadIndicator.length).toBe(1); }); diff --git a/tests/utils/TestHelper.js b/tests/utils/TestHelper.js index 319732eca13e..eea6ae43461f 100644 --- a/tests/utils/TestHelper.js +++ b/tests/utils/TestHelper.js @@ -11,7 +11,7 @@ import * as NumberUtils from '../../src/libs/NumberUtils'; * @param {String} login * @param {Number} accountID * @param {String} [firstName] - * @returns {Promise} + * @returns {Object} */ function buildPersonalDetails(login, accountID, firstName = 'Test') { const avatar = ReportUtils.getDefaultAvatar(login); From 973de5c964596501d6adf4bcf900dbcb699817bb Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Wed, 14 Sep 2022 12:02:02 -0400 Subject: [PATCH 04/17] Remove docs from react-navigation setup and link to react-navigation docs --- jest/setup.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/jest/setup.js b/jest/setup.js index d6911480710d..5c84427e5205 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -5,16 +5,13 @@ import _ from 'underscore'; require('react-native-reanimated/lib/reanimated2/jestUtils').setUpTests(); -// Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing -jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper'); - jest.mock('react-native-blob-util', () => ({})); +// These two mocks are required as per setup instructions for react-navigation testing +// https://reactnavigation.org/docs/testing/#mocking-native-modules +jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper'); jest.mock('react-native-reanimated', () => { const Reanimated = require('react-native-reanimated/mock'); - - // The mock for `call` immediately calls the callback which is incorrect - // So we override it with a no-op Reanimated.default.call = () => {}; return Reanimated; }); From 261c712e1b8118de955bd31e6cf5b070dd285b3d Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Wed, 14 Sep 2022 12:38:59 -0400 Subject: [PATCH 05/17] Clean up all testID and use accessibilityHint or accessibilityLabel instead --- src/components/DisplayNames/index.native.js | 2 +- src/components/OptionRow.js | 5 +- src/components/OptionsList/BaseOptionsList.js | 2 +- src/components/Text.js | 4 -- src/components/UnreadActionIndicator.js | 2 +- src/pages/home/HeaderView.js | 2 +- src/pages/home/ReportHeaderViewBackButton.js | 1 + src/pages/home/ReportScreen.js | 2 +- .../FloatingMessageCounterContainer/index.js | 5 +- .../report/FloatingMessageCounter/index.js | 2 +- src/pages/home/report/ReportActionItem.js | 2 +- .../home/report/ReportActionItemCreated.js | 2 +- src/pages/home/report/ReportActionsList.js | 3 +- src/pages/home/sidebar/SidebarLinks.js | 3 +- src/pages/signin/LoginForm.js | 2 +- tests/ui/UnreadIndicatorsTest.js | 56 +++++++++---------- 16 files changed, 47 insertions(+), 48 deletions(-) diff --git a/src/components/DisplayNames/index.native.js b/src/components/DisplayNames/index.native.js index 91ed0406a0d7..743a8036b965 100644 --- a/src/components/DisplayNames/index.native.js +++ b/src/components/DisplayNames/index.native.js @@ -4,7 +4,7 @@ import Text from '../Text'; // As we don't have to show tooltips of the Native platform so we simply render the full display names list. const DisplayNames = props => ( - + {props.fullTitle} ); diff --git a/src/components/OptionRow.js b/src/components/OptionRow.js index 40471941aba4..e408387b1a3f 100644 --- a/src/components/OptionRow.js +++ b/src/components/OptionRow.js @@ -148,7 +148,7 @@ const OptionRow = (props) => { props.isDisabled && styles.cursorDisabled, ]} > - + { } { /> {props.option.alternateText ? ( diff --git a/src/components/OptionsList/BaseOptionsList.js b/src/components/OptionsList/BaseOptionsList.js index e5524c49dab5..c9f983a9720f 100644 --- a/src/components/OptionsList/BaseOptionsList.js +++ b/src/components/OptionsList/BaseOptionsList.js @@ -166,6 +166,7 @@ class BaseOptionsList extends Component { renderItem({item, index, section}) { return ( ) : null} ( - + {props.translate('common.new')} diff --git a/src/pages/home/HeaderView.js b/src/pages/home/HeaderView.js index ea5db9406a7e..6e5b625e7491 100644 --- a/src/pages/home/HeaderView.js +++ b/src/pages/home/HeaderView.js @@ -91,7 +91,7 @@ const HeaderView = (props) => { const icons = ReportUtils.getIcons(props.report, props.personalDetails, props.policies); const brickRoadIndicator = ReportUtils.hasReportNameError(props.report) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : ''; return ( - + {props.isSmallScreenWidth && ( ( diff --git a/src/pages/home/ReportScreen.js b/src/pages/home/ReportScreen.js index 4e43bb06956c..7ac2117071c0 100644 --- a/src/pages/home/ReportScreen.js +++ b/src/pages/home/ReportScreen.js @@ -237,7 +237,7 @@ class ReportScreen extends React.Component { /> this.setState({skeletonViewContainerHeight: event.nativeEvent.layout.height})} diff --git a/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js b/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js index a367eea5f602..91ad8203ce81 100644 --- a/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js +++ b/src/pages/home/report/FloatingMessageCounter/FloatingMessageCounterContainer/index.js @@ -4,7 +4,10 @@ import styles from '../../../../../styles/styles'; import floatingMessageCounterContainerPropTypes from './floatingMessageCounterContainerPropTypes'; const FloatingMessageCounterContainer = props => ( - + {props.children} ); diff --git a/src/pages/home/report/FloatingMessageCounter/index.js b/src/pages/home/report/FloatingMessageCounter/index.js index 8af8266b0a87..9cfb9ba5818f 100644 --- a/src/pages/home/report/FloatingMessageCounter/index.js +++ b/src/pages/home/report/FloatingMessageCounter/index.js @@ -62,7 +62,7 @@ class FloatingMessageCounter extends PureComponent { render() { return ( - + {hovered => ( - + {this.props.shouldDisplayNewIndicator && ( )} diff --git a/src/pages/home/report/ReportActionItemCreated.js b/src/pages/home/report/ReportActionItemCreated.js index 10b5fcd31f5e..93bc71a3eab6 100644 --- a/src/pages/home/report/ReportActionItemCreated.js +++ b/src/pages/home/report/ReportActionItemCreated.js @@ -39,7 +39,7 @@ const ReportActionItemCreated = (props) => { const icons = ReportUtils.getIcons(props.report, props.personalDetails, props.policies); return ( + - + this.input = el} label={this.props.translate('loginForm.phoneOrEmail')} diff --git a/tests/ui/UnreadIndicatorsTest.js b/tests/ui/UnreadIndicatorsTest.js index cc0defa51e62..d13953880d91 100644 --- a/tests/ui/UnreadIndicatorsTest.js +++ b/tests/ui/UnreadIndicatorsTest.js @@ -13,7 +13,6 @@ import * as TestHelper from '../utils/TestHelper'; import appSetup from '../../src/setup'; import fontWeightBold from '../../src/styles/fontWeight/bold'; import * as AppActions from '../../src/libs/actions/App'; -import ReportHeaderViewBackButton from '../../src/pages/home/ReportHeaderViewBackButton'; import ReportActionsView from '../../src/pages/home/report/ReportActionsView'; import * as NumberUtils from '../../src/libs/NumberUtils'; import LocalNotification from '../../src/libs/Notification/LocalNotification'; @@ -37,7 +36,7 @@ beforeAll(() => { * @param {RenderAPI} renderedApp */ function scrollUpToRevealNewMessagesBadge(renderedApp) { - fireEvent.scroll(renderedApp.getByTestId('report-actions-list'), { + fireEvent.scroll(renderedApp.getByA11yLabel('List of chat messages'), { nativeEvent: { contentOffset: { y: 250, @@ -65,7 +64,7 @@ function scrollUpToRevealNewMessagesBadge(renderedApp) { * @return {Boolean} */ function isNewMessagesBadgeVisible(renderedApp) { - const badge = renderedApp.getByTestId('new-messages-badge'); + const badge = renderedApp.getByA11yHint('Scroll to newest messages'); return badge.props.style.transform[0].translateY === 10; } @@ -74,8 +73,7 @@ function isNewMessagesBadgeVisible(renderedApp) { * @return {Promise} */ async function navigateToSidebar(renderedApp) { - const reportHeader = renderedApp.getByTestId('report-header'); - const reportHeaderBackButton = await reportHeader.findByType(ReportHeaderViewBackButton); + const reportHeaderBackButton = renderedApp.getByA11yHint('Navigate back to chats list'); fireEvent(reportHeaderBackButton, 'press'); return waitForPromisesToResolve(); } @@ -86,7 +84,7 @@ async function navigateToSidebar(renderedApp) { * @return {Promise} */ function navigateToSidebarOption(renderedApp, index) { - const optionRows = renderedApp.getAllByTestId('option-row'); + const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); fireEvent(optionRows[index], 'press'); return waitForPromisesToResolve(); } @@ -96,7 +94,7 @@ function navigateToSidebarOption(renderedApp, index) { * @return {Boolean} */ function isDrawerOpen(renderedApp) { - const reportScreen = renderedApp.getByTestId('report-screen'); + const reportScreen = renderedApp.getByA11yLabel('Main chat area'); return reportScreen.findByType(ReportActionsView).props.isDrawerOpen; } @@ -119,7 +117,7 @@ describe('Unread Indicators', () => { await waitForPromisesToResolve(); }); - const loginForm = renderedApp.queryAllByTestId('login-form'); + const loginForm = renderedApp.queryAllByA11yLabel('Login form'); expect(loginForm.length).toBe(1); await TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); @@ -163,7 +161,7 @@ describe('Unread Indicators', () => { expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); // Verify the sidebar links are rendered - const sidebarLinks = renderedApp.queryAllByTestId('sidebar-links'); + const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); expect(sidebarLinks.length).toBe(1); // And verify that the Report screen is rendered after manually setting the sidebar as loaded @@ -174,11 +172,11 @@ describe('Unread Indicators', () => { expect(isDrawerOpen(renderedApp)).toBe(true); // Verify there is only one option in the sidebar - let optionRows = renderedApp.getAllByTestId('option-row'); + let optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); expect(optionRows.length).toBe(1); // And that the text is bold - const displayNameText = renderedApp.getByTestId('option-row-display-name'); + const displayNameText = renderedApp.getByA11yLabel('Chat user display names'); expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); await navigateToSidebarOption(renderedApp, 0); @@ -187,14 +185,14 @@ describe('Unread Indicators', () => { expect(isDrawerOpen(renderedApp)).toBe(false); // That the report actions are visible along with the created action - const createdAction = renderedApp.getByTestId('report-action-created'); + const createdAction = renderedApp.getByA11yLabel('Chat welcome message'); expect(createdAction).toBeTruthy(); - const reportComments = renderedApp.getAllByTestId('report-action-item'); + const reportComments = renderedApp.getAllByA11yLabel('Chat message'); expect(reportComments.length).toBe(9); // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will // have a sequenceNumber of 2 - let unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); let sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); expect(sequenceNumber).toBe(2); @@ -204,7 +202,7 @@ describe('Unread Indicators', () => { expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); // And that the option row in the LHN is no longer bold (since OpenReport marked it as read) - const updatedDisplayNameText = renderedApp.getByTestId('option-row-display-name'); + const updatedDisplayNameText = renderedApp.getByA11yLabel('Chat user display names'); expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); // Tap on the back button to return to the sidebar @@ -217,7 +215,7 @@ describe('Unread Indicators', () => { await navigateToSidebarOption(renderedApp, 0); // Verify the unread indicator is no longer present - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); expect(isDrawerOpen(renderedApp)).toBe(false); @@ -267,11 +265,11 @@ describe('Unread Indicators', () => { await navigateToSidebar(renderedApp); // Verify the new report option appears in the LHN - optionRows = renderedApp.getAllByTestId('option-row'); + optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); expect(optionRows.length).toBe(2); // Verify the text for the new chat is bold and above the previous indicating it has not yet been read - let displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + let displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); const firstReportOption = displayNameTexts[0]; expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); @@ -285,7 +283,7 @@ describe('Unread Indicators', () => { await navigateToSidebarOption(renderedApp, 0); // Verify that all report options appear in a "read" state - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); @@ -301,7 +299,7 @@ describe('Unread Indicators', () => { await waitForPromisesToResolve(); // Verify the indicator appears above the last action - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); expect(sequenceNumber).toBe(3); @@ -314,7 +312,7 @@ describe('Unread Indicators', () => { await navigateToSidebar(renderedApp); // Verify the report is marked as unread in the sidebar - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); @@ -324,7 +322,7 @@ describe('Unread Indicators', () => { await navigateToSidebar(renderedApp); // Verify the report is now marked as read - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); @@ -332,7 +330,7 @@ describe('Unread Indicators', () => { // Navigate to the report again and verify the new line indicator is missing await navigateToSidebarOption(renderedApp, 1); await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); // Scroll up and verify the badge is hidden @@ -349,7 +347,7 @@ describe('Unread Indicators', () => { }); await waitForPromisesToResolve(); - displayNameTexts = renderedApp.queryAllByTestId('option-row-display-name'); + displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); @@ -358,19 +356,19 @@ describe('Unread Indicators', () => { // Navigate to the report again and verify the indicator exists await navigateToSidebarOption(renderedApp, 1); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); // Leave a comment as the current user and verify the indicator is removed Report.addComment(REPORT_ID, 'Current User Comment 1'); await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); // Mark a previous comment as unread and verify the unread action indicator returns Report.markCommentAsUnread(REPORT_ID, 9); await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); // Trigger the app going inactive and active again @@ -378,7 +376,7 @@ describe('Unread Indicators', () => { AppState.emitCurrentTestState('active'); // Verify the new line is cleared - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); // As the current user add several comments @@ -394,7 +392,7 @@ describe('Unread Indicators', () => { // Mark the last comment as "unread" and verify the unread indicator appears Report.markCommentAsUnread(REPORT_ID, 14); await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByTestId('unread-action-indicator'); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); }); }); From ac9fe71febeec7b2e95575a2c0b370d3d9e7de28 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Wed, 14 Sep 2022 12:49:39 -0400 Subject: [PATCH 06/17] Use accessibilityElementsHidden --- src/pages/home/ReportScreen.js | 1 - src/pages/home/sidebar/SidebarLinks.js | 10 +++++++++- tests/ui/UnreadIndicatorsTest.js | 4 ++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/pages/home/ReportScreen.js b/src/pages/home/ReportScreen.js index 7ac2117071c0..92b334ebabb6 100644 --- a/src/pages/home/ReportScreen.js +++ b/src/pages/home/ReportScreen.js @@ -237,7 +237,6 @@ class ReportScreen extends React.Component { /> this.setState({skeletonViewContainerHeight: event.nativeEvent.layout.height})} diff --git a/src/pages/home/sidebar/SidebarLinks.js b/src/pages/home/sidebar/SidebarLinks.js index a3250b6d4f4f..c6c905a2030d 100644 --- a/src/pages/home/sidebar/SidebarLinks.js +++ b/src/pages/home/sidebar/SidebarLinks.js @@ -26,6 +26,8 @@ import withLocalize, {withLocalizePropTypes} from '../../../components/withLocal import * as App from '../../../libs/actions/App'; import * as ReportUtils from '../../../libs/ReportUtils'; import withCurrentUserPersonalDetails from '../../../components/withCurrentUserPersonalDetails'; +import withDrawerState from '../../../components/withDrawerState'; +import withWindowDimensions from '../../../components/withWindowDimensions'; const propTypes = { /** Toggles the navigation menu open and closed */ @@ -253,7 +255,11 @@ class SidebarLinks extends React.Component { }]; return ( - + { From 68fed0c20d29468cf248612bb2f3ef3e7882de19 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Wed, 14 Sep 2022 12:54:59 -0400 Subject: [PATCH 07/17] Undo unnecessary refactor of back button --- src/pages/home/HeaderView.js | 14 +++++---- src/pages/home/ReportHeaderViewBackButton.js | 31 -------------------- 2 files changed, 9 insertions(+), 36 deletions(-) delete mode 100644 src/pages/home/ReportHeaderViewBackButton.js diff --git a/src/pages/home/HeaderView.js b/src/pages/home/HeaderView.js index 6e5b625e7491..69a8b524c263 100644 --- a/src/pages/home/HeaderView.js +++ b/src/pages/home/HeaderView.js @@ -26,7 +26,6 @@ import Text from '../../components/Text'; import Tooltip from '../../components/Tooltip'; import variables from '../../styles/variables'; import colors from '../../styles/colors'; -import ReportHeaderViewBackButton from './ReportHeaderViewBackButton'; const propTypes = { /** Toggles the navigationMenu open and closed */ @@ -94,10 +93,15 @@ const HeaderView = (props) => { {props.isSmallScreenWidth && ( - + + + + + )} {Boolean(props.report && title) && ( ( - - - - - -); - -ReportHeaderViewBackButton.displayName = 'ReportHeaderViewBackButton'; -ReportHeaderViewBackButton.propTypes = propTypes; -export default ReportHeaderViewBackButton; From efb1d62e1874e77e4deb6bad46a449e343a1f934 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 13:23:50 -0400 Subject: [PATCH 08/17] Remove jest.setTimeout() by breaking test up into smaller chunks --- tests/ui/UnreadIndicatorsTest.js | 280 +++++++++++++++++-------------- 1 file changed, 152 insertions(+), 128 deletions(-) diff --git a/tests/ui/UnreadIndicatorsTest.js b/tests/ui/UnreadIndicatorsTest.js index 32013bcb1b38..b05d2b77ff14 100644 --- a/tests/ui/UnreadIndicatorsTest.js +++ b/tests/ui/UnreadIndicatorsTest.js @@ -13,7 +13,6 @@ import * as TestHelper from '../utils/TestHelper'; import appSetup from '../../src/setup'; import fontWeightBold from '../../src/styles/fontWeight/bold'; import * as AppActions from '../../src/libs/actions/App'; -import ReportActionsView from '../../src/pages/home/report/ReportActionsView'; import * as NumberUtils from '../../src/libs/NumberUtils'; import LocalNotification from '../../src/libs/Notification/LocalNotification'; import * as Report from '../../src/libs/actions/Report'; @@ -27,7 +26,6 @@ beforeAll(() => { global.fetch = TestHelper.getGlobalFetchMock(); // We need a bit more time for this test in some places - jest.setTimeout(30000); Linking.setInitialURL('https://new.expensify.com/r/1'); appSetup(); }); @@ -98,64 +96,77 @@ function isDrawerOpen(renderedApp) { return !lodashGet(sidebarLinks, [0, 'props', 'accessibilityElementsHidden']); } -describe('Unread Indicators', () => { - it('Shows correct LHN Status, “New Messages” badge, and New Line Indicators', async () => { - const REPORT_ID = 1; - const USER_A_ACCOUNT_ID = 1; - const USER_A_EMAIL = 'user_a@test.com'; - const USER_B_ACCOUNT_ID = 2; - const USER_B_EMAIL = 'user_b@test.com'; - const USER_C_ACCOUNT_ID = 3; - const USER_C_EMAIL = 'user_c@test.com'; - - // Render the App and sign in as a test user. - const renderedApp = render(); - - // Note: act() is necessary since react-navigation's NavigationContainer has an internal state update that will throw some - // warnings related to async code. See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act - await act(async () => { - await waitForPromisesToResolve(); - }); +const REPORT_ID = 1; +const USER_A_ACCOUNT_ID = 1; +const USER_A_EMAIL = 'user_a@test.com'; +const USER_B_ACCOUNT_ID = 2; +const USER_B_EMAIL = 'user_b@test.com'; +const USER_C_ACCOUNT_ID = 3; +const USER_C_EMAIL = 'user_c@test.com'; - const loginForm = renderedApp.queryAllByA11yLabel('Login form'); - expect(loginForm.length).toBe(1); +/** + * @returns {RenderAPI} + */ +async function signInAndGetAppWithUnreadChat() { + // Render the App and sign in as a test user. + const renderedApp = render(); - await TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); + // Note: act() is necessary since react-navigation's NavigationContainer has an internal state update that will throw some + // warnings related to async code. See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act + await act(async () => { + await waitForPromisesToResolve(); + }); - const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); + const loginForm = renderedApp.queryAllByA11yLabel('Login form'); + expect(loginForm.length).toBe(1); - // Simulate setting an unread report and personal details - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { - reportID: REPORT_ID, - reportName: 'Chat Report', - maxSequenceNumber: 9, - lastReadSequenceNumber: 1, - lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), - lastMessageText: 'Test', - participants: [USER_B_EMAIL], - }); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { - 0: { - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - automatic: false, - sequenceNumber: 0, - timestamp: MOMENT_TEN_MINUTES_AGO.unix(), - reportActionID: NumberUtils.rand64(), - }, - 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), - 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), - 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), - 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), - 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), - 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), - 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), - 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), - 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), - }); - Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { - [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), - }); - await waitForPromisesToResolve(); + await TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); + + const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); + + // Simulate setting an unread report and personal details + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + reportID: REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 9, + lastReadSequenceNumber: 1, + lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), + lastMessageText: 'Test', + participants: [USER_B_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: MOMENT_TEN_MINUTES_AGO.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), + 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), + 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), + 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), + 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), + 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), + 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), + 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), + 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), + }); + + // We manually setting the sidebar as loaded since the onLayout event does not fire in tests + AppActions.setSidebarLoaded(true); + await waitForPromisesToResolve(); + return renderedApp; +} + +describe('Unread Indicators', () => { + afterEach(Onyx.clear); + + it('Display bold in the LHN for unread chat and new line indicator above the chat message when we navigate to it', async () => { + const renderedApp = await signInAndGetAppWithUnreadChat(); // Verify no notifications are created for these older messages expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); @@ -163,16 +174,10 @@ describe('Unread Indicators', () => { // Verify the sidebar links are rendered const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); expect(sidebarLinks.length).toBe(1); - - // And verify that the Report screen is rendered after manually setting the sidebar as loaded - // since the onLayout event does not fire in tests - AppActions.setSidebarLoaded(true); - await waitForPromisesToResolve(); - expect(isDrawerOpen(renderedApp)).toBe(true); // Verify there is only one option in the sidebar - let optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); + const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); expect(optionRows.length).toBe(1); // And that the text is bold @@ -192,36 +197,50 @@ describe('Unread Indicators', () => { // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will // have a sequenceNumber of 2 - let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); - let sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); expect(sequenceNumber).toBe(2); // Scroll up and verify that the "New messages" badge appears scrollUpToRevealNewMessagesBadge(renderedApp); expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + }); - // And that the option row in the LHN is no longer bold (since OpenReport marked it as read) - const updatedDisplayNameText = renderedApp.getByA11yLabel('Chat user display names'); - expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + it('Clear the new line indicator and bold when we navigate away from a chat that is now read', async () => { + const renderedApp = await signInAndGetAppWithUnreadChat(); + + // Navigate to the unread chat from the sidebar + await navigateToSidebarOption(renderedApp, 0); + expect(isDrawerOpen(renderedApp)).toBe(false); - // Tap on the back button to return to the sidebar + // Then navigate back to the sidebar await navigateToSidebar(renderedApp); // Verify the LHN is now open expect(isDrawerOpen(renderedApp)).toBe(true); - // Navigate to the report again + // Verify that the option row in the LHN is no longer bold (since OpenReport marked it as read) + const updatedDisplayNameText = renderedApp.getByA11yLabel('Chat user display names'); + expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + + // Tap on the chat again await navigateToSidebarOption(renderedApp, 0); - // Verify the unread indicator is no longer present - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + // Verify the unread indicator is not present + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); expect(isDrawerOpen(renderedApp)).toBe(false); - // Scroll and verify that the new messages badge is hidden + // Scroll and verify that the new messages badge is also hidden scrollUpToRevealNewMessagesBadge(renderedApp); expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + }); + + it('Shows a browser notification and bold text when a new message arrives for a chat that is read', async () => { + const renderedApp = await signInAndGetAppWithUnreadChat(); + + // Read the chat by navigating to it then return to the LHN // Simulate a new report arriving via Pusher along with reportActions and personalDetails for the other participant const NEW_REPORT_ID = 2; @@ -261,14 +280,14 @@ describe('Unread Indicators', () => { // Verify notification was created as the new message that has arrived is very recent expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); - // Navigate back to the sidebar + // // Navigate back to the sidebar await navigateToSidebar(renderedApp); - // Verify the new report option appears in the LHN - optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); + // // Verify the new report option appears in the LHN + const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); expect(optionRows.length).toBe(2); - // Verify the text for the new chat is bold and above the previous indicating it has not yet been read + // Verify the text for both chats are bold indicating that nothing has not yet been read let displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); const firstReportOption = displayNameTexts[0]; @@ -276,22 +295,26 @@ describe('Unread Indicators', () => { expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); const secondReportOption = displayNameTexts[1]; - expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); expect(lodashGet(secondReportOption, ['props', 'children'])).toBe('B User'); // Tap the new report option and navigate back to the sidebar again via the back button await navigateToSidebarOption(renderedApp, 0); - // Verify that all report options appear in a "read" state + // Verify that report we navigated to appears in a "read" state while the original unread report still shows as unread displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); expect(displayNameTexts.length).toBe(2); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + }); - // Tap the previous report between User A and User B - await navigateToSidebarOption(renderedApp, 1); + it('Manually marking a chat message as read shows the new line indicator and updates the LHN', async () => { + const renderedApp = await signInAndGetAppWithUnreadChat(); + + // Navigate to the unread report + await navigateToSidebarOption(renderedApp, 0); // It's difficult to trigger marking a report comment as unread since we would have to mock the long press event and then // another press on the context menu item so we will do it via the action directly and then test if the UI has updated properly @@ -299,9 +322,9 @@ describe('Unread Indicators', () => { await waitForPromisesToResolve(); // Verify the indicator appears above the last action - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); - sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); expect(sequenceNumber).toBe(3); // Scroll up and verify the new messages badge appears @@ -312,51 +335,45 @@ describe('Unread Indicators', () => { await navigateToSidebar(renderedApp); // Verify the report is marked as unread in the sidebar - displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + let displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); // Navigate to the report again and back to the sidebar - await navigateToSidebarOption(renderedApp, 1); + await navigateToSidebarOption(renderedApp, 0); await navigateToSidebar(renderedApp); // Verify the report is now marked as read displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); // Navigate to the report again and verify the new line indicator is missing - await navigateToSidebarOption(renderedApp, 1); - await waitForPromisesToResolve(); + await navigateToSidebarOption(renderedApp, 0); unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); - // Scroll up and verify the badge is hidden + // Scroll up and verify the "New messages" badge is hidden scrollUpToRevealNewMessagesBadge(renderedApp); expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); - expect(isDrawerOpen(renderedApp)).toBe(false); + }); - // Navigate to the LHN - await navigateToSidebar(renderedApp); + it('Removes the new line indicator when a new message is created by the current user', async () => { + const renderedApp = await signInAndGetAppWithUnreadChat(); - // Simulate another new message on the report with User B - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { - 10: TestHelper.buildTestReportComment(USER_B_EMAIL, 10, moment().unix()), - }); - await waitForPromisesToResolve(); + // Verify we are on the LHN and that the chat shows as unread in the LHN + expect(isDrawerOpen(renderedApp)).toBe(true); - displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - // Navigate to the report again and verify the indicator exists - await navigateToSidebarOption(renderedApp, 1); - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + // Navigate to the report and verify the indicator is present + await navigateToSidebarOption(renderedApp, 0); + let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(1); // Leave a comment as the current user and verify the indicator is removed @@ -364,6 +381,29 @@ describe('Unread Indicators', () => { await waitForPromisesToResolve(); unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); + }); + + it('Clears the new line indicator when the user moves the App to the background', async () => { + const renderedApp = await signInAndGetAppWithUnreadChat(); + + // Verify we are on the LHN and that the chat shows as unread in the LHN + expect(isDrawerOpen(renderedApp)).toBe(true); + + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + // Navigate to the chat and verify the new line indicator is present + await navigateToSidebarOption(renderedApp, 0); + let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(1); + + // Then back to the LHN - then back to the chat again and verify the new line indicator has cleared + await navigateToSidebar(renderedApp); + await navigateToSidebarOption(renderedApp, 0); + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(0); // Mark a previous comment as unread and verify the unread action indicator returns Report.markCommentAsUnread(REPORT_ID, 9); @@ -378,21 +418,5 @@ describe('Unread Indicators', () => { // Verify the new line is cleared unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); expect(unreadIndicator.length).toBe(0); - - // As the current user add several comments - Report.addComment(REPORT_ID, 'Current User Comment 2'); - await waitForPromisesToResolve(); - - Report.addComment(REPORT_ID, 'Current User Comment 3'); - await waitForPromisesToResolve(); - - Report.addComment(REPORT_ID, 'Current User Comment 4'); - await waitForPromisesToResolve(); - - // Mark the last comment as "unread" and verify the unread indicator appears - Report.markCommentAsUnread(REPORT_ID, 14); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); }); }); From 18367421f260003630e554647d02481d021f7415 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 13:56:52 -0400 Subject: [PATCH 09/17] Extract the one part of tests that actually does need async/await to work. Use regular promises in the actual tests themselves --- contributingGuides/STYLE.md | 2 +- tests/ui/UnreadIndicatorsTest.js | 639 ++++++++++-------- .../utils/waitForPromisesToResolveWithAct.js | 21 + 3 files changed, 364 insertions(+), 298 deletions(-) create mode 100644 tests/utils/waitForPromisesToResolveWithAct.js diff --git a/contributingGuides/STYLE.md b/contributingGuides/STYLE.md index 6402d27e2e85..62e64bede72c 100644 --- a/contributingGuides/STYLE.md +++ b/contributingGuides/STYLE.md @@ -388,7 +388,7 @@ So, if a new language feature isn't something we have agreed to support it's off Here are a couple of things we would ask that you *avoid* to help maintain consistency in our codebase: -- **Async/Await** - Use the native `Promise` instead. Async/Await is permitted in test files only. +- **Async/Await** - Use the native `Promise` instead - **Optional Chaining** - Use `lodashGet()` to fetch a nested value instead - **Null Coalescing Operator** - Use `lodashGet()` or `||` to set a default value for a possibly `undefined` or `null` variable diff --git a/tests/ui/UnreadIndicatorsTest.js b/tests/ui/UnreadIndicatorsTest.js index b05d2b77ff14..45172e574f40 100644 --- a/tests/ui/UnreadIndicatorsTest.js +++ b/tests/ui/UnreadIndicatorsTest.js @@ -1,14 +1,14 @@ -/* eslint-disable @lwc/lwc/no-async-await */ import React from 'react'; import Onyx from 'react-native-onyx'; import {Linking, AppState} from 'react-native'; -import {fireEvent, render, act} from '@testing-library/react-native'; +import {fireEvent, render} from '@testing-library/react-native'; import lodashGet from 'lodash/get'; import moment from 'moment'; import App from '../../src/App'; import CONST from '../../src/CONST'; import ONYXKEYS from '../../src/ONYXKEYS'; import waitForPromisesToResolve from '../utils/waitForPromisesToResolve'; +import waitForPromisesToResolveWithAct from '../utils/waitForPromisesToResolveWithAct'; import * as TestHelper from '../utils/TestHelper'; import appSetup from '../../src/setup'; import fontWeightBold from '../../src/styles/fontWeight/bold'; @@ -70,7 +70,7 @@ function isNewMessagesBadgeVisible(renderedApp) { * @param {RenderAPI} renderedApp * @return {Promise} */ -async function navigateToSidebar(renderedApp) { +function navigateToSidebar(renderedApp) { const reportHeaderBackButton = renderedApp.getByA11yHint('Navigate back to chats list'); fireEvent(reportHeaderBackButton, 'press'); return waitForPromisesToResolve(); @@ -105,318 +105,363 @@ const USER_C_ACCOUNT_ID = 3; const USER_C_EMAIL = 'user_c@test.com'; /** + * Sets up a test with a logged in user that has one unread chat from another user. Returns the test instance. + * * @returns {RenderAPI} */ -async function signInAndGetAppWithUnreadChat() { +function signInAndGetAppWithUnreadChat() { // Render the App and sign in as a test user. const renderedApp = render(); - - // Note: act() is necessary since react-navigation's NavigationContainer has an internal state update that will throw some - // warnings related to async code. See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act - await act(async () => { - await waitForPromisesToResolve(); - }); - - const loginForm = renderedApp.queryAllByA11yLabel('Login form'); - expect(loginForm.length).toBe(1); - - await TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); - - const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); - - // Simulate setting an unread report and personal details - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { - reportID: REPORT_ID, - reportName: 'Chat Report', - maxSequenceNumber: 9, - lastReadSequenceNumber: 1, - lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), - lastMessageText: 'Test', - participants: [USER_B_EMAIL], - }); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { - 0: { - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - automatic: false, - sequenceNumber: 0, - timestamp: MOMENT_TEN_MINUTES_AGO.unix(), - reportActionID: NumberUtils.rand64(), - }, - 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), - 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), - 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), - 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), - 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), - 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), - 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), - 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), - 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), - }); - Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { - [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), - }); - - // We manually setting the sidebar as loaded since the onLayout event does not fire in tests - AppActions.setSidebarLoaded(true); - await waitForPromisesToResolve(); - return renderedApp; + return waitForPromisesToResolveWithAct() + .then(() => { + const loginForm = renderedApp.queryAllByA11yLabel('Login form'); + expect(loginForm.length).toBe(1); + + return TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); + }) + .then(() => { + const MOMENT_TEN_MINUTES_AGO = moment().subtract(10, 'minutes'); + + // Simulate setting an unread report and personal details + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + reportID: REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 9, + lastReadSequenceNumber: 1, + lastMessageTimestamp: MOMENT_TEN_MINUTES_AGO.utc(), + lastMessageText: 'Test', + participants: [USER_B_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: MOMENT_TEN_MINUTES_AGO.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: TestHelper.buildTestReportComment(USER_B_EMAIL, 1, MOMENT_TEN_MINUTES_AGO.add(10, 'seconds').unix()), + 2: TestHelper.buildTestReportComment(USER_B_EMAIL, 2, MOMENT_TEN_MINUTES_AGO.add(20, 'seconds').unix()), + 3: TestHelper.buildTestReportComment(USER_B_EMAIL, 3, MOMENT_TEN_MINUTES_AGO.add(30, 'seconds').unix()), + 4: TestHelper.buildTestReportComment(USER_B_EMAIL, 4, MOMENT_TEN_MINUTES_AGO.add(40, 'seconds').unix()), + 5: TestHelper.buildTestReportComment(USER_B_EMAIL, 5, MOMENT_TEN_MINUTES_AGO.add(50, 'seconds').unix()), + 6: TestHelper.buildTestReportComment(USER_B_EMAIL, 6, MOMENT_TEN_MINUTES_AGO.add(60, 'seconds').unix()), + 7: TestHelper.buildTestReportComment(USER_B_EMAIL, 7, MOMENT_TEN_MINUTES_AGO.add(70, 'seconds').unix()), + 8: TestHelper.buildTestReportComment(USER_B_EMAIL, 8, MOMENT_TEN_MINUTES_AGO.add(80, 'seconds').unix()), + 9: TestHelper.buildTestReportComment(USER_B_EMAIL, 9, MOMENT_TEN_MINUTES_AGO.add(90, 'seconds').unix()), + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_B_EMAIL]: TestHelper.buildPersonalDetails(USER_B_EMAIL, USER_B_ACCOUNT_ID, 'B'), + }); + + // We manually setting the sidebar as loaded since the onLayout event does not fire in tests + AppActions.setSidebarLoaded(true); + return waitForPromisesToResolve(); + }) + .then(() => renderedApp); } describe('Unread Indicators', () => { afterEach(Onyx.clear); - it('Display bold in the LHN for unread chat and new line indicator above the chat message when we navigate to it', async () => { - const renderedApp = await signInAndGetAppWithUnreadChat(); - - // Verify no notifications are created for these older messages - expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); - - // Verify the sidebar links are rendered - const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); - expect(sidebarLinks.length).toBe(1); - expect(isDrawerOpen(renderedApp)).toBe(true); - - // Verify there is only one option in the sidebar - const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); - expect(optionRows.length).toBe(1); - - // And that the text is bold - const displayNameText = renderedApp.getByA11yLabel('Chat user display names'); - expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - - await navigateToSidebarOption(renderedApp, 0); - - // Verify that the report screen is rendered and the drawer is closed - expect(isDrawerOpen(renderedApp)).toBe(false); - - // That the report actions are visible along with the created action - const createdAction = renderedApp.getByA11yLabel('Chat welcome message'); - expect(createdAction).toBeTruthy(); - const reportComments = renderedApp.getAllByA11yLabel('Chat message'); - expect(reportComments.length).toBe(9); - - // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will - // have a sequenceNumber of 2 - const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); - const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); - expect(sequenceNumber).toBe(2); - - // Scroll up and verify that the "New messages" badge appears - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + it('Display bold in the LHN for unread chat and new line indicator above the chat message when we navigate to it', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Verify no notifications are created for these older messages + expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); + + // Verify the sidebar links are rendered + const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); + expect(sidebarLinks.length).toBe(1); + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Verify there is only one option in the sidebar + const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); + expect(optionRows.length).toBe(1); + + // And that the text is bold + const displayNameText = renderedApp.getByA11yLabel('Chat user display names'); + expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + // Verify that the report screen is rendered and the drawer is closed + expect(isDrawerOpen(renderedApp)).toBe(false); + + // That the report actions are visible along with the created action + const createdAction = renderedApp.getByA11yLabel('Chat welcome message'); + expect(createdAction).toBeTruthy(); + const reportComments = renderedApp.getAllByA11yLabel('Chat message'); + expect(reportComments.length).toBe(9); + + // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will + // have a sequenceNumber of 2 + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(1); + const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + expect(sequenceNumber).toBe(2); + + // Scroll up and verify that the "New messages" badge appears + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + }); }); - it('Clear the new line indicator and bold when we navigate away from a chat that is now read', async () => { - const renderedApp = await signInAndGetAppWithUnreadChat(); - - // Navigate to the unread chat from the sidebar - await navigateToSidebarOption(renderedApp, 0); - expect(isDrawerOpen(renderedApp)).toBe(false); - - // Then navigate back to the sidebar - await navigateToSidebar(renderedApp); - - // Verify the LHN is now open - expect(isDrawerOpen(renderedApp)).toBe(true); - - // Verify that the option row in the LHN is no longer bold (since OpenReport marked it as read) - const updatedDisplayNameText = renderedApp.getByA11yLabel('Chat user display names'); - expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - - // Tap on the chat again - await navigateToSidebarOption(renderedApp, 0); - - // Verify the unread indicator is not present - const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); - expect(isDrawerOpen(renderedApp)).toBe(false); - - // Scroll and verify that the new messages badge is also hidden - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + it('Clear the new line indicator and bold when we navigate away from a chat that is now read', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Navigate to the unread chat from the sidebar + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + expect(isDrawerOpen(renderedApp)).toBe(false); + + // Then navigate back to the sidebar + return navigateToSidebar(renderedApp); + }) + .then(() => { + // Verify the LHN is now open + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Verify that the option row in the LHN is no longer bold (since OpenReport marked it as read) + const updatedDisplayNameText = renderedApp.getByA11yLabel('Chat user display names'); + expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + + // Tap on the chat again + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + // Verify the unread indicator is not present + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(0); + expect(isDrawerOpen(renderedApp)).toBe(false); + + // Scroll and verify that the new messages badge is also hidden + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + }); }); - it('Shows a browser notification and bold text when a new message arrives for a chat that is read', async () => { - const renderedApp = await signInAndGetAppWithUnreadChat(); - - // Read the chat by navigating to it then return to the LHN - - // Simulate a new report arriving via Pusher along with reportActions and personalDetails for the other participant - const NEW_REPORT_ID = 2; - const NEW_REPORT_CREATED_MOMENT = moment(); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${NEW_REPORT_ID}`, { - reportID: NEW_REPORT_ID, - reportName: 'Chat Report', - maxSequenceNumber: 1, - lastReadSequenceNumber: 0, - lastMessageTimestamp: NEW_REPORT_CREATED_MOMENT.utc(), - lastMessageText: 'Comment 1', - participants: [USER_C_EMAIL], - }); - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${NEW_REPORT_ID}`, { - 0: { - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - automatic: false, - sequenceNumber: 0, - timestamp: NEW_REPORT_CREATED_MOMENT.unix(), - reportActionID: NumberUtils.rand64(), - }, - 1: { - actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT, - actorEmail: USER_C_EMAIL, - person: [{type: 'TEXT', style: 'strong', text: 'User C'}], - sequenceNumber: 1, - timestamp: NEW_REPORT_CREATED_MOMENT.add(5, 'seconds').unix(), - message: [{type: 'COMMENT', html: 'Comment 1', text: 'Comment 1'}], - reportActionID: NumberUtils.rand64(), - }, - }); - Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { - [USER_C_EMAIL]: TestHelper.buildPersonalDetails(USER_C_EMAIL, USER_C_ACCOUNT_ID, 'C'), - }); - await waitForPromisesToResolve(); - - // Verify notification was created as the new message that has arrived is very recent - expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); - - // // Navigate back to the sidebar - await navigateToSidebar(renderedApp); - - // // Verify the new report option appears in the LHN - const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); - expect(optionRows.length).toBe(2); - - // Verify the text for both chats are bold indicating that nothing has not yet been read - let displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); - const firstReportOption = displayNameTexts[0]; - expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); - - const secondReportOption = displayNameTexts[1]; - expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(secondReportOption, ['props', 'children'])).toBe('B User'); - - // Tap the new report option and navigate back to the sidebar again via the back button - await navigateToSidebarOption(renderedApp, 0); - - // Verify that report we navigated to appears in a "read" state while the original unread report still shows as unread - displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); - expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + it('Shows a browser notification and bold text when a new message arrives for a chat that is read', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Simulate a new report arriving via Pusher along with reportActions and personalDetails for the other participant + const NEW_REPORT_ID = 2; + const NEW_REPORT_CREATED_MOMENT = moment(); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${NEW_REPORT_ID}`, { + reportID: NEW_REPORT_ID, + reportName: 'Chat Report', + maxSequenceNumber: 1, + lastReadSequenceNumber: 0, + lastMessageTimestamp: NEW_REPORT_CREATED_MOMENT.utc(), + lastMessageText: 'Comment 1', + participants: [USER_C_EMAIL], + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${NEW_REPORT_ID}`, { + 0: { + actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, + automatic: false, + sequenceNumber: 0, + timestamp: NEW_REPORT_CREATED_MOMENT.unix(), + reportActionID: NumberUtils.rand64(), + }, + 1: { + actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT, + actorEmail: USER_C_EMAIL, + person: [{type: 'TEXT', style: 'strong', text: 'User C'}], + sequenceNumber: 1, + timestamp: NEW_REPORT_CREATED_MOMENT.add(5, 'seconds').unix(), + message: [{type: 'COMMENT', html: 'Comment 1', text: 'Comment 1'}], + reportActionID: NumberUtils.rand64(), + }, + }); + Onyx.merge(ONYXKEYS.PERSONAL_DETAILS, { + [USER_C_EMAIL]: TestHelper.buildPersonalDetails(USER_C_EMAIL, USER_C_ACCOUNT_ID, 'C'), + }); + return waitForPromisesToResolve(); + }) + .then(() => { + // Verify notification was created as the new message that has arrived is very recent + expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); + + // // Navigate back to the sidebar + return navigateToSidebar(renderedApp); + }) + .then(() => { + // // Verify the new report option appears in the LHN + const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); + expect(optionRows.length).toBe(2); + + // Verify the text for both chats are bold indicating that nothing has not yet been read + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(2); + const firstReportOption = displayNameTexts[0]; + expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); + + const secondReportOption = displayNameTexts[1]; + expect(lodashGet(secondReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(secondReportOption, ['props', 'children'])).toBe('B User'); + + // Tap the new report option and navigate back to the sidebar again via the back button + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + // Verify that report we navigated to appears in a "read" state while the original unread report still shows as unread + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(2); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); + expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(displayNameTexts[1], ['props', 'children'])).toBe('B User'); + }); }); - it('Manually marking a chat message as read shows the new line indicator and updates the LHN', async () => { - const renderedApp = await signInAndGetAppWithUnreadChat(); - - // Navigate to the unread report - await navigateToSidebarOption(renderedApp, 0); - - // It's difficult to trigger marking a report comment as unread since we would have to mock the long press event and then - // another press on the context menu item so we will do it via the action directly and then test if the UI has updated properly - Report.markCommentAsUnread(REPORT_ID, 3); - await waitForPromisesToResolve(); - - // Verify the indicator appears above the last action - let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); - const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); - expect(sequenceNumber).toBe(3); - - // Scroll up and verify the new messages badge appears - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); - - // Navigate to the sidebar - await navigateToSidebar(renderedApp); - - // Verify the report is marked as unread in the sidebar - let displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); - - // Navigate to the report again and back to the sidebar - await navigateToSidebarOption(renderedApp, 0); - await navigateToSidebar(renderedApp); - - // Verify the report is now marked as read - displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); - - // Navigate to the report again and verify the new line indicator is missing - await navigateToSidebarOption(renderedApp, 0); - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); - - // Scroll up and verify the "New messages" badge is hidden - scrollUpToRevealNewMessagesBadge(renderedApp); - expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + it('Manually marking a chat message as read shows the new line indicator and updates the LHN', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Navigate to the unread report + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + // It's difficult to trigger marking a report comment as unread since we would have to mock the long press event and then + // another press on the context menu item so we will do it via the action directly and then test if the UI has updated properly + Report.markCommentAsUnread(REPORT_ID, 3); + return waitForPromisesToResolve(); + }) + .then(() => { + // Verify the indicator appears above the last action + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(1); + const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); + expect(sequenceNumber).toBe(3); + + // Scroll up and verify the new messages badge appears + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(true); + + // Navigate to the sidebar + return navigateToSidebar(renderedApp); + }) + .then(() => { + // Verify the report is marked as unread in the sidebar + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); + + // Navigate to the report again and back to the sidebar + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => navigateToSidebar(renderedApp)) + .then(() => { + // Verify the report is now marked as read + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); + + // Navigate to the report again and verify the new line indicator is missing + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(0); + + // Scroll up and verify the "New messages" badge is hidden + scrollUpToRevealNewMessagesBadge(renderedApp); + expect(isNewMessagesBadgeVisible(renderedApp)).toBe(false); + }); }); - it('Removes the new line indicator when a new message is created by the current user', async () => { - const renderedApp = await signInAndGetAppWithUnreadChat(); - - // Verify we are on the LHN and that the chat shows as unread in the LHN - expect(isDrawerOpen(renderedApp)).toBe(true); - - const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - - // Navigate to the report and verify the indicator is present - await navigateToSidebarOption(renderedApp, 0); - let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); - - // Leave a comment as the current user and verify the indicator is removed - Report.addComment(REPORT_ID, 'Current User Comment 1'); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + it('Removes the new line indicator when a new message is created by the current user', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Verify we are on the LHN and that the chat shows as unread in the LHN + expect(isDrawerOpen(renderedApp)).toBe(true); + + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + // Navigate to the report and verify the indicator is present + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(1); + + // Leave a comment as the current user and verify the indicator is removed + Report.addComment(REPORT_ID, 'Current User Comment 1'); + return waitForPromisesToResolve(); + }) + .then(() => { + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(0); + }); }); - it('Clears the new line indicator when the user moves the App to the background', async () => { - const renderedApp = await signInAndGetAppWithUnreadChat(); - - // Verify we are on the LHN and that the chat shows as unread in the LHN - expect(isDrawerOpen(renderedApp)).toBe(true); - - const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); - expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); - expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); - - // Navigate to the chat and verify the new line indicator is present - await navigateToSidebarOption(renderedApp, 0); - let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); - - // Then back to the LHN - then back to the chat again and verify the new line indicator has cleared - await navigateToSidebar(renderedApp); - await navigateToSidebarOption(renderedApp, 0); - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); - - // Mark a previous comment as unread and verify the unread action indicator returns - Report.markCommentAsUnread(REPORT_ID, 9); - await waitForPromisesToResolve(); - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); - - // Trigger the app going inactive and active again - AppState.emitCurrentTestState('background'); - AppState.emitCurrentTestState('active'); - - // Verify the new line is cleared - unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + it('Clears the new line indicator when the user moves the App to the background', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Verify we are on the LHN and that the chat shows as unread in the LHN + expect(isDrawerOpen(renderedApp)).toBe(true); + + const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); + expect(displayNameTexts.length).toBe(1); + expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); + expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); + + // Navigate to the chat and verify the new line indicator is present + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(1); + + // Then back to the LHN - then back to the chat again and verify the new line indicator has cleared + return navigateToSidebar(renderedApp); + }) + .then(() => navigateToSidebarOption(renderedApp, 0)) + .then(() => { + const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(0); + + // Mark a previous comment as unread and verify the unread action indicator returns + Report.markCommentAsUnread(REPORT_ID, 9); + return waitForPromisesToResolve(); + }) + .then(() => { + let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(1); + + // Trigger the app going inactive and active again + AppState.emitCurrentTestState('background'); + AppState.emitCurrentTestState('active'); + + // Verify the new line is cleared + unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); + expect(unreadIndicator.length).toBe(0); + }); }); }); diff --git a/tests/utils/waitForPromisesToResolveWithAct.js b/tests/utils/waitForPromisesToResolveWithAct.js new file mode 100644 index 000000000000..37d5ccb041ce --- /dev/null +++ b/tests/utils/waitForPromisesToResolveWithAct.js @@ -0,0 +1,21 @@ +import {act} from '@testing-library/react-native'; +import waitForPromisesToResolve from './waitForPromisesToResolve'; + +/** + * This method is necessary because react-navigation's NavigationContainer makes an internal state update when parsing the + * linkingConfig to get the initialState. This throws some warnings related to async code if we do not wrap this call in an act(). + * + * See: https://callstack.github.io/react-native-testing-library/docs/understanding-act/#asynchronous-act + * + * This apparently will not work unless we use async/await because of some kind of voodoo magic inside the react-test-renderer + * so we are suppressing our lint rule and avoiding async/await everywhere else in our tests. + * + * @returns {Promise} + */ +// eslint-disable-next-line @lwc/lwc/no-async-await +export default async function waitForPromisesToResolveWithAct() { + // eslint-disable-next-line @lwc/lwc/no-async-await + await act(async () => { + await waitForPromisesToResolve(); + }); +} From c350685dfb652e51827207874a9e7175265ffe83 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 14:02:27 -0400 Subject: [PATCH 10/17] Cleanup Expensicons mock --- jest/setup.js | 93 +++------------------------------------------------ 1 file changed, 5 insertions(+), 88 deletions(-) diff --git a/jest/setup.js b/jest/setup.js index 5c84427e5205..9a0f864ab4b6 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -58,91 +58,8 @@ mockImages('images'); mockImages('images/avatars'); mockImages('images/bankicons'); mockImages('images/product-illustrations'); -jest.mock('../src/components/Icon/Expensicons', () => ({ - ActiveRoomAvatar: () => '', - AdminRoomAvatar: () => '', - Android: () => '', - AnnounceRoomAvatar: () => '', - Apple: () => '', - ArrowRight: () => '', - BackArrow: () => '', - Bank: () => '', - Bill: () => '', - Bolt: () => '', - Briefcase: () => '', - Bug: () => '', - Building: () => '', - Camera: () => '', - Cash: () => '', - ChatBubble: () => '', - Checkmark: () => '', - CircleHourglass: () => '', - Clipboard: () => '', - Close: () => '', - ClosedSign: () => '', - Collapse: () => '', - Concierge: () => '', - Connect: () => '', - CreditCard: () => '', - DeletedRoomAvatar: () => '', - DomainRoomAvatar: () => '', - DotIndicator: () => '', - DownArrow: () => '', - Download: () => '', - Emoji: () => '', - Exclamation: () => '', - Exit: () => '', - ExpensifyCard: () => '', - Expand: () => '', - Eye: () => '', - EyeDisabled: () => '', - FallbackAvatar: () => '', - FallbackWorkspaceAvatar: () => '', - Gallery: () => '', - Gear: () => '', - Hashtag: () => '', - ImageCropMask: () => '', - Info: () => '', - Invoice: () => '', - Key: () => '', - Keyboard: () => '', - Link: () => '', - LinkCopy: () => '', - Lock: () => '', - Luggage: () => '', - MagnifyingGlass: () => '', - Mail: () => '', - MoneyBag: () => '', - MoneyCircle: () => '', - Monitor: () => '', - NewWindow: () => '', - NewWorkspace: () => '', - Offline: () => '', - OfflineCloud: () => '', - Paperclip: () => '', - PayPal: () => '', - Paycheck: () => '', - Pencil: () => '', - Phone: () => '', - Pin: () => '', - PinCircle: () => '', - Plus: () => '', - Printer: () => '', - Profile: () => '', - QuestionMark: () => '', - Receipt: () => '', - ReceiptSearch: () => '', - Rotate: () => '', - RotateLeft: () => '', - Send: () => '', - Sync: () => '', - ThreeDots: () => '', - Transfer: () => '', - Trashcan: () => '', - UpArrow: () => '', - Upload: () => '', - Users: () => '', - Wallet: () => '', - Workspace: () => '', - Zoom: () => '', -})); +jest.mock('../src/components/Icon/Expensicons', () => { + const reduce = require('underscore').reduce; + const Expensicons = jest.requireActual('../src/components/Icon/Expensicons'); + return reduce(Expensicons, (prev, _curr, key) => ({...prev, [key]: () => ''}), {}); +}); From f51ed16f150e23fc80a48e40bc59bf7870e03af3 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 14:06:49 -0400 Subject: [PATCH 11/17] Clean up function names --- __mocks__/react-native.js | 6 ++---- src/libs/ReportActionsUtils.js | 4 ++-- src/libs/actions/Report.js | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/__mocks__/react-native.js b/__mocks__/react-native.js index 3e407252dc78..e2630c1ef632 100644 --- a/__mocks__/react-native.js +++ b/__mocks__/react-native.js @@ -1,13 +1,10 @@ -/* eslint-disable arrow-body-style */ // eslint-disable-next-line no-restricted-imports import * as ReactNative from 'react-native'; import _ from 'underscore'; jest.doMock('react-native', () => { let url = 'https://new.expensify.com/'; - const getInitialURL = () => { - return Promise.resolve(url); - }; + const getInitialURL = () => Promise.resolve(url); let appState = 'active'; let count = 0; @@ -57,6 +54,7 @@ jest.doMock('react-native', () => { ...ReactNative.Dimensions, addEventListener: jest.fn(), get: () => ({ + // Tests will run with the app in a typical small screen size width: 300, height: 700, scale: 1, fontScale: 1, }), }, diff --git a/src/libs/ReportActionsUtils.js b/src/libs/ReportActionsUtils.js index 157891dd8aaa..1b49c722e642 100644 --- a/src/libs/ReportActionsUtils.js +++ b/src/libs/ReportActionsUtils.js @@ -126,7 +126,7 @@ function getLastVisibleMessageText(reportID, actionsToMerge = {}) { * @param {Number} lastReadSequenceNumber * @return {String} */ -function getNewLastReadSequenceNumberForDeletedAction(reportID, actionsToMerge = {}, deletedSequenceNumber, lastReadSequenceNumber) { +function getOptimisticLastReadSequenceNumberForDeletedAction(reportID, actionsToMerge = {}, deletedSequenceNumber, lastReadSequenceNumber) { // If the action we are deleting is unread then just return the current last read sequence number if (deletedSequenceNumber > lastReadSequenceNumber) { return lastReadSequenceNumber; @@ -148,7 +148,7 @@ function getNewLastReadSequenceNumberForDeletedAction(reportID, actionsToMerge = } export { - getNewLastReadSequenceNumberForDeletedAction, + getOptimisticLastReadSequenceNumberForDeletedAction, getLastVisibleMessageText, getSortedReportActions, getMostRecentIOUReportSequenceNumber, diff --git a/src/libs/actions/Report.js b/src/libs/actions/Report.js index 9d977290278d..4897d56ed02f 100644 --- a/src/libs/actions/Report.js +++ b/src/libs/actions/Report.js @@ -1186,7 +1186,7 @@ function deleteReportComment(reportID, reportAction) { // If we are deleting the last visible message, let's find the previous visible one and update the lastMessageText in the LHN. // Similarly, we are deleting the last read comment will want to update the lastReadSequenceNumber to use the previous visible message. const lastMessageText = ReportActionsUtils.getLastVisibleMessageText(reportID, optimisticReportActions); - const lastReadSequenceNumber = ReportActionsUtils.getNewLastReadSequenceNumberForDeletedAction( + const lastReadSequenceNumber = ReportActionsUtils.getOptimisticLastReadSequenceNumberForDeletedAction( reportID, optimisticReportActions, reportAction.sequenceNumber, From ff196b198e5567b4e65102e80f1b0ebe2df5304b Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 23:48:25 -0400 Subject: [PATCH 12/17] Add test for deleting comment --- src/components/OptionRow.js | 1 + src/components/OptionsList/BaseOptionsList.js | 1 + src/pages/home/sidebar/SidebarLinks.js | 1 + tests/ui/UnreadIndicatorsTest.js | 54 +++++++++++++++++++ tests/utils/TestHelper.js | 2 +- 5 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/components/OptionRow.js b/src/components/OptionRow.js index e408387b1a3f..6ac45e98709d 100644 --- a/src/components/OptionRow.js +++ b/src/components/OptionRow.js @@ -196,6 +196,7 @@ const OptionRow = (props) => { /> {props.option.alternateText ? ( diff --git a/src/components/OptionsList/BaseOptionsList.js b/src/components/OptionsList/BaseOptionsList.js index c9f983a9720f..c8337b87acab 100644 --- a/src/components/OptionsList/BaseOptionsList.js +++ b/src/components/OptionsList/BaseOptionsList.js @@ -166,6 +166,7 @@ class BaseOptionsList extends Component { renderItem({item, index, section}) { return ( { // In this test, we are generically mocking the responses of all API requests by mocking fetch() and having it @@ -464,4 +465,57 @@ describe('Unread Indicators', () => { expect(unreadIndicator.length).toBe(0); }); }); + + it('Displays the correct chat message preview in the LHN when a comment is added then deleted', () => { + let reportActions; + let lastReportAction; + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, + callback: val => reportActions = val, + }); + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Navigate to the chat and simulate leaving a comment from the current user + return navigateToSidebarOption(renderedApp, 0); + }) + .then(() => { + // Leave a comment as the current user + Report.addComment(REPORT_ID, 'Current User Comment 1'); + return waitForPromisesToResolve(); + }) + .then(() => { + // Simulate the response from the server so that the comment can be deleted in this test + lastReportAction = {...CollectionUtils.lastItem(reportActions)}; + delete lastReportAction[lastReportAction.clientID]; + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + lastMessageText: lastReportAction.message[0].text, + lastMessageTimestamp: lastReportAction.timestamp, + lastActorEmail: lastReportAction.actorEmail, + maxSequenceNumber: lastReportAction.sequenceNumber, + reportID: REPORT_ID, + }); + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, { + [lastReportAction.clientID]: null, + 10: lastReportAction, + }); + return waitForPromisesToResolve(); + }) + .then(() => { + // Verify the chat preview text matches the last comment from the current user + const alternateText = renderedApp.queryAllByA11yLabel('Last chat message preview'); + expect(alternateText.length).toBe(1); + expect(alternateText[0].props.children).toBe('Current User Comment 1'); + + Report.deleteReportComment(REPORT_ID, lastReportAction); + return waitForPromisesToResolve(); + }) + .then(() => { + const alternateText = renderedApp.queryAllByA11yLabel('Last chat message preview'); + expect(alternateText.length).toBe(1); + expect(alternateText[0].props.children).toBe('Comment 9'); + }); + }); }); diff --git a/tests/utils/TestHelper.js b/tests/utils/TestHelper.js index eea6ae43461f..032f97fe2b1e 100644 --- a/tests/utils/TestHelper.js +++ b/tests/utils/TestHelper.js @@ -137,7 +137,7 @@ function buildTestReportComment(actorEmail, sequenceNumber, timestamp) { person: [{type: 'TEXT', style: 'strong', text: 'User B'}], sequenceNumber, timestamp, - message: [{type: 'COMMENT', html: 'Comment 1', text: `Comment ${sequenceNumber}`}], + message: [{type: 'COMMENT', html: `Comment ${sequenceNumber}`, text: `Comment ${sequenceNumber}`}], reportActionID: NumberUtils.rand64(), }; } From 7b76284a011aa08a4ad24aab7b867eaed725b395 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 18:34:02 -1000 Subject: [PATCH 13/17] improve a couple of comments and fix some incorrect changes --- jest/setup.js | 2 +- src/libs/actions/Report.js | 4 ++-- src/pages/home/HeaderView.js | 2 +- src/pages/home/report/FloatingMessageCounter/index.js | 5 ++++- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/jest/setup.js b/jest/setup.js index 9a0f864ab4b6..9016683290d1 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -50,7 +50,7 @@ function mockImages(imagePath) { }); } -// We are mock all images so that Icons and other assets cannot break tests. In the testing environment, importing things like .svg +// We are mocking all images so that Icons and other assets cannot break tests. In the testing environment, importing things like .svg // directly will lead to undefined variables instead of a component or string (which is what React expects). Loading these assets is // not required as the test environment does not actually render any UI anywhere and just needs them to noop so the test renderer // (which is a virtual implemented DOM) can do it's thing. diff --git a/src/libs/actions/Report.js b/src/libs/actions/Report.js index 4897d56ed02f..82a23a115fd0 100644 --- a/src/libs/actions/Report.js +++ b/src/libs/actions/Report.js @@ -11,6 +11,7 @@ import PushNotification from '../Notification/PushNotification'; import * as PersonalDetails from './PersonalDetails'; import Navigation from '../Navigation/Navigation'; import * as ActiveClientManager from '../ActiveClientManager'; +import Visibility from '../Visibility'; import ROUTES from '../../ROUTES'; import Timing from './Timing'; import * as DeprecatedAPI from '../deprecatedAPI'; @@ -25,7 +26,6 @@ import * as Localize from '../Localize'; import DateUtils from '../DateUtils'; import * as ReportActionsUtils from '../ReportActionsUtils'; import * as NumberUtils from '../NumberUtils'; -import Visibility from '../Visibility'; let currentUserEmail; let currentUserAccountID; @@ -805,7 +805,7 @@ function addActions(reportID, text = '', file) { const actionCount = text && file ? 2 : 1; const newSequenceNumber = highestSequenceNumber + actionCount; - // We guess at what these sequenceNumbers are to enable marking as unread while offline + // We're giving our best guess at what these sequenceNumbers are to enable marking as unread while offline. if (text && file) { reportCommentAction.sequenceNumber = highestSequenceNumber + 1; attachmentAction.sequenceNumber = highestSequenceNumber + 2; diff --git a/src/pages/home/HeaderView.js b/src/pages/home/HeaderView.js index 69a8b524c263..967523fe235a 100644 --- a/src/pages/home/HeaderView.js +++ b/src/pages/home/HeaderView.js @@ -93,7 +93,7 @@ const HeaderView = (props) => { {props.isSmallScreenWidth && ( - + + Date: Thu, 15 Sep 2022 19:43:40 -1000 Subject: [PATCH 14/17] Must mock useDrawerStatus in LHNOrderTest --- tests/unit/LHNOrderTest.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/unit/LHNOrderTest.js b/tests/unit/LHNOrderTest.js index 68944b326a9d..5fbc395b6f93 100644 --- a/tests/unit/LHNOrderTest.js +++ b/tests/unit/LHNOrderTest.js @@ -198,6 +198,16 @@ function getDefaultRenderedSidebarLinks() { )); } +jest.mock('@react-navigation/drawer', () => { + const drawer = jest.requireActual('@react-navigation/drawer'); + return { + ...drawer, + useDrawerStatus() { + return 'open'; + }, + }; +}); + describe('Sidebar', () => { describe('in default mode', () => { // Clear out Onyx after each test so that each test starts with a clean slate From b6d9615d0d25d26addef67ab6a89c709d3c2c117 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 19:58:59 -1000 Subject: [PATCH 15/17] Fix icons and withDrawerState for LHNOrderTest --- jest/setup.js | 9 ++++++++- src/pages/home/sidebar/SidebarLinks.js | 2 -- .../home/sidebar/SidebarScreen/BaseSidebarScreen.js | 4 +++- tests/unit/LHNOrderTest.js | 10 ---------- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/jest/setup.js b/jest/setup.js index 9016683290d1..07609b943522 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -61,5 +61,12 @@ mockImages('images/product-illustrations'); jest.mock('../src/components/Icon/Expensicons', () => { const reduce = require('underscore').reduce; const Expensicons = jest.requireActual('../src/components/Icon/Expensicons'); - return reduce(Expensicons, (prev, _curr, key) => ({...prev, [key]: () => ''}), {}); + return reduce(Expensicons, (prev, _curr, key) => { + const fn = () => ''; + Object.defineProperty(fn, 'name', { + value: key, + configurable: true, + }); + return {...prev, [key]: fn}; + }, {}); }); diff --git a/src/pages/home/sidebar/SidebarLinks.js b/src/pages/home/sidebar/SidebarLinks.js index 563f4ea8ca7c..98ef2aa5f97d 100644 --- a/src/pages/home/sidebar/SidebarLinks.js +++ b/src/pages/home/sidebar/SidebarLinks.js @@ -25,7 +25,6 @@ import withLocalize, {withLocalizePropTypes} from '../../../components/withLocal import * as App from '../../../libs/actions/App'; import * as ReportUtils from '../../../libs/ReportUtils'; import withCurrentUserPersonalDetails from '../../../components/withCurrentUserPersonalDetails'; -import withDrawerState from '../../../components/withDrawerState'; import withWindowDimensions from '../../../components/withWindowDimensions'; import Timing from '../../../libs/actions/Timing'; import reportActionPropTypes from '../report/reportActionPropTypes'; @@ -222,7 +221,6 @@ SidebarLinks.defaultProps = defaultProps; export default compose( withLocalize, withCurrentUserPersonalDetails, - withDrawerState, withWindowDimensions, withOnyx({ reports: { diff --git a/src/pages/home/sidebar/SidebarScreen/BaseSidebarScreen.js b/src/pages/home/sidebar/SidebarScreen/BaseSidebarScreen.js index 42eac4ea43c2..ff3b97c3f778 100644 --- a/src/pages/home/sidebar/SidebarScreen/BaseSidebarScreen.js +++ b/src/pages/home/sidebar/SidebarScreen/BaseSidebarScreen.js @@ -18,6 +18,7 @@ import * as Policy from '../../../../libs/actions/Policy'; import Performance from '../../../../libs/Performance'; import * as Welcome from '../../../../libs/actions/Welcome'; import {sidebarPropTypes, sidebarDefaultProps} from './sidebarPropTypes'; +import withDrawerState from '../../../../components/withDrawerState'; const propTypes = { @@ -110,6 +111,7 @@ class BaseSidebarScreen extends Component { insets={insets} onAvatarClick={this.navigateToSettings} isSmallScreenWidth={this.props.isSmallScreenWidth} + isDrawerOpen={this.props.isDrawerOpen} /> { - const drawer = jest.requireActual('@react-navigation/drawer'); - return { - ...drawer, - useDrawerStatus() { - return 'open'; - }, - }; -}); - describe('Sidebar', () => { describe('in default mode', () => { // Clear out Onyx after each test so that each test starts with a clean slate From b3ab1ba3c7c0a99d9604f1df0562f7684f468222 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Thu, 15 Sep 2022 20:03:49 -1000 Subject: [PATCH 16/17] improve comment and add explanation for icon name setting --- jest/setup.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/jest/setup.js b/jest/setup.js index 07609b943522..722e67007f13 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -62,11 +62,10 @@ jest.mock('../src/components/Icon/Expensicons', () => { const reduce = require('underscore').reduce; const Expensicons = jest.requireActual('../src/components/Icon/Expensicons'); return reduce(Expensicons, (prev, _curr, key) => { + // We set the name of the anonymous mock function here so we can dynamically build the list of mocks and access the + // "name" property to use in accessibility hints for element querying const fn = () => ''; - Object.defineProperty(fn, 'name', { - value: key, - configurable: true, - }); + Object.defineProperty(fn, 'name', {value: key}); return {...prev, [key]: fn}; }, {}); }); From 6b8536a5eea2a474e880dc0f99258cc8bd22db08 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Fri, 16 Sep 2022 10:38:37 -1000 Subject: [PATCH 17/17] Make some requested changes and improve comments further --- .../@react-native-firebase/crashlytics.js | 7 +- __mocks__/react-native.js | 16 +++-- jest/setup.js | 7 -- src/CONST.js | 7 ++ src/libs/ReportActionsUtils.js | 2 +- tests/ui/UnreadIndicatorsTest.js | 72 +++++++++---------- .../utils/waitForPromisesToResolveWithAct.js | 12 ++++ 7 files changed, 73 insertions(+), 50 deletions(-) diff --git a/__mocks__/@react-native-firebase/crashlytics.js b/__mocks__/@react-native-firebase/crashlytics.js index ff8b4c56321a..0cd842b4765d 100644 --- a/__mocks__/@react-native-firebase/crashlytics.js +++ b/__mocks__/@react-native-firebase/crashlytics.js @@ -1 +1,6 @@ -export default {}; +// uses and we need to mock the imported crashlytics module +// due to an error that happens otherwise https://github.com/invertase/react-native-firebase/issues/2475 +export default { + log: jest.fn(), + recordError: jest.fn(), +}; diff --git a/__mocks__/react-native.js b/__mocks__/react-native.js index e2630c1ef632..495745fa8c66 100644 --- a/__mocks__/react-native.js +++ b/__mocks__/react-native.js @@ -1,6 +1,7 @@ // eslint-disable-next-line no-restricted-imports import * as ReactNative from 'react-native'; import _ from 'underscore'; +import CONST from '../src/CONST'; jest.doMock('react-native', () => { let url = 'https://new.expensify.com/'; @@ -9,6 +10,13 @@ jest.doMock('react-native', () => { let appState = 'active'; let count = 0; const changeListeners = {}; + + // Tests will run with the app in a typical small screen size by default. We do this since the react-native test renderer + // runs against index.native.js source and so anything that is testing a component reliant on withWindowDimensions() + // would be most commonly assumed to be on a mobile phone vs. a tablet or desktop style view. This behavior can be + // overridden by explicitly setting the dimensions inside a test via Dimensions.set() + let dimensions = CONST.TESTING.SCREEN_SIZE.SMALL; + return Object.setPrototypeOf( { NativeModules: { @@ -53,10 +61,10 @@ jest.doMock('react-native', () => { Dimensions: { ...ReactNative.Dimensions, addEventListener: jest.fn(), - get: () => ({ - // Tests will run with the app in a typical small screen size - width: 300, height: 700, scale: 1, fontScale: 1, - }), + get: () => dimensions, + set: (newDimensions) => { + dimensions = newDimensions; + }, }, }, ReactNative, diff --git a/jest/setup.js b/jest/setup.js index 722e67007f13..d62bf1e6468e 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -16,13 +16,6 @@ jest.mock('react-native-reanimated', () => { return Reanimated; }); -// uses and we need to mock the imported crashlytics module -// due to an error that happens otherwise https://github.com/invertase/react-native-firebase/issues/2475 -jest.mock('@react-native-firebase/crashlytics', () => () => ({ - log: jest.fn(), - recordError: jest.fn(), -})); - // The main app uses a NativeModule called BootSplash to show/hide a splash screen. Since we can't use this in the node environment // where tests run we simulate a behavior where the splash screen is always hidden (similar to web which has no splash screen at all). jest.mock('../src/libs/BootSplash', () => ({ diff --git a/src/CONST.js b/src/CONST.js index bc443e5e3fba..c5f954527670 100755 --- a/src/CONST.js +++ b/src/CONST.js @@ -827,6 +827,13 @@ const CONST = { INCORRECT_PASSWORD: 2, }, }, + TESTING: { + SCREEN_SIZE: { + SMALL: { + width: 300, height: 700, scale: 1, fontScale: 1, + }, + }, + }, }; export default CONST; diff --git a/src/libs/ReportActionsUtils.js b/src/libs/ReportActionsUtils.js index 1b49c722e642..86fbbfca799d 100644 --- a/src/libs/ReportActionsUtils.js +++ b/src/libs/ReportActionsUtils.js @@ -124,7 +124,7 @@ function getLastVisibleMessageText(reportID, actionsToMerge = {}) { * @param {Object} [actionsToMerge] * @param {Number} deletedSequenceNumber * @param {Number} lastReadSequenceNumber - * @return {String} + * @return {Number} */ function getOptimisticLastReadSequenceNumberForDeletedAction(reportID, actionsToMerge = {}, deletedSequenceNumber, lastReadSequenceNumber) { // If the action we are deleting is unread then just return the current last read sequence number diff --git a/tests/ui/UnreadIndicatorsTest.js b/tests/ui/UnreadIndicatorsTest.js index 93630d4f661d..10adbab78db5 100644 --- a/tests/ui/UnreadIndicatorsTest.js +++ b/tests/ui/UnreadIndicatorsTest.js @@ -25,8 +25,6 @@ beforeAll(() => { // behavior. But here we just want to treat all API requests as a generic "success" and in the cases where we need to // simulate data arriving we will just set it into Onyx directly with Onyx.merge() or Onyx.set() etc. global.fetch = TestHelper.getGlobalFetchMock(); - - // We need a bit more time for this test in some places Linking.setInitialURL('https://new.expensify.com/r/1'); appSetup(); }); @@ -35,7 +33,7 @@ beforeAll(() => { * @param {RenderAPI} renderedApp */ function scrollUpToRevealNewMessagesBadge(renderedApp) { - fireEvent.scroll(renderedApp.getByA11yLabel('List of chat messages'), { + fireEvent.scroll(renderedApp.queryByA11yLabel('List of chat messages'), { nativeEvent: { contentOffset: { y: 250, @@ -63,7 +61,7 @@ function scrollUpToRevealNewMessagesBadge(renderedApp) { * @return {Boolean} */ function isNewMessagesBadgeVisible(renderedApp) { - const badge = renderedApp.getByA11yHint('Scroll to newest messages'); + const badge = renderedApp.queryByA11yHint('Scroll to newest messages'); return badge.props.style.transform[0].translateY === 10; } @@ -72,7 +70,7 @@ function isNewMessagesBadgeVisible(renderedApp) { * @return {Promise} */ function navigateToSidebar(renderedApp) { - const reportHeaderBackButton = renderedApp.getByA11yHint('Navigate back to chats list'); + const reportHeaderBackButton = renderedApp.queryByA11yHint('Navigate back to chats list'); fireEvent(reportHeaderBackButton, 'press'); return waitForPromisesToResolve(); } @@ -83,7 +81,7 @@ function navigateToSidebar(renderedApp) { * @return {Promise} */ function navigateToSidebarOption(renderedApp, index) { - const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); + const optionRows = renderedApp.queryAllByA11yHint('Navigates to a chat'); fireEvent(optionRows[index], 'press'); return waitForPromisesToResolve(); } @@ -116,7 +114,7 @@ function signInAndGetAppWithUnreadChat() { return waitForPromisesToResolveWithAct() .then(() => { const loginForm = renderedApp.queryAllByA11yLabel('Login form'); - expect(loginForm.length).toBe(1); + expect(loginForm).toHaveLength(1); return TestHelper.signInWithTestUser(USER_A_ACCOUNT_ID, USER_A_EMAIL, undefined, undefined, 'A'); }) @@ -172,19 +170,19 @@ describe('Unread Indicators', () => { renderedApp = testInstance; // Verify no notifications are created for these older messages - expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(0); + expect(LocalNotification.showCommentNotification.mock.calls).toHaveLength(0); // Verify the sidebar links are rendered const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); - expect(sidebarLinks.length).toBe(1); + expect(sidebarLinks).toHaveLength(1); expect(isDrawerOpen(renderedApp)).toBe(true); // Verify there is only one option in the sidebar - const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); - expect(optionRows.length).toBe(1); + const optionRows = renderedApp.queryAllByA11yHint('Navigates to a chat'); + expect(optionRows).toHaveLength(1); // And that the text is bold - const displayNameText = renderedApp.getByA11yLabel('Chat user display names'); + const displayNameText = renderedApp.queryByA11yLabel('Chat user display names'); expect(lodashGet(displayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); return navigateToSidebarOption(renderedApp, 0); @@ -194,15 +192,15 @@ describe('Unread Indicators', () => { expect(isDrawerOpen(renderedApp)).toBe(false); // That the report actions are visible along with the created action - const createdAction = renderedApp.getByA11yLabel('Chat welcome message'); + const createdAction = renderedApp.queryByA11yLabel('Chat welcome message'); expect(createdAction).toBeTruthy(); - const reportComments = renderedApp.getAllByA11yLabel('Chat message'); - expect(reportComments.length).toBe(9); + const reportComments = renderedApp.queryAllByA11yLabel('Chat message'); + expect(reportComments).toHaveLength(9); // Since the last read sequenceNumber is 1 we should have an unread indicator above the next "unread" action which will // have a sequenceNumber of 2 const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); + expect(unreadIndicator).toHaveLength(1); const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); expect(sequenceNumber).toBe(2); @@ -232,7 +230,7 @@ describe('Unread Indicators', () => { expect(isDrawerOpen(renderedApp)).toBe(true); // Verify that the option row in the LHN is no longer bold (since OpenReport marked it as read) - const updatedDisplayNameText = renderedApp.getByA11yLabel('Chat user display names'); + const updatedDisplayNameText = renderedApp.queryByA11yLabel('Chat user display names'); expect(lodashGet(updatedDisplayNameText, ['props', 'style', 0, 'fontWeight'])).toBe(undefined); // Tap on the chat again @@ -241,7 +239,7 @@ describe('Unread Indicators', () => { .then(() => { // Verify the unread indicator is not present const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + expect(unreadIndicator).toHaveLength(0); expect(isDrawerOpen(renderedApp)).toBe(false); // Scroll and verify that the new messages badge is also hidden @@ -293,19 +291,19 @@ describe('Unread Indicators', () => { }) .then(() => { // Verify notification was created as the new message that has arrived is very recent - expect(LocalNotification.showCommentNotification.mock.calls.length).toBe(1); + expect(LocalNotification.showCommentNotification.mock.calls).toHaveLength(1); // // Navigate back to the sidebar return navigateToSidebar(renderedApp); }) .then(() => { // // Verify the new report option appears in the LHN - const optionRows = renderedApp.getAllByA11yHint('Navigates to a chat'); - expect(optionRows.length).toBe(2); + const optionRows = renderedApp.queryAllByA11yHint('Navigates to a chat'); + expect(optionRows).toHaveLength(2); // Verify the text for both chats are bold indicating that nothing has not yet been read const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); + expect(displayNameTexts).toHaveLength(2); const firstReportOption = displayNameTexts[0]; expect(lodashGet(firstReportOption, ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); expect(lodashGet(firstReportOption, ['props', 'children'])).toBe('C User'); @@ -320,7 +318,7 @@ describe('Unread Indicators', () => { .then(() => { // Verify that report we navigated to appears in a "read" state while the original unread report still shows as unread const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(2); + expect(displayNameTexts).toHaveLength(2); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('C User'); expect(lodashGet(displayNameTexts[1], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); @@ -346,7 +344,7 @@ describe('Unread Indicators', () => { .then(() => { // Verify the indicator appears above the last action const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); + expect(unreadIndicator).toHaveLength(1); const sequenceNumber = lodashGet(unreadIndicator, [0, 'props', 'data-sequence-number']); expect(sequenceNumber).toBe(3); @@ -360,7 +358,7 @@ describe('Unread Indicators', () => { .then(() => { // Verify the report is marked as unread in the sidebar const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); + expect(displayNameTexts).toHaveLength(1); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); @@ -371,7 +369,7 @@ describe('Unread Indicators', () => { .then(() => { // Verify the report is now marked as read const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); + expect(displayNameTexts).toHaveLength(1); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(undefined); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); @@ -380,7 +378,7 @@ describe('Unread Indicators', () => { }) .then(() => { const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + expect(unreadIndicator).toHaveLength(0); // Scroll up and verify the "New messages" badge is hidden scrollUpToRevealNewMessagesBadge(renderedApp); @@ -398,7 +396,7 @@ describe('Unread Indicators', () => { expect(isDrawerOpen(renderedApp)).toBe(true); const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); + expect(displayNameTexts).toHaveLength(1); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); @@ -407,7 +405,7 @@ describe('Unread Indicators', () => { }) .then(() => { const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); + expect(unreadIndicator).toHaveLength(1); // Leave a comment as the current user and verify the indicator is removed Report.addComment(REPORT_ID, 'Current User Comment 1'); @@ -415,7 +413,7 @@ describe('Unread Indicators', () => { }) .then(() => { const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + expect(unreadIndicator).toHaveLength(0); }); }); @@ -429,7 +427,7 @@ describe('Unread Indicators', () => { expect(isDrawerOpen(renderedApp)).toBe(true); const displayNameTexts = renderedApp.queryAllByA11yLabel('Chat user display names'); - expect(displayNameTexts.length).toBe(1); + expect(displayNameTexts).toHaveLength(1); expect(lodashGet(displayNameTexts[0], ['props', 'children'])).toBe('B User'); expect(lodashGet(displayNameTexts[0], ['props', 'style', 0, 'fontWeight'])).toBe(fontWeightBold); @@ -438,7 +436,7 @@ describe('Unread Indicators', () => { }) .then(() => { const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); + expect(unreadIndicator).toHaveLength(1); // Then back to the LHN - then back to the chat again and verify the new line indicator has cleared return navigateToSidebar(renderedApp); @@ -446,7 +444,7 @@ describe('Unread Indicators', () => { .then(() => navigateToSidebarOption(renderedApp, 0)) .then(() => { const unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + expect(unreadIndicator).toHaveLength(0); // Mark a previous comment as unread and verify the unread action indicator returns Report.markCommentAsUnread(REPORT_ID, 9); @@ -454,7 +452,7 @@ describe('Unread Indicators', () => { }) .then(() => { let unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(1); + expect(unreadIndicator).toHaveLength(1); // Trigger the app going inactive and active again AppState.emitCurrentTestState('background'); @@ -462,7 +460,7 @@ describe('Unread Indicators', () => { // Verify the new line is cleared unreadIndicator = renderedApp.queryAllByA11yLabel('New message line indicator'); - expect(unreadIndicator.length).toBe(0); + expect(unreadIndicator).toHaveLength(0); }); }); @@ -506,7 +504,7 @@ describe('Unread Indicators', () => { .then(() => { // Verify the chat preview text matches the last comment from the current user const alternateText = renderedApp.queryAllByA11yLabel('Last chat message preview'); - expect(alternateText.length).toBe(1); + expect(alternateText).toHaveLength(1); expect(alternateText[0].props.children).toBe('Current User Comment 1'); Report.deleteReportComment(REPORT_ID, lastReportAction); @@ -514,7 +512,7 @@ describe('Unread Indicators', () => { }) .then(() => { const alternateText = renderedApp.queryAllByA11yLabel('Last chat message preview'); - expect(alternateText.length).toBe(1); + expect(alternateText).toHaveLength(1); expect(alternateText[0].props.children).toBe('Comment 9'); }); }); diff --git a/tests/utils/waitForPromisesToResolveWithAct.js b/tests/utils/waitForPromisesToResolveWithAct.js index 37d5ccb041ce..eaef0f3b1a9d 100644 --- a/tests/utils/waitForPromisesToResolveWithAct.js +++ b/tests/utils/waitForPromisesToResolveWithAct.js @@ -10,6 +10,18 @@ import waitForPromisesToResolve from './waitForPromisesToResolve'; * This apparently will not work unless we use async/await because of some kind of voodoo magic inside the react-test-renderer * so we are suppressing our lint rule and avoiding async/await everywhere else in our tests. * + * When to use this: + * + * - If you see the jest output complaining about needing to use act() AND the callback inside the act() returns a promise. We can't + * call .then() on act() and the test renderer wants us to use async/await so use this function instead. + * + * + * When not to use this: + * + * - You're not rendering any react components at all in your tests, but have some async logic you need to wait for e.g. Onyx.merge(). Use waitForPromisesToResolve(). + * - You're writing UI tests but don't see any errors or warnings related to using act(). You probably don't need this in that case and should use waitForPromisesToResolve(). + * - You're writing UI test and do see a warning about using act(), but there's no asynchronous code that needs to run inside act(). + * * @returns {Promise} */ // eslint-disable-next-line @lwc/lwc/no-async-await