diff --git a/__mocks__/@react-native-firebase/crashlytics.js b/__mocks__/@react-native-firebase/crashlytics.js new file mode 100644 index 000000000000..0cd842b4765d --- /dev/null +++ b/__mocks__/@react-native-firebase/crashlytics.js @@ -0,0 +1,6 @@ +// 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__/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..495745fa8c66 --- /dev/null +++ b/__mocks__/react-native.js @@ -0,0 +1,72 @@ +// 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/'; + const getInitialURL = () => Promise.resolve(url); + + 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: { + ...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: () => dimensions, + set: (newDimensions) => { + dimensions = newDimensions; + }, + }, + }, + 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..d62bf1e6468e 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -1,15 +1,64 @@ +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-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'); + Reanimated.default.call = () => {}; + return Reanimated; +}); -// 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: () => {}, +// 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'), })); -jest.mock('react-native-blob-util', () => ({})); +// 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(), +})); + +/** + * @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}`, () => () => ''); + } + }); +} + +// 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. +mockImages('images'); +mockImages('images/avatars'); +mockImages('images/bankicons'); +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) => { + // 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}); + return {...prev, [key]: fn}; + }, {}); +}); diff --git a/package.json b/package.json index fb1a983ae489..45e48d8c16ff 100644 --- a/package.json +++ b/package.json @@ -203,6 +203,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/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/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..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 cadae24e801e..6ac45e98709d 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..c8337b87acab 100644 --- a/src/components/OptionsList/BaseOptionsList.js +++ b/src/components/OptionsList/BaseOptionsList.js @@ -166,6 +166,8 @@ class BaseOptionsList extends Component { renderItem({item, index, section}) { return ( { diff --git a/src/components/UnreadActionIndicator.js b/src/components/UnreadActionIndicator.js index 389413e4f38e..9fe271226463 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..86fbbfca799d 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,59 @@ 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) + )); + if (lastMessageIndex < 0) { + return ''; + } + + const htmlText = lodashGet(sortedActions, [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 {Number} + */ +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; + } + + // 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 sortedActions[lastMessageIndex].sequenceNumber; +} + export { + getOptimisticLastReadSequenceNumberForDeletedAction, + getLastVisibleMessageText, getSortedReportActions, getMostRecentIOUReportSequenceNumber, isDeletedAction, diff --git a/src/libs/ReportUtils.js b/src/libs/ReportUtils.js index 375a4be558f5..ae8e3291420b 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..82a23a115fd0 100644 --- a/src/libs/actions/Report.js +++ b/src/libs/actions/Report.js @@ -21,7 +21,6 @@ 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'; @@ -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'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; + } 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.getOptimisticLastReadSequenceNumberForDeletedAction( + 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..967523fe235a 100644 --- a/src/pages/home/HeaderView.js +++ b/src/pages/home/HeaderView.js @@ -49,7 +49,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 +60,7 @@ const propTypes = { const defaultProps = { personalDetails: {}, + policies: {}, report: null, }; @@ -96,6 +97,7 @@ const HeaderView = (props) => { diff --git a/src/pages/home/ReportScreen.js b/src/pages/home/ReportScreen.js index 5728117b4c01..c533936615ab 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 = { @@ -249,6 +252,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) && ( @@ -284,6 +288,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..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 7025d5a67a4f..97287442ce29 100644 --- a/src/pages/home/report/FloatingMessageCounter/index.js +++ b/src/pages/home/report/FloatingMessageCounter/index.js @@ -62,7 +62,10 @@ 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..6ecd61ea974d 100644 --- a/src/pages/home/report/ReportActionsList.js +++ b/src/pages/home/report/ReportActionsList.js @@ -106,14 +106,15 @@ 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 + * @param {Object} item.action * @return {String} */ keyExtractor(item) { - return `${item.action.reportActionID}${item.action.sequenceNumber}`; + return `${item.action.clientID}${item.action.reportActionID}${item.action.sequenceNumber}`; } /** @@ -135,7 +136,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 +380,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 462d14e9f3ba..98ef2aa5f97d 100644 --- a/src/pages/home/sidebar/SidebarLinks.js +++ b/src/pages/home/sidebar/SidebarLinks.js @@ -25,6 +25,7 @@ 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 withWindowDimensions from '../../../components/withWindowDimensions'; import Timing from '../../../libs/actions/Timing'; import reportActionPropTypes from '../report/reportActionPropTypes'; @@ -144,7 +145,11 @@ class SidebarLinks extends React.Component { Timing.end(CONST.TIMING.SIDEBAR_LINKS_FILTER_REPORTS); 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..10adbab78db5 --- /dev/null +++ b/tests/ui/UnreadIndicatorsTest.js @@ -0,0 +1,519 @@ +import React from 'react'; +import Onyx from 'react-native-onyx'; +import {Linking, AppState} from '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'; +import * as AppActions from '../../src/libs/actions/App'; +import * as NumberUtils from '../../src/libs/NumberUtils'; +import LocalNotification from '../../src/libs/Notification/LocalNotification'; +import * as Report from '../../src/libs/actions/Report'; +import * as CollectionUtils from '../../src/libs/CollectionUtils'; + +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(); + Linking.setInitialURL('https://new.expensify.com/r/1'); + appSetup(); +}); + +/** + * @param {RenderAPI} renderedApp + */ +function scrollUpToRevealNewMessagesBadge(renderedApp) { + fireEvent.scroll(renderedApp.queryByA11yLabel('List of chat messages'), { + 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.queryByA11yHint('Scroll to newest messages'); + return badge.props.style.transform[0].translateY === 10; +} + +/** + * @param {RenderAPI} renderedApp + * @return {Promise} + */ +function navigateToSidebar(renderedApp) { + const reportHeaderBackButton = renderedApp.queryByA11yHint('Navigate back to chats list'); + fireEvent(reportHeaderBackButton, 'press'); + return waitForPromisesToResolve(); +} + +/** + * @param {RenderAPI} renderedApp + * @param {Number} index + * @return {Promise} + */ +function navigateToSidebarOption(renderedApp, index) { + const optionRows = renderedApp.queryAllByA11yHint('Navigates to a chat'); + fireEvent(optionRows[index], 'press'); + return waitForPromisesToResolve(); +} + +/** + * @param {RenderAPI} renderedApp + * @return {Boolean} + */ +function isDrawerOpen(renderedApp) { + const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); + return !lodashGet(sidebarLinks, [0, 'props', 'accessibilityElementsHidden']); +} + +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'; + +/** + * Sets up a test with a logged in user that has one unread chat from another user. Returns the test instance. + * + * @returns {RenderAPI} + */ +function signInAndGetAppWithUnreadChat() { + // Render the App and sign in as a test user. + const renderedApp = render(); + return waitForPromisesToResolveWithAct() + .then(() => { + const loginForm = renderedApp.queryAllByA11yLabel('Login form'); + expect(loginForm).toHaveLength(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', () => { + let renderedApp; + return signInAndGetAppWithUnreadChat() + .then((testInstance) => { + renderedApp = testInstance; + + // Verify no notifications are created for these older messages + expect(LocalNotification.showCommentNotification.mock.calls).toHaveLength(0); + + // Verify the sidebar links are rendered + const sidebarLinks = renderedApp.queryAllByA11yLabel('List of chats'); + expect(sidebarLinks).toHaveLength(1); + expect(isDrawerOpen(renderedApp)).toBe(true); + + // Verify there is only one option in the sidebar + const optionRows = renderedApp.queryAllByA11yHint('Navigates to a chat'); + expect(optionRows).toHaveLength(1); + + // And that the text is bold + const displayNameText = renderedApp.queryByA11yLabel('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.queryByA11yLabel('Chat welcome message'); + expect(createdAction).toBeTruthy(); + 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).toHaveLength(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', () => { + 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.queryByA11yLabel('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).toHaveLength(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', () => { + 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).toHaveLength(1); + + // // Navigate back to the sidebar + return navigateToSidebar(renderedApp); + }) + .then(() => { + // // Verify the new report option appears in the LHN + 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).toHaveLength(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).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); + 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', () => { + 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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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', () => { + 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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(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).toHaveLength(1); + expect(alternateText[0].props.children).toBe('Comment 9'); + }); + }); +}); diff --git a/tests/unit/LHNOrderTest.js b/tests/unit/LHNOrderTest.js index 3a0194f0f480..68944b326a9d 100644 --- a/tests/unit/LHNOrderTest.js +++ b/tests/unit/LHNOrderTest.js @@ -198,13 +198,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..032f97fe2b1e 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 {Object} + */ +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 ${sequenceNumber}`, text: `Comment ${sequenceNumber}`}], + reportActionID: NumberUtils.rand64(), + }; +} + export { getGlobalFetchMock, signInWithTestUser, setPersonalDetails, + buildPersonalDetails, + buildTestReportComment, }; diff --git a/tests/utils/waitForPromisesToResolveWithAct.js b/tests/utils/waitForPromisesToResolveWithAct.js new file mode 100644 index 000000000000..eaef0f3b1a9d --- /dev/null +++ b/tests/utils/waitForPromisesToResolveWithAct.js @@ -0,0 +1,33 @@ +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. + * + * 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 +export default async function waitForPromisesToResolveWithAct() { + // eslint-disable-next-line @lwc/lwc/no-async-await + await act(async () => { + await waitForPromisesToResolve(); + }); +}