level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
2,540
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/login/login_mfa.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import LoginMfa from 'components/login/login_mfa'; import SaveButton from 'components/save_button'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; describe('components/login/LoginMfa', () => { const baseProps = { loginId: 'login_id', password: 'password', onSubmit: jest.fn(), }; const token = '123456'; test('should match snapshot', () => { const wrapper = shallow( <LoginMfa {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should handle token entered', () => { const wrapper = mountWithIntl( <LoginMfa {...baseProps}/>, ); let input = wrapper.find('input').first(); expect(input.props().disabled).toEqual(false); let button = wrapper.find(SaveButton).first(); expect(button.props().disabled).toEqual(true); input.simulate('change', {target: {value: token}}); button = wrapper.find(SaveButton).first(); expect(button.props().disabled).toEqual(false); input = wrapper.find('input').first(); expect(input.props().value).toEqual(token); }); test('should handle submit', () => { const wrapper = mountWithIntl( <LoginMfa {...baseProps}/>, ); let input = wrapper.find('input').first(); input.simulate('change', {target: {value: token}}); wrapper.find(SaveButton).simulate('click'); const saveButton = wrapper.find(SaveButton).first().props(); expect(saveButton.disabled).toEqual(false); expect(saveButton.saving).toEqual(true); input = wrapper.find('input').first(); expect(input.props().disabled).toEqual(true); expect(baseProps.onSubmit).toHaveBeenCalledWith({loginId: baseProps.loginId, password: baseProps.password, token}); }); });
2,542
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/login
petrpan-code/mattermost/mattermost/webapp/channels/src/components/login/__snapshots__/login.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/login/Login should match snapshot 1`] = ` <div className="login-body" > <div className="login-body-content" > <Column message="Please contact your System Administrator to resolve this." title="This server doesn’t have any sign-in methods enabled" /> </div> </div> `; exports[`components/login/Login should match snapshot with base login 1`] = ` <div className="login-body" > <div className="login-body-content" > <div className="login-body-message" > <h1 className="login-body-message-title" > Log in to your account </h1> <p className="login-body-message-subtitle" > Collaborate with your team in real-time </p> <div className="login-body-message-svg" > <Svg width={270} /> </div> </div> <div className="login-body-action" > <AlternateLink alternateLinkLabel="Don't have an account?" alternateLinkPath="/access_problem" className="login-body-alternate-link" onClick={[Function]} /> <div className="login-body-card" > <div className="login-body-card-content" tabIndex={0} > <p className="login-body-card-title" > Log in </p> <form onSubmit={[Function]} > <div className="login-body-card-form" > <ForwardRef autoFocus={true} containerClassName="login-body-card-form-input" disabled={false} hasError={false} inputSize="large" name="loginId" onChange={[Function]} placeholder="Email" type="text" value="" /> <ForwardRef className="login-body-card-form-password-input" disabled={false} hasError={false} inputSize="large" onChange={[Function]} value="" /> <div className="login-body-card-form-link" > <Link to="/reset_password" > Forgot your password? </Link> </div> <SaveButton btnClass="" defaultMessage="Log in" disabled={false} extraClasses="login-body-card-form-button-submit large" onClick={[Function]} saving={false} savingMessage="Logging in…" /> </div> </form> </div> </div> </div> </div> </div> `;
2,543
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/login
petrpan-code/mattermost/mattermost/webapp/channels/src/components/login/__snapshots__/login_mfa.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/login/LoginMfa should match snapshot 1`] = ` <Column SVGElement={<Svg />} extraContent={ <div className="login-mfa-form" > <ForwardRef autoFocus={true} containerClassName="login-mfa-form-input" disabled={false} inputSize="large" name="token" onChange={[Function]} placeholder="Enter MFA Token" type="text" value="" /> <div className="login-mfa-form-button-container" > <SaveButton btnClass="" defaultMessage="Submit" disabled={true} extraClasses="login-mfa-form-button-submit large" onClick={[Function]} saving={false} savingMessage="Logging in…" /> </div> </div> } message="To complete the sign in process, please enter a token from your smartphone's authenticator" onEnterKeyDown={[Function]} title="Enter MFA Token" /> `;
2,548
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/main_menu/main_menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {createIntl} from 'react-intl'; import {Provider} from 'react-redux'; import {Permissions} from 'mattermost-redux/constants'; import Menu from 'components/widgets/menu/menu'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {Constants} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import {MainMenu} from './main_menu'; import type {Props} from './main_menu'; describe('components/Menu', () => { // Neccessary for components enhanced by HOCs due to issue with enzyme. // See https://github.com/enzymejs/enzyme/issues/539 const getMainMenuWrapper = (props: Props) => { return shallow(<MainMenu {...props}/>); // const wrapper = shallowWithIntl(<MainMenu {...props}/>); // return wrapper.find('MainMenu').shallow(); }; const defaultProps = { mobile: false, teamId: 'team-id', teamType: Constants.OPEN_TEAM, teamName: 'team_name', currentUser: TestHelper.getUserMock(), appDownloadLink: undefined, enableCommands: false, enableCustomEmoji: false, enableIncomingWebhooks: false, enableOAuthServiceProvider: false, enableOutgoingWebhooks: false, canManageSystemBots: false, canCreateOrDeleteCustomEmoji: false, canManageIntegrations: true, enableUserCreation: false, enableEmailInvitations: false, enablePluginMarketplace: false, experimentalPrimaryTeam: undefined, helpLink: undefined, reportAProblemLink: undefined, moreTeamsToJoin: false, pluginMenuItems: [], isMentionSearch: false, isFirstAdmin: false, intl: createIntl({locale: 'en', defaultLocale: 'en', timeZone: 'Etc/UTC', textComponent: 'span'}), teamUrl: '/team', location: { pathname: '/team', }, guestAccessEnabled: true, canInviteTeamMember: true, actions: { openModal: jest.fn(), showMentions: jest.fn(), showFlaggedPosts: jest.fn(), closeRightHandSide: jest.fn(), closeRhsMenu: jest.fn(), getCloudLimits: jest.fn(), }, teamIsGroupConstrained: false, isCloud: false, isStarterFree: false, subscription: {}, userIsAdmin: true, isFreeTrial: false, usageDeltaTeams: 1, }; const defaultState = { entities: { channels: { myMembers: [], }, general: { config: {}, license: { Cloud: 'false', }, }, teams: { currentTeamId: 'team-id', myMembers: { 'team-id': { team_id: 'team-id', user_id: 'test-user-id', roles: 'team_user', scheme_user: 'true', }, }, }, users: { currentUserId: 'test-user-id', profiles: { 'test-user-id': { id: 'test-user-id', roles: 'system_user system_manager', }, }, }, roles: { roles: { system_manager: { permissions: [ Permissions.SYSCONSOLE_WRITE_PLUGINS, ], }, }, }, }, }; test('should match snapshot with id', () => { const props = {...defaultProps, id: 'test-id'}; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with most of the thing disabled', () => { const wrapper = getMainMenuWrapper(defaultProps); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with most of the thing disabled in mobile', () => { const props = {...defaultProps, mobile: true}; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with most of the thing enabled', () => { const props = { ...defaultProps, appDownloadLink: 'test', enableCommands: true, enableCustomEmoji: true, canCreateOrDeleteCustomEmoji: true, enableIncomingWebhooks: true, enableOAuthServiceProvider: true, enableOutgoingWebhooks: true, enableUserCreation: true, enableEmailInvitations: true, enablePluginMarketplace: true, experimentalPrimaryTeam: 'test', helpLink: 'test-link-help', reportAProblemLink: 'test-report-link', moreTeamsToJoin: true, }; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with most of the thing enabled in mobile', () => { const props = { ...defaultProps, mobile: true, appDownloadLink: 'test', enableCommands: true, enableCustomEmoji: true, canCreateOrDeleteCustomEmoji: true, enableIncomingWebhooks: true, enableOAuthServiceProvider: true, enableOutgoingWebhooks: true, enableUserCreation: true, enableEmailInvitations: true, enablePluginMarketplace: true, experimentalPrimaryTeam: 'test', helpLink: 'test-link-help', reportAProblemLink: 'test-report-link', moreTeamsToJoin: true, }; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with plugins', () => { const props = { ...defaultProps, pluginMenuItems: [{ id: 'plugin-id-1', pluginId: 'plugin-1', mobileIcon: <i className='fa fa-anchor'/>, action: jest.fn, dropdownText: 'some dropdown text', tooltipText: 'some tooltip text', }, { id: 'plugind-id-2', pluginId: 'plugin-2', mobileIcon: <i className='fa fa-anchor'/>, action: jest.fn, dropdownText: 'some dropdown text', tooltipText: 'some tooltip text', }, ], }; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with plugins in mobile', () => { const props = { ...defaultProps, mobile: true, pluginMenuItems: [{ id: 'plugin-id-1', pluginId: 'plugin-1', icon: <i className='fa fa-anchor'/>, action: jest.fn, dropdownText: 'some dropdown text', tooltipText: 'some tooltip text', }, { id: 'plugind-id-2', pluginId: 'plugin-2', icon: <i className='fa fa-anchor'/>, action: jest.fn, dropdownText: 'some dropdown text', tooltipText: 'some tooltip text', }, ], }; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should show leave team option when primary team is not set', () => { const props = {...defaultProps, teamIsGroupConstrained: false, experimentalPrimaryTeam: undefined}; const wrapper = getMainMenuWrapper(props); // show leave team option when experimentalPrimaryTeam is not set expect(wrapper.find('#leaveTeam')).toHaveLength(1); expect(wrapper.find('#leaveTeam').find(Menu.ItemToggleModalRedux).props().show).toEqual(true); }); test('should hide leave team option when experimentalPrimaryTeam is same as current team', () => { const props = {...defaultProps, teamIsGroupConstrained: false}; const wrapper = getMainMenuWrapper(props); expect(wrapper.find('#leaveTeam')).toHaveLength(1); expect(wrapper.find('#leaveTeam').find(Menu.ItemToggleModalRedux).props().show).toEqual(true); }); test('should hide leave team option when experimentalPrimaryTeam is same as current team', () => { const props = {...defaultProps, teamIsGroupConstrained: false, experimentalPrimaryTeam: 'other-team'}; const wrapper = getMainMenuWrapper(props); expect(wrapper.find('#leaveTeam')).toHaveLength(1); expect(wrapper.find('#leaveTeam').find(Menu.ItemToggleModalRedux).props().show).toEqual(true); }); test('mobile view should hide the subscribe now button when does not have permissions', () => { const noPermissionsState = {...defaultState}; noPermissionsState.entities.roles.roles.system_manager.permissions = []; const store = mockStore(noPermissionsState); const wrapper = mountWithIntl( <Provider store={store}> <MainMenu {...defaultProps}/> </Provider>, ); expect(wrapper.find('UpgradeLink')).toHaveLength(0); }); test('mobile view should hide start trial menu item because user state does not have permission to write license', () => { const store = mockStore(defaultState); const wrapper = mountWithIntl( <Provider store={store}> <MainMenu {...defaultProps}/> </Provider>, ); expect(wrapper.find('#startTrial')).toHaveLength(0); }); test('should match snapshot with guest access disabled and no team invite permission', () => { const props = { ...defaultProps, guestAccessEnabled: false, canInviteTeamMember: false, }; const wrapper = getMainMenuWrapper(props); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with cloud free trial', () => { const props = { ...defaultProps, isCloud: true, isStarterFree: false, isFreeTrial: true, usageDeltaTeams: -1, }; const wrapper = getMainMenuWrapper(props); expect(wrapper.find('#createTeam')).toMatchSnapshot(); }); test('should match snapshot with cloud free and team limit reached', () => { const props = { ...defaultProps, isCloud: true, isStarterFree: true, isFreeTrial: false, usageDeltaTeams: 0, }; const wrapper = getMainMenuWrapper(props); expect(wrapper.find('#createTeam')).toMatchSnapshot(); }); });
2,550
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/main_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/main_menu/__snapshots__/main_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/Menu should match snapshot with cloud free and team limit reached 1`] = ` <MenuItemLink className="MenuItem__with-icon-tooltip" disabled={true} id="createTeam" show={true} sibling={ <RestrictedIndicator blocked={true} feature="mattermost.feature.create_multiple_teams" messageAdminPostTrial="Multiple teams allow for context-specific spaces that are more attuned to your and your teams’ needs. Upgrade to the Professional plan to create unlimited teams." messageAdminPreTrial="Create unlimited teams with one of our paid plans. Get the full experience of Enterprise when you start a free, 30 day trial." messageEndUser="Multiple teams allow for context-specific spaces that are more attuned to your teams’ needs." minimumPlanRequiredForFeature="professional" titleAdminPostTrial="Upgrade to create unlimited teams" titleAdminPreTrial="Try unlimited teams with a free trial" titleEndUser="Multiple teams available in paid plans" tooltipMessage="During your trial you are able to create multiple teams. These teams will be archived after your trial." /> } text="Create a Team" to="/create_team" /> `; exports[`components/Menu should match snapshot with cloud free trial 1`] = ` <MenuItemLink className="MenuItem__with-icon-tooltip" disabled={false} id="createTeam" show={true} sibling={ <RestrictedIndicator blocked={false} feature="mattermost.feature.create_multiple_teams" messageAdminPostTrial="Multiple teams allow for context-specific spaces that are more attuned to your and your teams’ needs. Upgrade to the Professional plan to create unlimited teams." messageAdminPreTrial="Create unlimited teams with one of our paid plans. Get the full experience of Enterprise when you start a free, 30 day trial." messageEndUser="Multiple teams allow for context-specific spaces that are more attuned to your teams’ needs." minimumPlanRequiredForFeature="professional" titleAdminPostTrial="Upgrade to create unlimited teams" titleAdminPreTrial="Try unlimited teams with a free trial" titleEndUser="Multiple teams available in paid plans" tooltipMessage="During your trial you are able to create multiple teams. These teams will be archived after your trial." /> } text="Create a Team" to="/create_team" /> `; exports[`components/Menu should match snapshot with guest access disabled and no team invite permission 1`] = ` <Menu ariaLabel="team menu" > <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" /> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> <MenuItemLink id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux className="destructive" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink className="" disabled={false} id="createTeam" show={true} sibling={false} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <Memo(MenuGroup)> <div className="MainMenu_dropdown-link" > <LearnAboutTeamsLink /> </div> </Memo(MenuGroup)> </Memo(MenuGroup)> <Memo(MenuGroup) /> </Menu> `; exports[`components/Menu should match snapshot with id 1`] = ` <Menu ariaLabel="team menu" id="test-id" > <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={false} id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> <MenuItemLink id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux className="destructive" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink className="" disabled={false} id="createTeam" show={true} sibling={false} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <Memo(MenuGroup)> <div className="MainMenu_dropdown-link" > <LearnAboutTeamsLink /> </div> </Memo(MenuGroup)> </Memo(MenuGroup)> <Memo(MenuGroup) /> </Menu> `; exports[`components/Menu should match snapshot with most of the thing disabled 1`] = ` <Menu ariaLabel="team menu" > <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={false} id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> <MenuItemLink id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux className="destructive" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink className="" disabled={false} id="createTeam" show={true} sibling={false} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <Memo(MenuGroup)> <div className="MainMenu_dropdown-link" > <LearnAboutTeamsLink /> </div> </Memo(MenuGroup)> </Memo(MenuGroup)> <Memo(MenuGroup) /> </Menu> `; exports[`components/Menu should match snapshot with most of the thing disabled in mobile 1`] = ` <Menu ariaLabel="main menu" > <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_billing", ] } > <MenuCloudTrial id="menuCloudTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_about_edition_and_license", ] } > <MenuStartTrial id="startTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="mentions" > @ </i> } id="recentMentions" onClick={[Function]} show={true} text="Recent Mentions" /> <MenuItemAction icon={ <i className="fa fa-bookmark" /> } id="flaggedPosts" onClick={[Function]} show={true} text="Saved messages" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user" /> } id="profileSettings" modalId="user_settings" show={true} text="Profile" /> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": true, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-cog" /> } id="accountSettings" modalId="user_settings" show={true} text="Settings" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={ <i className="fa fa-user-plus" /> } id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-globe" /> } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="createTeam" show={true} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={<LeaveTeamIcon />} id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup) /> <Memo(MenuGroup)> <MenuItemLink id="integrations" show={false} text="Integrations" to="/team_name/integrations" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemExternalLink icon={ <i className="fa fa-question" /> } id="helpLink" show={false} text="Help" /> <MenuItemExternalLink icon={ <i className="fa fa-phone" /> } id="reportLink" show={false} text="Report a Problem" /> <MenuItemExternalLink icon={ <i className="fa fa-mobile" /> } id="nativeAppLink" show={true} text="Download Apps" url="" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-info" /> } id="about" modalId="about" show={true} text="About Mattermost" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="fa fa-sign-out" /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> `; exports[`components/Menu should match snapshot with most of the thing enabled 1`] = ` <Menu ariaLabel="team menu" > <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={false} id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> <MenuItemLink id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux className="destructive" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink className="" disabled={false} id="createTeam" show={true} sibling={false} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <Memo(MenuGroup)> <div className="MainMenu_dropdown-link" > <LearnAboutTeamsLink /> </div> </Memo(MenuGroup)> </Memo(MenuGroup)> <Memo(MenuGroup) /> </Menu> `; exports[`components/Menu should match snapshot with most of the thing enabled in mobile 1`] = ` <Menu ariaLabel="main menu" > <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_billing", ] } > <MenuCloudTrial id="menuCloudTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_about_edition_and_license", ] } > <MenuStartTrial id="startTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="mentions" > @ </i> } id="recentMentions" onClick={[Function]} show={true} text="Recent Mentions" /> <MenuItemAction icon={ <i className="fa fa-bookmark" /> } id="flaggedPosts" onClick={[Function]} show={true} text="Saved messages" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user" /> } id="profileSettings" modalId="user_settings" show={true} text="Profile" /> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": true, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-cog" /> } id="accountSettings" modalId="user_settings" show={true} text="Settings" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={ <i className="fa fa-user-plus" /> } id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-globe" /> } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="createTeam" show={true} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={<LeaveTeamIcon />} id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup) /> <Memo(MenuGroup)> <MenuItemLink id="integrations" show={false} text="Integrations" to="/team_name/integrations" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemExternalLink icon={ <i className="fa fa-question" /> } id="helpLink" show={true} text="Help" url="test-link-help" /> <MenuItemExternalLink icon={ <i className="fa fa-phone" /> } id="reportLink" show={true} text="Report a Problem" url="test-report-link" /> <MenuItemExternalLink icon={ <i className="fa fa-mobile" /> } id="nativeAppLink" show={true} text="Download Apps" url="test" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-info" /> } id="about" modalId="about" show={true} text="About Mattermost" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="fa fa-sign-out" /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> `; exports[`components/Menu should match snapshot with plugins 1`] = ` <Menu ariaLabel="team menu" > <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={false} id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> <MenuItemLink id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux className="destructive" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink className="" disabled={false} id="createTeam" show={true} sibling={false} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <Memo(MenuGroup)> <div className="MainMenu_dropdown-link" > <LearnAboutTeamsLink /> </div> </Memo(MenuGroup)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={false} id="plugin-id-1_pluginmenuitem" key="plugin-id-1_pluginmenuitem" onClick={[Function]} show={true} /> <MenuItemAction icon={false} id="plugind-id-2_pluginmenuitem" key="plugind-id-2_pluginmenuitem" onClick={[Function]} show={true} /> </Memo(MenuGroup)> </Menu> `; exports[`components/Menu should match snapshot with plugins in mobile 1`] = ` <Menu ariaLabel="main menu" > <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_billing", ] } > <MenuCloudTrial id="menuCloudTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_about_edition_and_license", ] } > <MenuStartTrial id="startTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="mentions" > @ </i> } id="recentMentions" onClick={[Function]} show={true} text="Recent Mentions" /> <MenuItemAction icon={ <i className="fa fa-bookmark" /> } id="flaggedPosts" onClick={[Function]} show={true} text="Saved messages" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user" /> } id="profileSettings" modalId="user_settings" show={true} text="Profile" /> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": true, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-cog" /> } id="accountSettings" modalId="user_settings" show={true} text="Settings" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="addGroupsToTeam" modalId="add_groups_to_team" show={false} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={ <i className="fa fa-user-plus" /> } id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-globe" /> } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "team-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="manageGroups" modalId="manage_team_groups" show={false} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="team-id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="createTeam" show={true} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="joinTeam" show={false} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={<LeaveTeamIcon />} id="leaveTeam" modalId="leave_team" show={true} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction id="plugin-id-1_pluginmenuitem" key="plugin-id-1_pluginmenuitem" onClick={[Function]} show={true} /> <MenuItemAction id="plugind-id-2_pluginmenuitem" key="plugind-id-2_pluginmenuitem" onClick={[Function]} show={true} /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemLink id="integrations" show={false} text="Integrations" to="/team_name/integrations" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemExternalLink icon={ <i className="fa fa-question" /> } id="helpLink" show={false} text="Help" /> <MenuItemExternalLink icon={ <i className="fa fa-phone" /> } id="reportLink" show={false} text="Report a Problem" /> <MenuItemExternalLink icon={ <i className="fa fa-mobile" /> } id="nativeAppLink" show={true} text="Download Apps" url="" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-info" /> } id="about" modalId="about" show={true} text="About Mattermost" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="fa fa-sign-out" /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> `;
2,552
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown/markdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {TeamType} from '@mattermost/types/teams'; import Markdown from 'components/markdown'; import {renderWithContext} from 'tests/react_testing_utils'; import EmojiMap from 'utils/emoji_map'; import {TestHelper} from 'utils/test_helper'; describe('components/Markdown', () => { const baseProps = { channelNamesMap: {}, enableFormatting: true, mentionKeys: [], message: 'This _is_ some **Markdown**', siteURL: 'https://markdown.example.com', team: TestHelper.getTeamMock({ id: 'id123', invite_id: 'invite_id123', name: 'yourteamhere', create_at: 1, update_at: 2, delete_at: 3, display_name: 'test', description: 'test', email: '[email protected]', type: 'T' as TeamType, company_name: 'test', allowed_domains: 'test', allow_open_invite: false, scheme_id: 'test', group_constrained: false, }), hasImageProxy: false, minimumHashtagLength: 3, emojiMap: new EmojiMap(new Map()), metadata: {}, }; test('should render properly', () => { const {container} = renderWithContext(<Markdown {...baseProps}/>); expect(container).toMatchSnapshot(); }); test('should not render markdown when formatting is disabled', () => { const props = { ...baseProps, enableFormatting: false, }; const {container} = renderWithContext(<Markdown {...props}/>); expect(container).toMatchSnapshot(); }); });
2,554
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown/__snapshots__/markdown.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/Markdown should not render markdown when formatting is disabled 1`] = ` <div> <p> This <em> is </em> some <strong> Markdown </strong> </p> </div> `; exports[`components/Markdown should render properly 1`] = ` <div> <p> This <em> is </em> some <strong> Markdown </strong> </p> </div> `;
2,556
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown_image/markdown_image.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import FilePreviewModal from 'components/file_preview_modal'; import SizeAwareImage from 'components/size_aware_image'; import Constants from 'utils/constants'; import MarkdownImage from './markdown_image'; describe('components/MarkdownImage', () => { const baseProps = { imageMetadata: { format: 'png', height: 90, width: 1041, frameCount: 0, }, alt: 'test image', height: '', width: '', title: 'test title', className: 'markdown-inline-img', postId: 'post_id', imageIsLink: false, onImageLoaded: jest.fn(), onImageHeightChanged: jest.fn(), postType: 'system_generic', actions: { openModal: jest.fn(), }, }; test('should match snapshot', () => { const props = {...baseProps, src: '/images/logo.png'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for broken link', () => { const props = {...baseProps, imageMetadata: { format: 'png', height: 10, width: 10, frameCount: 0, }, src: 'brokenLink'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should handle load failure properly', () => { const props = {...baseProps, imageMetadata: { format: 'png', height: 10, width: 10, frameCount: 0, }, src: 'brokenLink'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); expect(wrapper.state('loadFailed')).toBe(false); (wrapper.instance() as MarkdownImage).handleLoadFail(); expect(wrapper.state('loadFailed')).toBe(true); }); test('should reset loadFailed state after image source is updated', () => { const props = {...baseProps, imageMetadata: { format: 'png', height: 10, width: 10, frameCount: 0, }, src: 'brokenLink'}; const nextProps = {...baseProps, src: 'https://example.com/image.png'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loadFailed: true}); wrapper.setProps(nextProps); expect(wrapper.state('loadFailed')).toBe(false); }); test('should render a link if the source is unsafe', () => { const props = {...baseProps, src: ''}; const wrapper = shallow( <MarkdownImage {...props}/>, ); expect(wrapper.find('img').props().alt).toBe(props.alt); expect(wrapper.find('img').props().className).toBe(props.className + ' broken-image'); expect(wrapper).toMatchSnapshot(); }); test('should handle not loaded state properly', () => { const props = {...baseProps, src: 'https://example.com/image.png'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); expect(wrapper.state('loaded')).toBe(false); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper.find(SizeAwareImage)).toHaveLength(1); expect(childrenWrapper.find(SizeAwareImage).prop('className')). toEqual(`${props.className} markdown-inline-img--loading`); }); test('should handle not loaded state properly in case of a header change system message', () => { const props = {...baseProps, src: 'https://example.com/image.png', postType: 'system_header_change'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); expect(wrapper.state('loaded')).toBe(false); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper.find(SizeAwareImage)).toHaveLength(1); expect(childrenWrapper.find(SizeAwareImage).prop('className')). toEqual(`${props.className} markdown-inline-img--scaled-down-loading`); }); test('should set loaded state when img loads and call onImageLoaded prop', () => { const props = {...baseProps, src: 'https://example.com/image.png'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); const dimensions = { height: props.imageMetadata.height, width: props.imageMetadata.width, }; expect(wrapper.state('loaded')).toBe(false); (wrapper.instance() as MarkdownImage).handleImageLoaded(dimensions); expect(wrapper.state('loaded')).toBe(true); expect(props.onImageLoaded).toHaveBeenCalledTimes(1); expect(props.onImageLoaded).toHaveBeenCalledWith(dimensions); }); it('should match snapshot for SizeAwareImage dimensions', () => { const props = {...baseProps, imageMetadata: {format: 'jpg', frameCount: 0, width: 100, height: 90}, src: 'path/image', }; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenWrapper = wrapper.props().children('safeSrc'); expect(childrenWrapper).toMatchSnapshot(); }); test('should render an image with preview modal if the source is safe', () => { const props = {...baseProps, src: 'https://example.com/image.png'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper.find(SizeAwareImage)).toHaveLength(1); expect(childrenWrapper.find(SizeAwareImage).prop('className')). toEqual(`${props.className} markdown-inline-img--hover cursor--pointer a11y--active`); expect(childrenWrapper).toMatchSnapshot(); }); test('should render an image with no preview if the source is safe and the image is a link', () => { const props = {...baseProps, src: 'https://example.com/image.png', imageIsLink: true}; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper.find(SizeAwareImage)).toHaveLength(1); expect(childrenWrapper.find(SizeAwareImage).prop('className')). toEqual(`${props.className} markdown-inline-img--hover markdown-inline-img--no-border`); expect(childrenWrapper.find(FilePreviewModal)).toHaveLength(0); expect(childrenWrapper).toMatchSnapshot(); }); test('should call openModal when showModal is called', () => { const props = {...baseProps, src: 'https://example.com/image.png'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); const mockEvent = { preventDefault: () => {}, }; (wrapper.instance() as MarkdownImage).showModal(mockEvent as unknown as React.MouseEvent<HTMLImageElement>, 'https://example.com/image.png'); expect(props.actions.openModal).toHaveBeenCalledTimes(1); }); test('should properly scale down the image in case of a header change system message', () => { const props = {...baseProps, src: 'https://example.com/image.png', postType: 'system_header_change'}; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper.find(SizeAwareImage)).toHaveLength(1); expect(childrenWrapper.find(SizeAwareImage).prop('className')). toEqual(`${props.className} markdown-inline-img--hover cursor--pointer a11y--active markdown-inline-img--scaled-down`); }); test('should render image with title, height, width', () => { const props = { alt: 'test image', title: 'test title', className: 'markdown-inline-img', postId: 'post_id', src: 'https://example.com/image.png', imageIsLink: false, height: '76', width: '50', actions: baseProps.actions, }; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper.find(SizeAwareImage)).toHaveLength(1); expect(childrenWrapper.find(SizeAwareImage).prop('className')). toEqual(`${props.className} markdown-inline-img--hover cursor--pointer a11y--active`); // These props can be strings since they're passed directly through to HTML tags expect(childrenWrapper.find(SizeAwareImage).prop('width')).toEqual('50'); expect(childrenWrapper.find(SizeAwareImage).prop('height')).toEqual('76'); expect(childrenWrapper.find(SizeAwareImage).prop('title')).toEqual('test title'); }); test(`should render image with MarkdownImageExpand if it is taller than ${Constants.EXPANDABLE_INLINE_IMAGE_MIN_HEIGHT}px`, () => { const props = { alt: 'test image', title: 'test title', className: 'markdown-inline-img', postId: 'post_id', src: 'https://example.com/image.png', imageIsLink: false, height: '250', width: '50', actions: baseProps.actions, }; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper).toMatchSnapshot(); }); test('should provide image src as an alt text for MarkdownImageExpand if image has no own alt text', () => { const props = { alt: '', title: 'test title', className: 'markdown-inline-img', postId: 'post_id', src: 'https://example.com/image.png', imageIsLink: false, height: '250', width: '50', actions: baseProps.actions, }; const wrapper = shallow( <MarkdownImage {...props}/>, ); wrapper.instance().setState({loaded: true}); const childrenNode = wrapper.props().children(props.src); // using a div as a workaround because shallow doesn't support react fragments const childrenWrapper = shallow(<div>{childrenNode}</div>); expect(childrenWrapper).toMatchSnapshot(); }); });
2,558
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown_image
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown_image/__snapshots__/markdown_image.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MarkdownImage should match snapshot 1`] = ` <Connect(Component) imageMetadata={ Object { "format": "png", "frameCount": 0, "height": 90, "width": 1041, } } src="/images/logo.png" > <Component /> </Connect(Component)> `; exports[`components/MarkdownImage should match snapshot for SizeAwareImage dimensions 1`] = ` <SizeAwareImage alt="test image" className="markdown-inline-img markdown-inline-img--hover markdown-inline-img--no-border" dimensions={ Object { "format": "jpg", "frameCount": 0, "height": 90, "width": 100, } } height="" onClick={[Function]} onImageLoadFail={[Function]} onImageLoaded={[Function]} showLoader={false} src="safeSrc" title="test title" width="" /> `; exports[`components/MarkdownImage should match snapshot for broken link 1`] = ` <Connect(Component) imageMetadata={ Object { "format": "png", "frameCount": 0, "height": 10, "width": 10, } } src="brokenLink" > <Component /> </Connect(Component)> `; exports[`components/MarkdownImage should provide image src as an alt text for MarkdownImageExpand if image has no own alt text 1`] = ` <div> <Connect(MarkdownImageExpand) alt="https://example.com/image.png" imageKey="https://example.com/image.png" postId="post_id" > <SizeAwareImage alt="" className="markdown-inline-img markdown-inline-img--hover cursor--pointer a11y--active" dimensions={Object {}} height="250" onClick={[Function]} onImageLoadFail={[Function]} onImageLoaded={[Function]} showLoader={false} src="https://example.com/image.png" title="test title" width="50" /> </Connect(MarkdownImageExpand)> </div> `; exports[`components/MarkdownImage should render a link if the source is unsafe 1`] = ` <div style={ Object { "display": "inline-block", } } > <img alt="test image" className="markdown-inline-img broken-image" src={null} /> </div> `; exports[`components/MarkdownImage should render an image with no preview if the source is safe and the image is a link 1`] = ` <div> <SizeAwareImage alt="test image" className="markdown-inline-img markdown-inline-img--hover markdown-inline-img--no-border" dimensions={ Object { "format": "png", "frameCount": 0, "height": 90, "width": 1041, } } height="" onClick={[Function]} onImageLoadFail={[Function]} onImageLoaded={[Function]} showLoader={false} src="https://example.com/image.png" title="test title" width="" /> </div> `; exports[`components/MarkdownImage should render an image with preview modal if the source is safe 1`] = ` <div> <SizeAwareImage alt="test image" className="markdown-inline-img markdown-inline-img--hover cursor--pointer a11y--active" dimensions={ Object { "format": "png", "frameCount": 0, "height": 90, "width": 1041, } } height="" onClick={[Function]} onImageLoadFail={[Function]} onImageLoaded={[Function]} showLoader={false} src="https://example.com/image.png" title="test title" width="" /> </div> `; exports[`components/MarkdownImage should render image with MarkdownImageExpand if it is taller than 100px 1`] = ` <div> <Connect(MarkdownImageExpand) alt="test image" imageKey="https://example.com/image.png" postId="post_id" > <SizeAwareImage alt="test image" className="markdown-inline-img markdown-inline-img--hover cursor--pointer a11y--active" dimensions={Object {}} height="250" onClick={[Function]} onImageLoadFail={[Function]} onImageLoaded={[Function]} showLoader={false} src="https://example.com/image.png" title="test title" width="50" /> </Connect(MarkdownImageExpand)> </div> `;
2,561
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown_image_expand/markdown_image_expand.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import MarkdownImageExpand from './markdown_image_expand'; describe('components/MarkdownImageExpand', () => { it('should match snapshot for collapsed embeds', () => { const toggleHandler = jest.fn(); const imageCollapseHandler = jest.fn(); const wrapper = shallow( <MarkdownImageExpand alt={'Some alt text'} postId={'abc'} isExpanded={false} imageKey={'1'} onToggle={toggleHandler} toggleInlineImageVisibility={imageCollapseHandler} >{'An image to expand'}</MarkdownImageExpand>, ); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot for expanded embeds', () => { const toggleHandler = jest.fn(); const imageCollapseHandler = jest.fn(); const wrapper = shallow( <MarkdownImageExpand alt={'Some alt text'} postId={'abc'} isExpanded={true} imageKey={'1'} onToggle={toggleHandler} toggleInlineImageVisibility={imageCollapseHandler} >{'An image to expand'}</MarkdownImageExpand>, ); expect(wrapper).toMatchSnapshot(); }); it('should emit toggle action on collapse button click', () => { const toggleHandler = jest.fn(); const imageCollapseHandler = jest.fn(); const wrapper = shallow( <MarkdownImageExpand alt={'Some alt text'} postId={'abc'} isExpanded={true} imageKey={'1'} onToggle={toggleHandler} toggleInlineImageVisibility={imageCollapseHandler} >{'An image to expand'}</MarkdownImageExpand>, ); wrapper.find('.markdown-image-expand__collapse-button').simulate('click'); expect(imageCollapseHandler).toHaveBeenCalled(); }); it('should emit toggle action on expand button click', () => { const toggleHandler = jest.fn(); const imageCollapseHandler = jest.fn(); const wrapper = shallow( <MarkdownImageExpand alt={'Some alt text'} postId={'abc'} isExpanded={false} imageKey={'1'} onToggle={toggleHandler} toggleInlineImageVisibility={imageCollapseHandler} >{'An image to expand'}</MarkdownImageExpand>, ); wrapper.find('.markdown-image-expand__expand-button').simulate('click'); expect(imageCollapseHandler).toHaveBeenCalled(); }); });
2,563
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown_image_expand
petrpan-code/mattermost/mattermost/webapp/channels/src/components/markdown_image_expand/__snapshots__/markdown_image_expand.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MarkdownImageExpand should match snapshot for collapsed embeds 1`] = ` <div className="markdown-image-expand " > <button className="markdown-image-expand__expand-button" onClick={[Function]} type="button" > <span className="icon icon-menu-right markdown-image-expand__expand-icon" /> <span className="markdown-image-expand__alt-text" > Some alt text </span> </button> </div> `; exports[`components/MarkdownImageExpand should match snapshot for expanded embeds 1`] = ` <div className="markdown-image-expand markdown-image-expand--expanded" > <button className="markdown-image-expand__collapse-button" onClick={[Function]} type="button" > <span className="icon icon-menu-down" /> </button> An image to expand </div> `;
2,569
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/menu/menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React, {useState} from 'react'; import {DotsVerticalIcon} from '@mattermost/compass-icons/components'; import {GenericModal} from '@mattermost/components'; import { renderWithContext, screen, userEvent, waitForElementToBeRemoved, } from 'tests/react_testing_utils'; import {Menu} from './menu'; import {MenuItem} from './menu_item'; import {SubMenu} from './sub_menu'; describe('menu click handlers', () => { test('should be able to open a React Bootstrap modal with the mouse', async () => { renderWithContext( <MenuWithModal/>, ); expect(screen.queryByText('Open modal')).not.toBeInTheDocument(); expect(screen.queryByText('A Modal')).not.toBeInTheDocument(); // Click to open the menu userEvent.click(screen.getByLabelText('menu with modal button')); expect(screen.getByText('Open modal')).toBeInTheDocument(); // Click to open the modal userEvent.click(screen.getByText('Open modal')); // Wait for the menu to close before the modal will be opened await waitForElementToBeRemoved(() => screen.queryByText('Open modal')); expect(screen.getByText('A Modal')).toBeInTheDocument(); }); for (const enterOrSpace of ['enter', 'space']) { test(`should be able to open a React Bootstrap modal with the keyboard using the ${enterOrSpace} key`, async () => { renderWithContext( <MenuWithModal/>, ); expect(screen.queryByText('Open modal')).not.toBeInTheDocument(); expect(screen.queryByText('A Modal')).not.toBeInTheDocument(); expect(document.body).toHaveFocus(); // Tab to select the menu button userEvent.tab(); expect(screen.getByLabelText('menu with modal button')).toHaveFocus(); // Press the key to open the menu userEvent.keyboard('{' + enterOrSpace + '}'); expect(screen.getByText('Open modal')).toBeInTheDocument(); // Press the down arrow twice to select the menu item we want userEvent.keyboard('{arrowdown}{arrowdown}'); expect(screen.getByText('Open modal').closest('li')).toHaveFocus(); // Press the key to open the modal userEvent.keyboard('{' + enterOrSpace + '}'); // Wait for the menu to close before the modal will be opened await waitForElementToBeRemoved(() => screen.queryByText('Open modal')); expect(screen.getByText('A Modal')).toBeInTheDocument(); }); } test('should be able to open a React Bootstrap modal from a submenu with the mouse', async () => { renderWithContext( <MenuWithSubMenuModal/>, ); expect(screen.queryByText('Open submenu')).not.toBeInTheDocument(); expect(screen.queryByText('Open modal')).not.toBeInTheDocument(); expect(screen.queryByText('A Modal')).not.toBeInTheDocument(); // Click to open the menu userEvent.click(screen.getByLabelText('menu with modal button')); expect(screen.getByText('Open submenu')).toBeInTheDocument(); expect(screen.queryByText('Open model from submenu')).not.toBeInTheDocument(); // Hover to open the submenu userEvent.hover(screen.getByText('Open submenu')); expect(screen.getByText('Open modal from submenu')).toBeInTheDocument(); // Click to open the modal userEvent.click(screen.getByText('Open modal from submenu')); // Wait for the menu and submenu to close before the modal will be opened await waitForElementToBeRemoved(() => screen.queryByText('Open modal from submenu')); await waitForElementToBeRemoved(() => screen.queryByText('Open submenu')); expect(screen.getByText('A Modal')).toBeInTheDocument(); }); for (const enterOrSpace of ['enter', 'space']) { test(`should be able to open a React Bootstrap modal with the keyboard using the ${enterOrSpace} key`, async () => { renderWithContext( <MenuWithSubMenuModal/>, ); expect(screen.queryByText('Open submenu')).not.toBeInTheDocument(); expect(screen.queryByText('Open modal')).not.toBeInTheDocument(); expect(screen.queryByText('A Modal')).not.toBeInTheDocument(); expect(document.body).toHaveFocus(); // Tab to select the menu button userEvent.tab(); expect(screen.getByLabelText('menu with modal button')).toHaveFocus(); // Press the key to open the menu userEvent.keyboard('{' + enterOrSpace + '}'); expect(screen.getByText('Open submenu')).toBeInTheDocument(); expect(screen.queryByText('Open model from submenu')).not.toBeInTheDocument(); // Press the down arrow to select the submenu item userEvent.keyboard('{arrowdown}'); expect(screen.getByText('Open submenu').closest('li')).toHaveFocus(); // Press the right arrow to open the submenu userEvent.keyboard('{arrowright}'); expect(screen.getByText('Open modal from submenu')).toBeInTheDocument(); // Press the down arrow once to focus first submenu item and then twice more to select the one we want userEvent.keyboard('{arrowdown}{arrowdown}{arrowdown}'); expect(screen.getByText('Open modal from submenu').closest('li')).toHaveFocus(); // Press the key to open the modal userEvent.keyboard('{' + enterOrSpace + '}'); // Wait for the menu and submenu to close before the modal will be opened await waitForElementToBeRemoved(() => screen.queryByText('Open submenu')); expect(screen.getByText('A Modal')).toBeInTheDocument(); }); } }); function MenuWithModal() { const [showModal, setShowModal] = useState(false); let modal; if (showModal) { modal = ( <GenericModal show={showModal} confirmButtonText='Confirm button' modalHeaderText='A Modal' onExited={() => setShowModal(false)} > {'The contents of A Modal'} </GenericModal> ); } return ( <> <Menu menu={{ id: 'Menu', }} menuButton={{ id: 'Menu-Button', 'aria-label': 'menu with modal button', children: <DotsVerticalIcon size={16}/>, }} > <OtherMenuItem/> <OtherMenuItem/> <MenuItem labels={<span>{'Open modal'}</span>} onClick={() => setShowModal(true)} /> </Menu> {modal} </> ); } function MenuWithSubMenuModal() { const [showModal, setShowModal] = useState(false); let modal; if (showModal) { modal = ( <GenericModal show={showModal} confirmButtonText='Confirm button' modalHeaderText='A Modal' onExited={() => setShowModal(false)} > {'The contents of A Modal'} </GenericModal> ); } return ( <> <Menu menu={{ id: 'Menu', }} menuButton={{ id: 'Menu-Button', 'aria-label': 'menu with modal button', children: <DotsVerticalIcon size={16}/>, }} > <OtherMenuItem/> <SubMenu id='Menu-SubMenu' labels={<>{'Open submenu'}</>} menuId='Menu-SubMenu-Menu' > <OtherMenuItem/> <OtherMenuItem/> <MenuItem labels={<span>{'Open modal from submenu'}</span>} onClick={() => setShowModal(true)} /> <OtherMenuItem/> </SubMenu> </Menu> {modal} </> ); } function OtherMenuItem(props: any) { return ( <MenuItem {...props} labels={<>{'Some menu item'}</>} onClick={() => { throw new Error("don't click me"); }} /> ); }
2,577
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/mfa/confirm.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {redirectUserToDefaultTeam} from 'actions/global_actions'; import Confirm from 'components/mfa/confirm'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import Constants from 'utils/constants'; jest.mock('actions/global_actions', () => ({ redirectUserToDefaultTeam: jest.fn(), })); describe('components/mfa/components/Confirm', () => { const originalAddEventListener = document.body.addEventListener; const defaultProps = { updateParent: jest.fn(), state: { enforceMultifactorAuthentication: true, }, }; afterAll(() => { document.body.addEventListener = originalAddEventListener; }); test('should match snapshot', () => { const wrapper = shallow(<Confirm {...defaultProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should submit on form submit', () => { const wrapper = mountWithIntl(<Confirm {...defaultProps}/>); wrapper.find('form').simulate('submit'); expect(redirectUserToDefaultTeam).toHaveBeenCalled(); }); test('should submit on enter', () => { const map: { [key: string]: any } = { keydown: null, }; document.body.addEventListener = jest.fn().mockImplementation((event: string, callback: string) => { map[event] = callback; }); mountWithIntl(<Confirm {...defaultProps}/>); const event = { preventDefault: jest.fn(), key: Constants.KeyCodes.ENTER[0], }; map.keydown(event); expect(redirectUserToDefaultTeam).toHaveBeenCalled(); }); });
2,579
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/mfa
petrpan-code/mattermost/mattermost/webapp/channels/src/components/mfa/__snapshots__/confirm.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/mfa/components/Confirm should match snapshot 1`] = ` <div> <form className="form-group" onKeyPress={[Function]} onSubmit={[Function]} > <p> <FormattedMarkdownMessage defaultMessage="**Set up complete!**" id="mfa.confirm.complete" /> </p> <p> <MemoizedFormattedMessage defaultMessage="Your account is now secure. Next time you sign in, you will be asked to enter a code from the Google Authenticator app on your phone." id="mfa.confirm.secure" /> </p> <button className="btn btn-primary" type="submit" > <MemoizedFormattedMessage defaultMessage="Okay" id="mfa.confirm.okay" /> </button> </form> </div> `;
2,585
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/mobile_view_watcher/mobile_view_watcher.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {render} from '@testing-library/react'; import React from 'react'; import matchMedia from 'tests/helpers/match_media.mock'; import Constants, {WindowSizes} from 'utils/constants'; import MobileViewWatcher from './mobile_view_watcher'; describe('window.matchMedia', () => { const baseProps = { emitBrowserWindowResized: jest.fn(), }; afterEach(() => { matchMedia.clear(); }); test('should update redux when the desktop media query matches', () => { render(<MobileViewWatcher {...baseProps}/>); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(0); matchMedia.useMediaQuery(`(min-width: ${Constants.DESKTOP_SCREEN_WIDTH + 1}px)`); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(1); expect(baseProps.emitBrowserWindowResized.mock.calls[0][0]).toBe(WindowSizes.DESKTOP_VIEW); }); test('should update redux when the small desktop media query matches', () => { render(<MobileViewWatcher {...baseProps}/>); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(0); matchMedia.useMediaQuery(`(min-width: ${Constants.TABLET_SCREEN_WIDTH + 1}px) and (max-width: ${Constants.DESKTOP_SCREEN_WIDTH}px)`); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(1); expect(baseProps.emitBrowserWindowResized.mock.calls[0][0]).toBe(WindowSizes.SMALL_DESKTOP_VIEW); }); test('should update redux when the tablet media query matches', () => { render(<MobileViewWatcher {...baseProps}/>); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(0); matchMedia.useMediaQuery(`(min-width: ${Constants.MOBILE_SCREEN_WIDTH + 1}px) and (max-width: ${Constants.TABLET_SCREEN_WIDTH}px)`); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(1); expect(baseProps.emitBrowserWindowResized.mock.calls[0][0]).toBe(WindowSizes.TABLET_VIEW); }); test('should update redux when the mobile media query matches', () => { render(<MobileViewWatcher {...baseProps}/>); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(0); matchMedia.useMediaQuery(`(max-width: ${Constants.MOBILE_SCREEN_WIDTH}px)`); expect(baseProps.emitBrowserWindowResized).toBeCalledTimes(1); expect(baseProps.emitBrowserWindowResized.mock.calls[0][0]).toBe(WindowSizes.MOBILE_VIEW); }); });
2,588
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/modal_controller/modal_controller.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Modal} from 'react-bootstrap'; import {Provider} from 'react-redux'; import {closeModal} from 'actions/views/modals'; import mockStore from 'tests/test_store'; import ModalController from '.'; type TestModalProps = { onExited: () => void; } type TestModalState = { show: boolean; } class TestModal extends React.PureComponent<TestModalProps, TestModalState> { constructor(props: TestModalProps) { super(props); this.state = { show: true, }; } hideModal = () => { this.setState({show: false}); }; render() { return ( <Modal show={this.state.show} onHide={this.hideModal} onExited={this.props.onExited} > <Modal.Header closeButton={true}/> <Modal.Body/> </Modal> ); } } describe('components/ModalController', () => { const modalId = 'test_modal'; test('component should match snapshot without any modals', () => { const state = { views: { modals: { modalState: {}, }, }, }; const store = mockStore(state); const wrapper = mount( <Provider store={store}> <ModalController/> </Provider>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('ModalController > *').length).toBe(0); expect(document.getElementsByClassName('modal-dialog').length).toBeFalsy(); }); test('test model should be open', () => { const state = { views: { modals: { modalState: { [modalId]: { open: true, dialogProps: {}, dialogType: TestModal, }, }, }, }, }; const store = mockStore(state); mount( <Provider store={store}> <ModalController/> </Provider>, ); expect(document.getElementsByClassName('modal-dialog').length).toBe(1); }); test('should pass onExited to modal to allow a modal to remove itself', () => { const state = { views: { modals: { modalState: { [modalId]: { open: true, dialogProps: {}, dialogType: TestModal, }, }, }, }, }; const store = mockStore(state); const wrapper = mount( <Provider store={store}> <ModalController/> </Provider>, ); expect(wrapper.find(TestModal).exists()).toBe(true); expect(wrapper.find(TestModal).prop('onExited')).toBeDefined(); expect(wrapper.find(Modal).prop('onExited')).toBeDefined(); wrapper.find(TestModal).prop('onExited')!(); expect(store.getActions()).toEqual([ closeModal(modalId), ]); }); test('should call a provided onExited in addition to removing the modal', () => { const onExited = jest.fn(); const state = { views: { modals: { modalState: { [modalId]: { open: true, dialogProps: { onExited, }, dialogType: TestModal, }, }, }, }, }; const store = mockStore(state); const wrapper = mount( <Provider store={store}> <ModalController/> </Provider>, ); expect(wrapper.find(TestModal).exists()).toBe(true); expect(wrapper.find(TestModal).prop('onExited')).toBeDefined(); expect(wrapper.find(Modal).prop('onExited')).toBeDefined(); expect(onExited).not.toBeCalled(); wrapper.find(TestModal).prop('onExited')!(); expect(onExited).toBeCalled(); }); });
2,590
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/modal_controller
petrpan-code/mattermost/mattermost/webapp/channels/src/components/modal_controller/__snapshots__/modal_controller.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ModalController component should match snapshot without any modals 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(ModalController)> <ModalController actions={ Object { "closeModal": [Function], } } modals={ Object { "modalState": Object {}, } } /> </Connect(ModalController)> </Provider> `;
2,592
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels/more_direct_channels.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ComponentProps} from 'react'; import type {UserProfile} from '@mattermost/types/users'; import MoreDirectChannels from 'components/more_direct_channels/more_direct_channels'; import {TestHelper} from 'utils/test_helper'; jest.useFakeTimers(); const mockedUser = TestHelper.getUserMock(); describe('components/MoreDirectChannels', () => { const baseProps: ComponentProps<typeof MoreDirectChannels> = { currentUserId: 'current_user_id', currentTeamId: 'team_id', currentTeamName: 'team_name', searchTerm: '', totalCount: 3, users: [ { ...mockedUser, id: 'user_id_1', delete_at: 0, }, { ...mockedUser, id: 'user_id_2', delete_at: 0, }, { ...mockedUser, id: 'user_id_3', delete_at: 0, }, ], currentChannelMembers: [ { ...mockedUser, id: 'user_id_1', }, { ...mockedUser, id: 'user_id_2', }, ], isExistingChannel: false, restrictDirectMessage: 'any', onModalDismissed: jest.fn(), onExited: jest.fn(), actions: { getProfiles: jest.fn(() => { return new Promise<void>((resolve) => { process.nextTick(() => resolve()); }); }), getProfilesInTeam: jest.fn().mockResolvedValue({data: true}), loadProfilesMissingStatus: jest.fn().mockResolvedValue({data: true}), searchProfiles: jest.fn().mockResolvedValue({data: true}), searchGroupChannels: jest.fn().mockResolvedValue({data: true}), setModalSearchTerm: jest.fn().mockResolvedValue({data: true}), loadStatusesForProfilesList: jest.fn().mockResolvedValue({data: true}), loadProfilesForGroupChannels: jest.fn().mockResolvedValue({data: true}), openDirectChannelToUserId: jest.fn().mockResolvedValue({data: {name: 'dm'}}), openGroupChannelToUserIds: jest.fn().mockResolvedValue({data: {name: 'group'}}), getTotalUsersStats: jest.fn().mockImplementation(() => { return ((resolve: () => any) => { process.nextTick(() => resolve()); }); }), }, }; test('should match snapshot', () => { const props = {...baseProps, actions: {...baseProps.actions, loadProfilesMissingStatus: jest.fn()}}; const wrapper = shallow(<MoreDirectChannels {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should call for modal data on callback of modal onEntered', () => { const props = {...baseProps, actions: {...baseProps.actions, loadProfilesMissingStatus: jest.fn()}}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); wrapper.instance().loadModalData(); expect(props.actions.getProfiles).toHaveBeenCalledTimes(1); expect(props.actions.getTotalUsersStats).toHaveBeenCalledTimes(1); expect(props.actions.getProfiles).toBeCalledWith(0, 100); expect(props.actions.loadProfilesMissingStatus).toHaveBeenCalledTimes(1); expect(props.actions.loadProfilesMissingStatus).toBeCalledWith(baseProps.users); }); test('should call actions.loadProfilesMissingStatus on componentDidUpdate when users prop changes length', () => { const props = {...baseProps, actions: {...baseProps.actions, loadProfilesMissingStatus: jest.fn()}}; const wrapper = shallow(<MoreDirectChannels {...props}/>); const newUsers = [{ id: 'user_id_1', label: 'user_id_1', value: 'user_id_1', delete_at: 0, }]; wrapper.setProps({users: newUsers}); expect(props.actions.loadProfilesMissingStatus).toHaveBeenCalledTimes(1); expect(props.actions.loadProfilesMissingStatus).toBeCalledWith(newUsers); }); test('should call actions.setModalSearchTerm and match state on handleHide', () => { const props = {...baseProps, actions: {...baseProps.actions, setModalSearchTerm: jest.fn()}}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); wrapper.setState({show: true}); wrapper.instance().handleHide(); expect(props.actions.setModalSearchTerm).toHaveBeenCalledTimes(1); expect(props.actions.setModalSearchTerm).toBeCalledWith(''); expect(wrapper.state('show')).toEqual(false); }); test('should match state on setUsersLoadingState', () => { const props = {...baseProps}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); wrapper.setState({loadingUsers: true}); wrapper.instance().setUsersLoadingState(false); expect(wrapper.state('loadingUsers')).toEqual(false); wrapper.setState({loadingUsers: false}); wrapper.instance().setUsersLoadingState(true); expect(wrapper.state('loadingUsers')).toEqual(true); }); test('should call on search', () => { jest.useFakeTimers(); const props = {...baseProps, actions: {...baseProps.actions, setModalSearchTerm: jest.fn()}}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); wrapper.instance().search('user_search'); expect(props.actions.setModalSearchTerm).not.toBeCalled(); jest.runAllTimers(); expect(props.actions.setModalSearchTerm).toHaveBeenCalledTimes(1); expect(props.actions.setModalSearchTerm).toBeCalledWith('user_search'); }); test('should match state on handleDelete', () => { const props = {...baseProps}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); const user1 = { ...mockedUser, id: 'user_id_1', label: 'user_id_1', value: 'user_id_1', }; const user2 = { ...mockedUser, id: 'user_id_1', label: 'user_id_1', value: 'user_id_1', }; wrapper.setState({values: [user1]}); wrapper.instance().handleDelete([user2]); expect(wrapper.state('values')).toEqual([user2]); }); test('should not open a DM or GM if no user Ids', () => { const props = {...baseProps, currentChannelMembers: []}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); wrapper.instance().handleSubmit(); expect(wrapper.state('saving')).toEqual(false); expect(baseProps.actions.openDirectChannelToUserId).not.toBeCalled(); }); test('should open a DM', (done) => { jest.useFakeTimers({legacyFakeTimers: true}); const user: UserProfile = { ...mockedUser, id: 'user_id_1', }; const props = {...baseProps, currentChannelMembers: [user]}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); const handleHide = jest.fn(); const exitToChannel = ''; wrapper.instance().handleHide = handleHide; wrapper.instance().exitToChannel = exitToChannel; wrapper.instance().handleSubmit(); expect(wrapper.state('saving')).toEqual(true); expect(props.actions.openDirectChannelToUserId).toHaveBeenCalledTimes(1); expect(props.actions.openDirectChannelToUserId).toHaveBeenCalledWith('user_id_1'); process.nextTick(() => { expect(wrapper.state('saving')).toEqual(false); expect(handleHide).toBeCalled(); expect(wrapper.instance().exitToChannel).toEqual(`/${props.currentTeamName}/channels/dm`); done(); }); }); test('should open a GM', (done) => { jest.useFakeTimers({legacyFakeTimers: true}); const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...baseProps}/>); const handleHide = jest.fn(); const exitToChannel = ''; wrapper.instance().handleHide = handleHide; wrapper.instance().exitToChannel = exitToChannel; wrapper.instance().handleSubmit(); expect(wrapper.state('saving')).toEqual(true); expect(baseProps.actions.openGroupChannelToUserIds).toHaveBeenCalledTimes(1); expect(baseProps.actions.openGroupChannelToUserIds).toHaveBeenCalledWith(['user_id_1', 'user_id_2']); process.nextTick(() => { expect(wrapper.state('saving')).toEqual(false); expect(handleHide).toBeCalled(); expect(wrapper.instance().exitToChannel).toEqual(`/${baseProps.currentTeamName}/channels/group`); done(); }); }); test('should exclude deleted users if there is not direct channel between users', () => { const users: UserProfile[] = [ { ...mockedUser, id: 'user_id_1', delete_at: 0, }, { ...mockedUser, id: 'user_id_2', delete_at: 0, }, { ...mockedUser, id: 'deleted_user_1', delete_at: 1, }, { ...mockedUser, id: 'deleted_user_2', delete_at: 1, }, { ...mockedUser, id: 'deleted_user_3', delete_at: 1, }, ]; const myDirectChannels = [ {name: 'deleted_user_1__current_user_id'}, {name: 'not_existent_user_1__current_user_id'}, {name: 'current_user_id__deleted_user_2'}, ]; const currentChannelMembers: UserProfile[] = []; const props = {...baseProps, users, myDirectChannels, currentChannelMembers}; const wrapper = shallow<MoreDirectChannels>(<MoreDirectChannels {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
2,595
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels/__snapshots__/more_direct_channels.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MoreDirectChannels should exclude deleted users if there is not direct channel between users 1`] = ` <Modal animation={true} aria-labelledby="moreDmModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels" dialogComponentClass={[Function]} enforceFocus={true} id="moreDmModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onEntered={[Function]} onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="moreDmModalLabel" > <MemoizedFormattedMessage defaultMessage="Direct Messages" id="more_direct_channels.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" role="application" > <Connect(Component) addValue={[Function]} currentUserId="current_user_id" handleDelete={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} isExistingChannel={false} loading={true} saving={false} search={[Function]} selectedItemRef={ Object { "current": null, } } totalCount={3} users={ Array [ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 1, "email": "", "first_name": "", "id": "deleted_user_1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 1, "email": "", "first_name": "", "id": "deleted_user_2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 1, "email": "", "first_name": "", "id": "deleted_user_3", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, ] } values={Array []} /> </ModalBody> <ModalFooter bsClass="modal-footer" className="modal-footer--invisible" componentClass="div" > <button className="btn btn-tertiary" id="closeModalButton" type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="general_button.close" /> </button> </ModalFooter> </Modal> `; exports[`components/MoreDirectChannels should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="moreDmModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels" dialogComponentClass={[Function]} enforceFocus={true} id="moreDmModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onEntered={[Function]} onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="moreDmModalLabel" > <MemoizedFormattedMessage defaultMessage="Direct Messages" id="more_direct_channels.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" role="application" > <Connect(Component) addValue={[Function]} currentUserId="current_user_id" handleDelete={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} isExistingChannel={false} loading={true} saving={false} search={[Function]} selectedItemRef={ Object { "current": null, } } totalCount={3} users={ Array [ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_3", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, ] } values={ Array [ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_1", "is_bot": false, "label": "some-user", "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", "value": "user_id_1", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id_2", "is_bot": false, "label": "some-user", "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", "value": "user_id_2", }, ] } /> </ModalBody> <ModalFooter bsClass="modal-footer" className="modal-footer--invisible" componentClass="div" > <button className="btn btn-tertiary" id="closeModalButton" type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="general_button.close" /> </button> </ModalFooter> </Modal> `;
2,596
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels/list/index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {UserProfile} from '@mattermost/types/users'; import {General} from 'mattermost-redux/constants'; import * as ChannelUtils from 'mattermost-redux/utils/channel_utils'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import type {GlobalState} from 'types/store'; import type {OptionValue} from '../types'; import {makeGetOptions} from './index'; describe('makeGetOptions', () => { const currentUserId = 'currentUserId'; const baseState = { entities: { channels: { channels: {}, }, general: { config: {}, }, preferences: { myPreferences: {}, }, users: { currentUserId, }, }, views: { search: { modalSearch: '', }, }, } as unknown as GlobalState; test('should return the same result when called with the same arguments', () => { const getOptions = makeGetOptions(); const users = [ TestHelper.fakeUserWithId(), TestHelper.fakeUserWithId(), TestHelper.fakeUserWithId(), ]; const values = [ TestHelper.fakeUserWithId(), ] as OptionValue[]; expect(getOptions(baseState, users, values)).toBe(getOptions(baseState, users, values)); }); test('should return recent DMs, even with deleted users', () => { const getOptions = makeGetOptions(); const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const deletedUser = { ...TestHelper.fakeUserWithId(), delete_at: 1000, }; const dm1 = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, user1.id), last_post_at: 2000, }; const dm2 = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, user2.id), last_post_at: 3000, }; const deletedDM = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, deletedUser.id), last_post_at: 4000, }; const state = mergeObjects(baseState, { entities: { channels: { channels: { [dm1.id]: dm1, [dm2.id]: dm2, [deletedDM.id]: deletedDM, }, }, }, }); const users = [ user1, user2, deletedUser, ]; const values: OptionValue[] = []; // Results are sorted by last_post_at descending expect(getOptions(state, users, values)).toEqual([ {...deletedUser, last_post_at: deletedDM.last_post_at}, {...user2, last_post_at: dm2.last_post_at}, {...user1, last_post_at: dm1.last_post_at}, ]); }); test('should only return DMs with users matching the search term', () => { const getOptions = makeGetOptions(); const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const deletedUser = { ...TestHelper.fakeUserWithId(), delete_at: 1000, }; const dm1 = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, user1.id), last_post_at: 2000, }; const dm2 = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, user2.id), last_post_at: 3000, }; const deletedDM = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, deletedUser.id), last_post_at: 4000, }; const state = mergeObjects(baseState, { entities: { channels: { channels: { [dm1.id]: dm1, [dm2.id]: dm2, [deletedDM.id]: deletedDM, }, }, }, views: { search: { searchTerm: 'asdf', }, }, }); const users = [ user1, user2, deletedUser, ]; const values: OptionValue[] = []; // Results are sorted by last_post_at descending expect(getOptions(state, users, values)).toEqual([ {...deletedUser, last_post_at: deletedDM.last_post_at}, {...user2, last_post_at: dm2.last_post_at}, {...user1, last_post_at: dm1.last_post_at}, ]); }); test('should return recent GMs', () => { const getOptions = makeGetOptions(); const user1 = { ...TestHelper.fakeUserWithId(), username: 'apple', }; const user2 = { ...TestHelper.fakeUserWithId(), username: 'banana', }; const user3 = { ...TestHelper.fakeUserWithId(), username: 'carrot', }; const gmChannel1 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: 'apple, carrot', last_post_at: 1000, }; const gmChannel2 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: 'banana, carrot', last_post_at: 2000, }; const gmChannel3 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: 'apple, banana', last_post_at: 3000, }; const state = mergeObjects(baseState, { entities: { channels: { channels: { [gmChannel1.id]: gmChannel1, [gmChannel2.id]: gmChannel2, [gmChannel3.id]: gmChannel3, }, channelsInTeam: { '': [gmChannel1.id, gmChannel2.id, gmChannel3.id], }, }, users: { profiles: { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }, profilesInChannel: { [gmChannel1.id]: [user1.id, user3.id], [gmChannel2.id]: [user2.id, user3.id], [gmChannel3.id]: [user1.id, user2.id], }, }, }, }); const users: UserProfile[] = []; const values: OptionValue[] = []; // Results are sorted by last_post_at descending expect(getOptions(state, users, values)).toEqual([ { ...gmChannel3, profiles: [user1, user2], }, { ...gmChannel2, profiles: [user2, user3], }, { ...gmChannel1, profiles: [user1, user3], }, ]); }); test('should not return GMs without any posts', () => { const getOptions = makeGetOptions(); const user1 = { ...TestHelper.fakeUserWithId(), username: 'apple', }; const user2 = { ...TestHelper.fakeUserWithId(), username: 'banana', }; const user3 = { ...TestHelper.fakeUserWithId(), username: 'carrot', }; const gmChannel1 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: 'apple, carrot', last_post_at: 1000, }; const gmChannel2 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: 'banana, carrot', last_post_at: 0, }; const state = mergeObjects(baseState, { entities: { channels: { channels: { [gmChannel1.id]: gmChannel1, [gmChannel2.id]: gmChannel2, }, channelsInTeam: { '': [gmChannel1.id, gmChannel2.id], }, }, users: { profiles: { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }, profilesInChannel: { [gmChannel1.id]: [user1.id, user3.id], [gmChannel2.id]: [user2.id, user3.id], }, }, }, }); const users: UserProfile[] = []; const values: OptionValue[] = []; // Results are sorted by last_post_at descending expect(getOptions(state, users, values)).toEqual([ { ...gmChannel1, profiles: [user1, user3], }, ]); }); test('should only return GMs with users matching the search term', () => { const getOptions = makeGetOptions(); const user1 = { ...TestHelper.fakeUserWithId(), username: 'test_user', }; const user2 = { ...TestHelper.fakeUserWithId(), username: 'some_user', first_name: 'Some', last_name: 'Test', }; const user3 = { ...TestHelper.fakeUserWithId(), username: 'another_user', }; const gmChannel1 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, last_post_at: 1000, }; const gmChannel1WithProfiles = { ...gmChannel1, display_name: 'test_user', profiles: [user1], }; const gmChannel2 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, last_post_at: 2000, }; const gmChannel2WithProfiles = { ...gmChannel2, display_name: 'some_user', profiles: [user2], }; const gmChannel3 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, last_post_at: 3000, }; const gmChannel3WithProfiles = { ...gmChannel3, display_name: 'another_user', profiles: [user3], }; let state = mergeObjects(baseState, { entities: { channels: { channels: { [gmChannel1.id]: gmChannel1, [gmChannel2.id]: gmChannel2, [gmChannel3.id]: gmChannel3, }, channelsInTeam: { '': [gmChannel1.id, gmChannel2.id, gmChannel3.id], }, }, users: { profiles: { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }, profilesInChannel: { [gmChannel1.id]: [user1.id], [gmChannel2.id]: [user2.id], [gmChannel3.id]: [user3.id], }, }, }, views: { search: { modalSearch: 'test', }, }, }); const users: UserProfile[] = []; const values: OptionValue[] = []; // Results are sorted by last_post_at descending expect(getOptions(state, users, values)).toEqual([ gmChannel2WithProfiles, gmChannel1WithProfiles, ]); state = mergeObjects(state, { views: { search: { modalSearch: 'user', }, }, }); expect(getOptions(state, users, values)).toEqual([ gmChannel3WithProfiles, gmChannel2WithProfiles, gmChannel1WithProfiles, ]); state = mergeObjects(state, { views: { search: { modalSearch: 'qwertyasdf', }, }, }); expect(getOptions(state, users, values)).toEqual([]); }); test('should only return GMs with users matching the selected items', () => { const getOptions = makeGetOptions(); const user1 = { ...TestHelper.fakeUserWithId(), username: 'apple', }; const user2 = { ...TestHelper.fakeUserWithId(), username: 'banana', }; const user3 = { ...TestHelper.fakeUserWithId(), username: 'carrot', }; const gmChannel1 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, last_post_at: 1000, }; const gmChannel1WithProfiles = { ...gmChannel1, display_name: 'apple, carrot', profiles: [user1, user3], }; const gmChannel2 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, last_post_at: 2000, }; const gmChannel2WithProfiles = { ...gmChannel2, display_name: 'banana, carrot', profiles: [user2, user3], }; const state = mergeObjects(baseState, { entities: { channels: { channels: { [gmChannel1.id]: gmChannel1, [gmChannel2.id]: gmChannel2, }, channelsInTeam: { '': [gmChannel1.id, gmChannel2.id], }, }, users: { profiles: { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }, profilesInChannel: { [gmChannel1.id]: [user1.id, user3.id], [gmChannel2.id]: [user2.id, user3.id], }, }, }, }); const users = [ user1, user2, user3, ]; let values: OptionValue[] = []; // Results are sorted by last_post_at descending followed by DMs matching users expect(getOptions(state, users, values)).toEqual([ gmChannel2WithProfiles, gmChannel1WithProfiles, ]); values = [user1] as OptionValue[]; expect(getOptions(state, users, values)).toEqual([ gmChannel1WithProfiles, ]); values = [user2] as OptionValue[]; expect(getOptions(state, users, values)).toEqual([ gmChannel2WithProfiles, ]); values = [user3] as OptionValue[]; expect(getOptions(state, users, values)).toEqual([ gmChannel2WithProfiles, gmChannel1WithProfiles, ]); values = [user3, user2] as OptionValue[]; expect(getOptions(state, users, values)).toEqual([ gmChannel2WithProfiles, ]); }); test('should return users without DMs as long as either there are no recents or a search term is being used', () => { const getOptions = makeGetOptions(); const user1 = { ...TestHelper.fakeUserWithId(), username: 'apple', }; const user2 = { ...TestHelper.fakeUserWithId(), username: 'banana', }; const user3 = { ...TestHelper.fakeUserWithId(), username: 'carrot', }; const dm1 = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, name: ChannelUtils.getDirectChannelName(currentUserId, user1.id), last_post_at: 2000, }; const users = [ user1, user2, user3, ]; const values: OptionValue[] = []; let state = mergeObjects(baseState, { users: { profiles: { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }, }, }); // No recent DMs exist, so show all the users expect(getOptions(state, users, values)).toEqual([ {...user1, last_post_at: 0}, {...user2, last_post_at: 0}, {...user3, last_post_at: 0}, ]); state = mergeObjects(state, { entities: { channels: { channels: { [dm1.id]: dm1, }, channelsInTeam: { '': [dm1.id], }, }, users: { profilesInChannel: { [dm1.id]: [user1.id], }, }, }, }); // Now a recent DM exists, so only show that expect(getOptions(state, users, values)).toEqual([ {...user1, last_post_at: 2000}, ]); state = mergeObjects(state, { views: { search: { modalSearch: 'asdfasdfasdf', }, }, }); // And now a search term has been entered, so show other users again. Note that users is expected to have been // filtered by the search term already even if it doesn't match at this point expect(getOptions(state, users, values)).toEqual([ {...user1, last_post_at: 2000}, {...user2, last_post_at: 0}, {...user3, last_post_at: 0}, ]); }); });
2,600
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels/list_item/list_item.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {General} from 'mattermost-redux/constants'; import ListItem from './list_item'; import type {Props} from './list_item'; import type {OptionValue} from '../types'; describe('ListItem', () => { const baseProps: Props = { isMobileView: false, isSelected: false, add: jest.fn(), select: jest.fn(), option: {} as OptionValue, }; test('should match snapshot when rendering user', () => { const user = { id: 'user_id_1', username: 'username1', last_post_at: 0, } as OptionValue; const wrapper = shallow( <ListItem {...baseProps} option={user} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when rendering GroupChannel', () => { const channel = { id: 'channel_id_1', type: General.GM_CHANNEL, display_name: 'user1, user2, user3', last_post_at: 0, profiles: [ { id: 'user_id_1', username: 'user1', }, { id: 'user_id_2', username: 'user2', }, { id: 'user_id_3', username: 'user3', }, ], } as OptionValue; const wrapper = shallow( <ListItem {...baseProps} option={channel} />, ); expect(wrapper).toMatchSnapshot(); }); });
2,602
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels/list_item
petrpan-code/mattermost/mattermost/webapp/channels/src/components/more_direct_channels/list_item/__snapshots__/list_item.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ListItem should match snapshot when rendering GroupChannel 1`] = ` <div className="more-modal__row clickable" onClick={[Function]} onMouseEnter={[Function]} > <GMDetails option={ Object { "display_name": "user1, user2, user3", "id": "channel_id_1", "last_post_at": 0, "profiles": Array [ Object { "id": "user_id_1", "username": "user1", }, Object { "id": "user_id_2", "username": "user2", }, Object { "id": "user_id_3", "username": "user3", }, ], "type": "G", } } /> <div className="more-modal__actions" > <div className="more-modal__actions--round" > <AddIcon /> </div> </div> </div> `; exports[`ListItem should match snapshot when rendering user 1`] = ` <div className="more-modal__row clickable" onClick={[Function]} onMouseEnter={[Function]} > <Connect(UserDetails) option={ Object { "id": "user_id_1", "last_post_at": 0, "username": "username1", } } /> <div className="more-modal__actions" > <div className="more-modal__actions--round" > <AddIcon /> </div> </div> </div> `;
2,605
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/msg_typing/actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {getMissingProfilesByIds, getStatusesByIds} from 'mattermost-redux/actions/users'; import {General, WebsocketEvents} from 'mattermost-redux/constants'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import configureStore from 'tests/test_store'; import {userStartedTyping} from './actions'; jest.mock('mattermost-redux/actions/users', () => ({ getMissingProfilesByIds: jest.fn(() => ({type: 'GET_MISSING_PROFILES_BY_IDS'})), getStatusesByIds: jest.fn(() => ({type: 'GET_STATUSES_BY_IDS'})), })); describe('handleUserTypingEvent', () => { const initialState = { entities: { general: { config: {}, }, users: { currentUserId: 'user', statuses: {}, users: {}, }, }, }; const userId = 'otheruser'; const channelId = 'channel'; const rootId = 'root'; test('should dispatch a TYPING event', () => { const store = configureStore(initialState); store.dispatch(userStartedTyping(userId, channelId, rootId, Date.now())); expect(store.getActions().find((action) => action.type === WebsocketEvents.TYPING)).toMatchObject({ type: WebsocketEvents.TYPING, data: { id: channelId + rootId, userId, }, }); }); test('should possibly load missing users and not get again the state', () => { const store = configureStore(initialState); store.dispatch(userStartedTyping(userId, channelId, rootId, Date.now())); expect(getMissingProfilesByIds).toHaveBeenCalledWith([userId]); expect(getStatusesByIds).not.toHaveBeenCalled(); }); test('should load statuses for users that are not online but are in the store', async () => { const state = mergeObjects(initialState, { entities: { users: { profiles: { otheruser: { id: 'otheruser', roles: 'system_user', }, }, statuses: { otheruser: General.AWAY, }, }, }, }); const store = configureStore(state); store.dispatch(userStartedTyping(userId, channelId, rootId, Date.now())); // Wait for side effects to resolve await Promise.resolve(); expect(getStatusesByIds).toHaveBeenCalled(); }); test('should not load statuses for users that are online', async () => { const state = mergeObjects(initialState, { entities: { users: { statuses: { otheruser: General.ONLINE, }, }, }, }); const store = configureStore(state); store.dispatch(userStartedTyping(userId, channelId, rootId, Date.now())); // Wait for side effects to resolve await Promise.resolve(); expect(getStatusesByIds).not.toHaveBeenCalled(); }); });
2,608
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/msg_typing/msg_typing.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import MsgTyping from 'components/msg_typing/msg_typing'; describe('components/MsgTyping', () => { const baseProps = { typingUsers: [], channelId: 'test', postId: '', userStartedTyping: jest.fn(), userStoppedTyping: jest.fn(), }; test('should match snapshot, on nobody typing', () => { const wrapper = shallow(<MsgTyping {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on one user typing', () => { const typingUsers = ['test.user']; const props = {...baseProps, typingUsers}; const wrapper = shallow(<MsgTyping {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on multiple users typing', () => { const typingUsers = ['test.user', 'other.test.user', 'another.user']; const props = {...baseProps, typingUsers}; const wrapper = shallow(<MsgTyping {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
2,610
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/msg_typing
petrpan-code/mattermost/mattermost/webapp/channels/src/components/msg_typing/__snapshots__/msg_typing.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MsgTyping should match snapshot, on multiple users typing 1`] = ` <span className="msg-typing" > <MemoizedFormattedMessage defaultMessage="{users} and {last} are typing..." id="msg_typing.areTyping" values={ Object { "last": "another.user", "users": "test.user, other.test.user", } } /> </span> `; exports[`components/MsgTyping should match snapshot, on nobody typing 1`] = ` <span className="msg-typing" /> `; exports[`components/MsgTyping should match snapshot, on one user typing 1`] = ` <span className="msg-typing" > <MemoizedFormattedMessage defaultMessage="{user} is typing..." id="msg_typing.isTyping" values={ Object { "user": "test.user", } } /> </span> `;
2,611
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/multiselect/multiselect.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import MultiSelect from './multiselect'; import type {Value} from './multiselect'; import MultiSelectList from './multiselect_list'; import type {Props as MultiSelectProps} from './multiselect_list'; const element = () => <div/>; describe('components/multiselect/multiselect', () => { const totalCount = 8; const optionsNumber = 8; const users = []; for (let i = 0; i < optionsNumber; i++) { users.push({id: `${i}`, label: `${i}`, value: `${i}`}); } const baseProps = { ariaLabelRenderer: element as any, handleAdd: jest.fn(), handleDelete: jest.fn(), handleInput: jest.fn(), handleSubmit: jest.fn(), optionRenderer: element, options: users, perPage: 5, saving: false, totalCount, users, valueRenderer: element as any, values: [{id: 'id', label: 'label', value: 'value'}], }; test('should match snapshot', () => { const wrapper = shallow( <MultiSelect {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for page 2', () => { const wrapper = shallow( <MultiSelect {...baseProps}/>, ); wrapper.find('.filter-control__next').simulate('click'); wrapper.update(); expect(wrapper.state('page')).toEqual(1); expect(wrapper).toMatchSnapshot(); }); test('MultiSelectList should match state on next page', () => { const renderOption: MultiSelectProps<Value>['optionRenderer'] = (option, isSelected, onAdd, onMouseMove) => { return ( <p key={option.id} ref={isSelected ? 'selected' : option.id} onClick={() => onAdd(option)} onMouseMove={() => onMouseMove(option)} > {option.id} </p> ); }; const renderValue = (props: {data: {value: unknown}}) => { return props.data.value; }; const wrapper = mountWithIntl( <MultiSelect {...baseProps} optionRenderer={renderOption} valueRenderer={renderValue} />, ); expect(wrapper.find(MultiSelectList).state('selected')).toEqual(-1); wrapper.find('.filter-control__next').simulate('click'); expect(wrapper.find(MultiSelectList).state('selected')).toEqual(0); }); test('MultiSelectList should match snapshot when custom no option message is defined', () => { const customNoOptionsMessage = ( <div className='custom-no-options-message'> <span>{'No matches found'}</span> </div> ); const wrapper = shallow( <MultiSelect {...baseProps} customNoOptionsMessage={customNoOptionsMessage} />, ); expect(wrapper).toMatchSnapshot(); }); test('Back button should be customizable', () => { const handleBackButtonClick = jest.fn(); const wrapper = mountWithIntl( <MultiSelect {...baseProps} backButtonClick={handleBackButtonClick} backButtonText='Cancel' backButtonClass='tertiary-button' saveButtonPosition='bottom' />, ); const backButton = wrapper.find('div.multi-select__footer button.tertiary-button'); backButton.simulate('click'); expect(backButton).toHaveLength(1); expect(handleBackButtonClick).toHaveBeenCalled(); }); });
2,613
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/multiselect/multiselect_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Value} from './multiselect'; import MultiSelectList from './multiselect_list'; import type {Props as MultiSelectProps} from './multiselect_list'; const element = () => <div/>; describe('components/multiselect/multiselect', () => { const optionsNumber = 8; const users = []; for (let i = 0; i < optionsNumber; i++) { users.push({id: `${i}`, label: `${i}`, value: `${i}`}); } const selectedItemRef = { current: { getBoundingClientRect: jest.fn(() => ({ bottom: 100, top: 50, })) as any, scrollIntoView: jest.fn(), }, } as any; const baseProps = { ariaLabelRenderer: element as any, loading: false, onAdd: jest.fn(), onPageChange: jest.fn(), onSelect: jest.fn(), optionRenderer: element, selectedItemRef, options: users, perPage: 5, page: 1, }; test('MultiSelectList should have selected item scrollIntoView to align at bottom of list', () => { const renderOption: MultiSelectProps<Value>['optionRenderer'] = (option, isSelected, onAdd, onMouseMove) => { return ( <p key={option.id} ref={isSelected ? selectedItemRef : option.id} onClick={() => onAdd(option)} onMouseMove={() => onMouseMove(option)} > {option.id} </p> ); }; const wrapper = shallow( <MultiSelectList {...baseProps} optionRenderer={renderOption} />, ); (wrapper.instance() as any).listRef = { current: { getBoundingClientRect: jest.fn(() => ({ bottom: 50, top: 50, })), }, } as any; wrapper.setState({selected: 1}); expect(selectedItemRef.current.scrollIntoView).toHaveBeenCalledWith(false); }); test('MultiSelectList should have selected item scrollIntoView to align at top of list', () => { const renderOption: MultiSelectProps<Value>['optionRenderer'] = (option, isSelected, onAdd, onMouseMove) => { return ( <p key={option.id} ref={isSelected ? selectedItemRef : option.id} onClick={() => onAdd(option)} onMouseMove={() => onMouseMove(option)} > {option.id} </p> ); }; const wrapper = shallow( <MultiSelectList {...baseProps} optionRenderer={renderOption} />, ); (wrapper.instance() as any).listRef = { current: { getBoundingClientRect: jest.fn(() => ({ bottom: 200, top: 60, })), }, } as any; wrapper.setState({selected: 1}); expect(selectedItemRef.current.scrollIntoView).toHaveBeenCalledWith(true); }); });
2,615
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/multiselect
petrpan-code/mattermost/mattermost/webapp/channels/src/components/multiselect/__snapshots__/multiselect.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/multiselect/multiselect MultiSelectList should match snapshot when custom no option message is defined 1`] = ` <Fragment> <div className="filtered-user-list" > <div className="filter-row filter-row--full" > <div className="multi-select__container react-select" > <StateManager className="" classNamePrefix="react-select-auto react-select" components={ Object { "IndicatorsContainer": [Function], "Menu": [Function], "MultiValueLabel": [Function], "MultiValueRemove": [Function], } } defaultInputValue="" defaultMenuIsOpen={false} defaultValue={null} getOptionLabel={[Function]} getOptionValue={[Function]} id="selectItems" inputValue="" isClearable={false} isMulti={true} menuIsOpen={false} onChange={[Function]} onInputChange={[Function]} onKeyDown={[Function]} openMenuOnFocus={false} options={ Array [ Object { "id": "0", "label": "0", "value": "0", }, Object { "id": "1", "label": "1", "value": "1", }, Object { "id": "2", "label": "2", "value": "2", }, Object { "id": "3", "label": "3", "value": "3", }, Object { "id": "4", "label": "4", "value": "4", }, Object { "id": "5", "label": "5", "value": "5", }, Object { "id": "6", "label": "6", "value": "6", }, Object { "id": "7", "label": "7", "value": "7", }, ] } styles={ Object { "container": [Function], } } value={ Array [ Object { "id": "id", "label": "label", "value": "value", }, ] } /> <SaveButton btnClass="" defaultMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Save" id="save_button.save" /> } disabled={false} extraClasses="" id="saveItems" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> </div> <div className="multi-select__help" id="multiSelectHelpMemberInfo" > <MemoizedFormattedMessage defaultMessage="{memberOptions, number} of {totalCount, number} members" id="multiselect.numMembers" values={ Object { "memberOptions": 5, "totalCount": 8, } } /> </div> </div> <MultiSelectList ariaLabelRenderer={[Function]} customNoOptionsMessage={ <div className="custom-no-options-message" > <span> No matches found </span> </div> } onAction={[Function]} onAdd={[Function]} onSelect={[Function]} optionRenderer={[Function]} options={ Array [ Object { "id": "0", "label": "0", "value": "0", }, Object { "id": "1", "label": "1", "value": "1", }, Object { "id": "2", "label": "2", "value": "2", }, Object { "id": "3", "label": "3", "value": "3", }, Object { "id": "4", "label": "4", "value": "4", }, ] } page={0} perPage={5} query="" /> <div className="multi-select__help" id="multiSelectMessageNote" /> <div className="filter-controls" > <button className="btn btn-tertiary filter-control filter-control__next" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Next" id="filtered_user_list.next" /> </button> </div> </div> </Fragment> `; exports[`components/multiselect/multiselect should match snapshot 1`] = ` <Fragment> <div className="filtered-user-list" > <div className="filter-row filter-row--full" > <div className="multi-select__container react-select" > <StateManager className="" classNamePrefix="react-select-auto react-select" components={ Object { "IndicatorsContainer": [Function], "Menu": [Function], "MultiValueLabel": [Function], "MultiValueRemove": [Function], } } defaultInputValue="" defaultMenuIsOpen={false} defaultValue={null} getOptionLabel={[Function]} getOptionValue={[Function]} id="selectItems" inputValue="" isClearable={false} isMulti={true} menuIsOpen={false} onChange={[Function]} onInputChange={[Function]} onKeyDown={[Function]} openMenuOnFocus={false} options={ Array [ Object { "id": "0", "label": "0", "value": "0", }, Object { "id": "1", "label": "1", "value": "1", }, Object { "id": "2", "label": "2", "value": "2", }, Object { "id": "3", "label": "3", "value": "3", }, Object { "id": "4", "label": "4", "value": "4", }, Object { "id": "5", "label": "5", "value": "5", }, Object { "id": "6", "label": "6", "value": "6", }, Object { "id": "7", "label": "7", "value": "7", }, ] } styles={ Object { "container": [Function], } } value={ Array [ Object { "id": "id", "label": "label", "value": "value", }, ] } /> <SaveButton btnClass="" defaultMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Save" id="save_button.save" /> } disabled={false} extraClasses="" id="saveItems" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> </div> <div className="multi-select__help" id="multiSelectHelpMemberInfo" > <MemoizedFormattedMessage defaultMessage="{memberOptions, number} of {totalCount, number} members" id="multiselect.numMembers" values={ Object { "memberOptions": 5, "totalCount": 8, } } /> </div> </div> <MultiSelectList ariaLabelRenderer={[Function]} onAction={[Function]} onAdd={[Function]} onSelect={[Function]} optionRenderer={[Function]} options={ Array [ Object { "id": "0", "label": "0", "value": "0", }, Object { "id": "1", "label": "1", "value": "1", }, Object { "id": "2", "label": "2", "value": "2", }, Object { "id": "3", "label": "3", "value": "3", }, Object { "id": "4", "label": "4", "value": "4", }, ] } page={0} perPage={5} query="" /> <div className="multi-select__help" id="multiSelectMessageNote" /> <div className="filter-controls" > <button className="btn btn-tertiary filter-control filter-control__next" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Next" id="filtered_user_list.next" /> </button> </div> </div> </Fragment> `; exports[`components/multiselect/multiselect should match snapshot for page 2 1`] = ` <Fragment> <div className="filtered-user-list" > <div className="filter-row filter-row--full" > <div className="multi-select__container react-select" > <StateManager className="" classNamePrefix="react-select-auto react-select" components={ Object { "IndicatorsContainer": [Function], "Menu": [Function], "MultiValueLabel": [Function], "MultiValueRemove": [Function], } } defaultInputValue="" defaultMenuIsOpen={false} defaultValue={null} getOptionLabel={[Function]} getOptionValue={[Function]} id="selectItems" inputValue="" isClearable={false} isMulti={true} menuIsOpen={false} onChange={[Function]} onInputChange={[Function]} onKeyDown={[Function]} openMenuOnFocus={false} options={ Array [ Object { "id": "0", "label": "0", "value": "0", }, Object { "id": "1", "label": "1", "value": "1", }, Object { "id": "2", "label": "2", "value": "2", }, Object { "id": "3", "label": "3", "value": "3", }, Object { "id": "4", "label": "4", "value": "4", }, Object { "id": "5", "label": "5", "value": "5", }, Object { "id": "6", "label": "6", "value": "6", }, Object { "id": "7", "label": "7", "value": "7", }, ] } styles={ Object { "container": [Function], } } value={ Array [ Object { "id": "id", "label": "label", "value": "value", }, ] } /> <SaveButton btnClass="" defaultMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Save" id="save_button.save" /> } disabled={false} extraClasses="" id="saveItems" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> </div> <div className="multi-select__help" id="multiSelectHelpMemberInfo" > <MemoizedFormattedMessage defaultMessage="{memberOptions, number} of {totalCount, number} members" id="multiselect.numMembers" values={ Object { "memberOptions": 3, "totalCount": 8, } } /> </div> </div> <MultiSelectList ariaLabelRenderer={[Function]} onAction={[Function]} onAdd={[Function]} onSelect={[Function]} optionRenderer={[Function]} options={ Array [ Object { "id": "5", "label": "5", "value": "5", }, Object { "id": "6", "label": "6", "value": "6", }, Object { "id": "7", "label": "7", "value": "7", }, ] } page={1} perPage={5} query="" /> <div className="multi-select__help" id="multiSelectMessageNote" /> <div className="filter-controls" > <button className="btn btn-tertiary filter-control filter-control__prev" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Previous" id="filtered_user_list.prev" /> </button> </div> </div> </Fragment> `;
2,617
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/new_channel_modal/new_channel_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {act} from 'react-dom/test-utils'; import {createChannel} from 'mattermost-redux/actions/channels'; import Permissions from 'mattermost-redux/constants/permissions'; import { render, renderWithContext, screen, userEvent, waitFor, } from 'tests/react_testing_utils'; import {suitePluginIds} from 'utils/constants'; import {cleanUpUrlable} from 'utils/url'; import type {GlobalState} from 'types/store'; import NewChannelModal from './new_channel_modal'; jest.mock('mattermost-redux/actions/channels'); const mockDispatch = jest.fn(); let mockState: GlobalState; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); describe('components/new_channel_modal', () => { beforeEach(() => { mockState = { entities: { general: { config: {}, }, channels: { currentChannelId: 'current_channel_id', channels: { current_channel_id: { id: 'current_channel_id', display_name: 'Current channel', name: 'current_channel', }, }, roles: { current_channel_id: [ 'channel_user', 'channel_admin', ], }, }, teams: { currentTeamId: 'current_team_id', myMembers: { current_team_id: { roles: 'team_user team_admin', }, }, teams: { current_team_id: { id: 'current_team_id', description: 'Curent team description', name: 'current-team', }, }, }, preferences: { myPreferences: {}, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }, roles: { roles: { channel_admin: { permissions: [], }, channel_user: { permissions: [], }, team_admin: { permissions: [], }, team_user: { permissions: [ Permissions.CREATE_PRIVATE_CHANNEL, ], }, system_admin: { permissions: [ Permissions.CREATE_PUBLIC_CHANNEL, ], }, system_user: { permissions: [], }, }, }, }, plugins: { plugins: {focalboard: {id: suitePluginIds.focalboard}}, }, } as unknown as GlobalState; }); test('should match component state with given props', () => { render(<NewChannelModal/>); const heading = screen.getByRole('heading'); expect(heading).toBeInTheDocument(); expect(heading).toHaveAttribute('id', 'genericModalLabel'); expect(heading.parentElement).toHaveClass('GenericModal__header'); expect(heading).toHaveTextContent('Create a new channel'); const channelNameHeading = screen.getByText('Channel name'); expect(channelNameHeading).toBeInTheDocument(); expect(channelNameHeading).toHaveClass('Input_legend Input_legend___focus'); const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); expect(channelNameInput).toHaveAttribute('type', 'text'); expect(channelNameInput).toHaveAttribute('name', 'new-channel-modal-name'); expect(channelNameInput).toHaveAttribute('id', 'input_new-channel-modal-name'); expect(channelNameInput).toHaveClass('Input form-control medium new-channel-modal-name-input Input__focus'); const editUrl = screen.getByText('Edit'); expect(editUrl).toBeInTheDocument(); expect(editUrl).toHaveClass('url-input-button-label'); expect(editUrl.parentElement).toHaveClass('url-input-button'); const publicChannelSvg = screen.getByLabelText('Globe Circle Solid Icon'); expect(publicChannelSvg).toBeInTheDocument(); const publicChannelHeading = screen.getByText('Public Channel'); expect(publicChannelHeading).toBeInTheDocument(); expect(publicChannelHeading.nextSibling).toHaveTextContent('Anyone can join'); const privateChannelSvg = screen.getByLabelText('Lock Circle Solid Icon'); expect(privateChannelSvg).toBeInTheDocument(); const privateChannelHeading = screen.getByText('Private Channel'); expect(privateChannelHeading).toBeInTheDocument(); expect(privateChannelHeading.nextSibling).toHaveTextContent('Only invited members'); const purposeTextArea = screen.getByPlaceholderText('Enter a purpose for this channel (optional)'); expect(purposeTextArea).toBeInTheDocument(); expect(purposeTextArea).toHaveClass('new-channel-modal-purpose-textarea'); const purposeDesc = screen.getByText('This will be displayed when browsing for channels.'); expect(purposeDesc).toBeInTheDocument(); const cancelButton = screen.getByText('Cancel'); expect(cancelButton).toBeInTheDocument(); expect(cancelButton).toHaveClass('btn-tertiary'); const createChannelButton = screen.getByText('Create channel'); expect(createChannelButton).toBeInTheDocument(); expect(createChannelButton).toHaveClass('btn-primary'); expect(createChannelButton).toBeDisabled(); }); test('should handle display name change', () => { const value = 'Channel name'; render( <NewChannelModal/>, ); // Change display name const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, value); // Display name should have been updated expect(channelNameInput).toHaveAttribute('value', value); // URL should have been changed according to display name const urlInputLabel = screen.getByTestId('urlInputLabel'); expect(urlInputLabel).toHaveTextContent(cleanUpUrlable(value)); }); test('should handle url change', async () => { const value = 'Channel name'; const url = 'channel-name-new'; render( <NewChannelModal/>, ); // Change display name const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, value); const urlInputLabel = screen.getByTestId('urlInputLabel'); expect(urlInputLabel).toHaveTextContent(cleanUpUrlable(value)); // Change URL const editUrl = screen.getByText('Edit'); expect(editUrl).toBeInTheDocument(); userEvent.click(editUrl); const editUrlInput = screen.getByTestId('channelURLInput'); userEvent.clear(editUrlInput); userEvent.type(editUrlInput, url); const doneButton = screen.getByText('Done'); await waitFor(() => userEvent.click(doneButton), ); // URL should have been updated expect(screen.getByText(url, {exact: false})).toBeInTheDocument(); // Change display name again userEvent.type(channelNameInput, `${value} updated`); // URL should NOT be updated expect(screen.getByText(url, {exact: false})).toBeInTheDocument(); }); test('should handle type changes', () => { render( <NewChannelModal/>, ); // Change type to private const privateChannel = screen.getByText('Private Channel'); expect(privateChannel).toBeInTheDocument(); userEvent.click(privateChannel); // Type should have been updated to private expect(privateChannel.parentElement?.nextSibling?.firstChild).toHaveAttribute('aria-label', 'Check Circle Icon'); // Change type to public const publicChannel = screen.getByText('Public Channel'); expect(publicChannel).toBeInTheDocument(); userEvent.click(publicChannel); // Type should have been updated to public expect(publicChannel.parentElement?.nextSibling?.firstChild).toHaveAttribute('aria-label', 'Check Circle Icon'); }); test('should handle purpose changes', () => { const value = 'Purpose'; render( <NewChannelModal/>, ); // Change purpose const ChannelPurposeTextArea = screen.getByPlaceholderText('Enter a purpose for this channel (optional)'); expect(ChannelPurposeTextArea).toBeInTheDocument(); userEvent.click(ChannelPurposeTextArea); userEvent.type(ChannelPurposeTextArea, value); // Purpose should have been updated expect(ChannelPurposeTextArea).toHaveValue(value); }); test('should enable confirm button when having valid display name, url and type', () => { render( <NewChannelModal/>, ); // Confirm button should be disabled const createChannelButton = screen.getByText('Create channel'); expect(createChannelButton).toBeInTheDocument(); expect(createChannelButton).toBeDisabled(); // Change display name const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, 'Channel name'); // Change type to private const privateChannel = screen.getByText('Private Channel'); expect(privateChannel).toBeInTheDocument(); userEvent.click(privateChannel); // Confirm button should be enabled expect(createChannelButton).toBeEnabled(); }); test('should disable confirm button when display name in error', () => { render( <NewChannelModal/>, ); // Change display name const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, 'Channel name'); // Change type to private const privateChannel = screen.getByText('Private Channel'); expect(privateChannel).toBeInTheDocument(); userEvent.click(privateChannel); // Confirm button should be enabled const createChannelButton = screen.getByText('Create channel'); expect(createChannelButton).toBeEnabled(); // Change display name to invalid userEvent.clear(channelNameInput); // Confirm button should be disabled expect(createChannelButton).toBeDisabled(); }); test('should disable confirm button when url in error', () => { render( <NewChannelModal/>, ); // Change display name const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, 'Channel name'); // Change type to private const privateChannel = screen.getByText('Private Channel'); expect(privateChannel).toBeInTheDocument(); userEvent.click(privateChannel); // Confirm button should be enabled const createChannelButton = screen.getByText('Create channel'); expect(createChannelButton).toBeEnabled(); // Change url to invalid const editUrl = screen.getByText('Edit'); expect(editUrl).toBeInTheDocument(); userEvent.click(editUrl); const editUrlInput = screen.getByTestId('channelURLInput'); userEvent.clear(editUrlInput); userEvent.type(editUrlInput, 'c-'); // Confirm button should be disabled expect(createChannelButton).toBeDisabled(); }); test('should disable confirm button when server error', async () => { render( <NewChannelModal/>, ); // Confirm button should be disabled const createChannelButton = screen.getByText('Create channel'); expect(createChannelButton).toBeDisabled(); // Change display name const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, 'Channel name'); // Change type to private const privateChannel = screen.getByText('Private Channel'); expect(privateChannel).toBeInTheDocument(); userEvent.click(privateChannel); // Confirm button should be enabled expect(createChannelButton).toBeEnabled(); // Submit await act(async () => userEvent.click(createChannelButton)); const serverError = screen.getByText('Something went wrong. Please try again.'); expect(serverError).toBeInTheDocument(); expect(createChannelButton).toBeDisabled(); }); test('should request team creation on submit', async () => { const name = 'Channel name'; renderWithContext( <NewChannelModal/>, ); // Confirm button should be disabled const createChannelButton = screen.getByText('Create channel'); expect(createChannelButton).toBeDisabled(); // Enter data const channelNameInput = screen.getByPlaceholderText('Enter a name for your new channel'); expect(channelNameInput).toBeInTheDocument(); expect(channelNameInput).toHaveAttribute('value', ''); userEvent.type(channelNameInput, name); // Display name should be updated expect(channelNameInput).toHaveValue(name); // Confirm button should be enabled expect(createChannelButton).toBeEnabled(); // Submit await act(async () => { userEvent.click(createChannelButton); }); // Request should be sent expect(createChannel).toHaveBeenCalledWith({ create_at: 0, creator_id: '', delete_at: 0, display_name: name, group_constrained: false, header: '', id: '', last_post_at: 0, last_root_post_at: 0, name: 'channel-name', purpose: '', scheme_id: '', team_id: 'current_team_id', type: 'O', update_at: 0, }, ''); }); });
2,624
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/no_results_indicator/no_results_indicator.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import NoResultsIndicator from 'components/no_results_indicator/no_results_indicator'; import {NoResultsVariant, NoResultsLayout} from './types'; describe('components/no_results_indicator', () => { test('should match snapshot with default props', () => { const wrapper = shallow( <NoResultsIndicator/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with variant ChannelSearch', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} variant={NoResultsVariant.ChannelSearch} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with variant Mentions', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} variant={NoResultsVariant.Mentions} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with variant FlaggedPosts', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} variant={NoResultsVariant.FlaggedPosts} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with variant PinnedPosts', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} variant={NoResultsVariant.PinnedPosts} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with variant ChannelFiles', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} variant={NoResultsVariant.ChannelFiles} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with variant ChannelFilesFiltered', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} variant={NoResultsVariant.ChannelFilesFiltered} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when expanded', () => { const wrapper = shallow( <NoResultsIndicator variant={NoResultsVariant.Search} expanded={true} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with horizontal layout', () => { const wrapper = shallow( <NoResultsIndicator iconGraphic={<div>{'Test'}</div>} title={'Test'} subtitle={'Subtitle'} layout={NoResultsLayout.Horizontal} />, ); expect(wrapper).toMatchSnapshot(); }); });
2,627
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/no_results_indicator
petrpan-code/mattermost/mattermost/webapp/channels/src/components/no_results_indicator/__snapshots__/no_results_indicator.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/no_results_indicator should match snapshot when expanded 1`] = ` <div className="no-results__holder" > <div className="no-results__wrapper" > <div className="no-results__variant-wrapper" > <SearchSVG className="no-results__icon" /> </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.search.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.search.subtitle" /> </div> </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with default props 1`] = ` <div className="no-results__wrapper" > <div className="no-results__text-container" /> </div> `; exports[`components/no_results_indicator should match snapshot with horizontal layout 1`] = ` <div className="no-results__wrapper horizontal-layout" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > Test </h3> <div className="no-results__subtitle" > Subtitle </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with variant ChannelFiles 1`] = ` <div className="no-results__wrapper" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.channel_files.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.channel_files.subtitle" /> </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with variant ChannelFilesFiltered 1`] = ` <div className="no-results__wrapper" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.channel_files_filtered.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.channel_files_filtered.subtitle" /> </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with variant ChannelSearch 1`] = ` <div className="no-results__wrapper" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.channel_search.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.channel_search.subtitle" /> </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with variant FlaggedPosts 1`] = ` <div className="no-results__wrapper" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.flagged_posts.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.flagged_posts.subtitle" /> </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with variant Mentions 1`] = ` <div className="no-results__wrapper" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.mentions.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.mentions.subtitle" /> </div> </div> </div> `; exports[`components/no_results_indicator should match snapshot with variant PinnedPosts 1`] = ` <div className="no-results__wrapper" > <div> Test </div> <div className="no-results__text-container" > <h3 className="no-results__title" > <MemoizedFormattedMessage id="no_results.pinned_messages.title" /> </h3> <div className="no-results__subtitle" > <MemoizedFormattedMessage id="no_results.pinned_messages.subtitle" /> </div> </div> </div> `;
2,632
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/notify_counts/notify_counts.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import * as ChannelSelectors from 'mattermost-redux/selectors/entities/channels'; import {mockStore} from 'tests/test_store'; import NotifyCounts from './'; describe('components/notify_counts', () => { const getUnreadStatusInCurrentTeam = jest.spyOn(ChannelSelectors, 'getUnreadStatusInCurrentTeam'); test('should show unread mention count', () => { getUnreadStatusInCurrentTeam.mockReturnValue(22); const {mountOptions} = mockStore(); const wrapper = mount(<NotifyCounts/>, mountOptions); expect(wrapper.find('.badge-notify').text()).toBe('22'); }); test('should show unread messages', () => { getUnreadStatusInCurrentTeam.mockReturnValue(true); const {mountOptions} = mockStore(); const wrapper = mount(<NotifyCounts/>, mountOptions); expect(wrapper.find('.badge-notify').text()).toBe('•'); }); test('should show not show unread indicator', () => { getUnreadStatusInCurrentTeam.mockReturnValue(false); const {mountOptions} = mockStore(); const wrapper = mount(<NotifyCounts/>, mountOptions); expect(wrapper.html()).toBe(''); }); });
2,637
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/onboarding_tasklist/onboarding_tasklist_completed.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import Completed from './onboarding_tasklist_completed'; let mockState: any; const mockDispatch = jest.fn(); const dismissMockFn = jest.fn(); jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); describe('components/onboarding_tasklist/onboarding_tasklist_completed.tsx', () => { const props = { dismissAction: dismissMockFn, isCurrentUserSystemAdmin: true, isFirstAdmin: true, }; beforeEach(() => { mockState = { entities: { admin: { prevTrialLicense: { IsLicensed: 'false', }, }, general: { license: { IsLicensed: 'false', }, }, cloud: { subscription: { product_id: 'prod_professional', is_free_trial: 'false', trial_end_at: 1, }, }, }, }; }); afterEach(() => { jest.restoreAllMocks(); }); test('should match snapshot', () => { const wrapper = shallow(<Completed {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('finds the completed subtitle', () => { const wrapper = shallow(<Completed {...props}/>); expect(wrapper.find('.completed-subtitle')).toHaveLength(1); }); test('displays the no thanks option to close the onboarding list', () => { const wrapper = shallow(<Completed {...props}/>); const noThanksLink = wrapper.find('.no-thanks-link'); expect(noThanksLink).toHaveLength(1); // calls the dissmiss function on click noThanksLink.simulate('click'); expect(dismissMockFn).toHaveBeenCalledTimes(1); }); });
2,641
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/onboarding_tasklist
petrpan-code/mattermost/mattermost/webapp/channels/src/components/onboarding_tasklist/__snapshots__/onboarding_tasklist_completed.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/onboarding_tasklist/onboarding_tasklist_completed.tsx should match snapshot 1`] = ` <Fragment> <CSSTransition classNames="fade" in={true} timeout={150} > <CompletedWrapper> <img alt="completed tasks image" src={null} /> <h2> <MemoizedFormattedMessage defaultMessage="Well done. You’ve completed all of the tasks!" id="onboardingTask.checklist.completed_title" /> </h2> <span className="completed-subtitle" > <MemoizedFormattedMessage defaultMessage="We hope Mattermost is more familiar now." id="onboardingTask.checklist.completed_subtitle" /> </span> <span className="start-trial-text" > <MemoizedFormattedMessage defaultMessage="Interested in our higher-security features?" id="onboardingTask.checklist.higher_security_features" /> <br /> <MemoizedFormattedMessage defaultMessage="Start your free Enterprise trial now!" id="onboardingTask.checklist.start_enterprise_now" /> </span> <StartTrialBtn message="Start free 30-day trial" onClick={[MockFunction]} telemetryId="start_trial_from_onboarding_completed_task" /> <button className="no-thanks-link style-link" onClick={[MockFunction]} > <MemoizedFormattedMessage defaultMessage="No, thanks" id="onboardingTask.checklist.no_thanks" /> </button> <div className="download-apps" > <span> <MemoizedFormattedMessage defaultMessage="Now that you’re all set up, <link>download our apps.</link>!" id="onboardingTask.checklist.downloads" values={ Object { "link": [Function], } } /> </span> </div> <div className="disclaimer" > <span> <MemoizedFormattedMessage defaultMessage="By clicking “Start trial”, I agree to the <linkEvaluation>Mattermost Software and Services License Agreement</linkEvaluation>, <linkPrivacy>privacy policy</linkPrivacy> and receiving product emails." id="onboardingTask.checklist.disclaimer" values={ Object { "linkEvaluation": [Function], "linkPrivacy": [Function], } } /> </span> </div> </CompletedWrapper> </CSSTransition> </Fragment> `;
2,645
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/onboarding_tasks/onboarding_tasks_manager.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import configureStore from 'store'; import {useTasksList} from './onboarding_tasks_manager'; const WrapperComponent = (): JSX.Element => { const taskList = useTasksList(); return ( <ul> {taskList.map((task: string) => <li key={task}>{task}</li>)} </ul> ); }; describe('onboarding tasks manager', () => { const user1 = 'user1'; const user2 = 'user2'; const user3 = 'user3'; const initialState = { entities: { admin: { prevTrialLicense: { IsLicensed: 'false', }, }, general: { license: { IsLicensed: 'false', }, }, preferences: {}, users: { currentUserId: user1, profiles: { [user1]: {id: user1, username: user1, roles: 'system_admin'}, [user2]: {id: user2, username: user2, roles: 'system_user'}, [user3]: {id: user3, username: user3, roles: 'system_guest'}, }, }, roles: {}, }, }; it('Places all the elements (6 ignoring plugins) when user is first admin or admin', () => { const store = configureStore(initialState); const wrapper = mount( <Provider store={store}> <WrapperComponent/> </Provider>, ); expect(wrapper.find('li')).toHaveLength(6); // find the visit system console and start_trial expect(wrapper.findWhere((node) => node.key() === 'visit_system_console')).toHaveLength(1); expect(wrapper.findWhere((node) => node.key() === 'start_trial')).toHaveLength(1); }); it('Removes start_trial and visit_system_console when user is end user', () => { const endUserState = {...initialState, entities: {...initialState.entities, users: {...initialState.entities.users, currentUserId: user2}}}; const store = configureStore(endUserState); const wrapper = mount( <Provider store={store}> <WrapperComponent/> </Provider>, ); expect(wrapper.find('li')).toHaveLength(4); // verify visit_system_console and start_trial were removed expect(wrapper.findWhere((node) => node.key() === 'visit_system_console')).toHaveLength(0); expect(wrapper.findWhere((node) => node.key() === 'start_trial')).toHaveLength(0); }); it('Removes invite people task item when user is GUEST user', () => { const endUserState = {...initialState, entities: {...initialState.entities, users: {...initialState.entities.users, currentUserId: user3}}}; const store = configureStore(endUserState); const wrapper = mount( <Provider store={store}> <WrapperComponent/> </Provider>, ); expect(wrapper.find('li')).toHaveLength(3); // verify visit_system_console and start_trial were removed expect(wrapper.findWhere((node) => node.key() === 'invite_people')).toHaveLength(0); }); });
2,654
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/password_reset_form/password_reset_form.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import PasswordResetForm from './password_reset_form'; describe('components/PasswordResetForm', () => { const baseProps = { location: { search: '', }, siteName: 'Mattermost', actions: { resetUserPassword: jest.fn().mockResolvedValue({data: true}), }, }; it('should match snapshot', () => { const wrapper = shallow(<PasswordResetForm {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should call the resetUserPassword() action on submit', () => { const props = { ...baseProps, location: { search: '?token=TOKEN', }, }; const wrapper = mountWithIntl(<PasswordResetForm {...props}/>); (wrapper.find('input[type="password"]').first().instance() as unknown as HTMLInputElement).value = 'PASSWORD'; wrapper.find('form').simulate('submit', {preventDefault: () => {}}); expect(props.actions.resetUserPassword).toHaveBeenCalledWith('TOKEN', 'PASSWORD'); }); });
2,656
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/password_reset_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/password_reset_form/__snapshots__/password_reset_form.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/PasswordResetForm should match snapshot 1`] = ` <div className="col-sm-12" > <div className="signup-team__container" > <MemoizedFormattedMessage defaultMessage="Password Reset" id="password_form.title" tagName="h1" /> <form onSubmit={[Function]} > <p> <MemoizedFormattedMessage defaultMessage="Enter a new password for your {siteName} account." id="password_form.enter" values={ Object { "siteName": "Mattermost", } } /> </p> <div className="form-group" > <input autoFocus={true} className="form-control" id="resetPasswordInput" name="password" placeholder="Password" spellCheck="false" type="password" /> </div> <button className="btn btn-primary" id="resetPasswordButton" type="submit" > <MemoizedFormattedMessage defaultMessage="Change my password" id="password_form.change" /> </button> </form> </div> </div> `;
2,658
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/password_reset_send_link/password_reset_send_link.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {MemoryRouter} from 'react-router-dom'; import {mountWithIntl, type MockIntl} from 'tests/helpers/intl-test-helper'; import {PasswordResetSendLink} from './password_reset_send_link'; describe('components/PasswordResetSendLink', () => { const baseProps = { actions: { sendPasswordResetEmail: jest.fn().mockResolvedValue({data: true}), }, intl: { formatMessage: jest.fn(), } as MockIntl, }; it('should match snapshot', () => { const wrapper = shallow(<PasswordResetSendLink {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should calls sendPasswordResetEmail() action on submit', () => { const props = {...baseProps}; const wrapper = mountWithIntl( <MemoryRouter> <PasswordResetSendLink {...props}/> </MemoryRouter>, ).children().children(); (wrapper.instance() as PasswordResetSendLink).emailInput.current!.value = '[email protected]'; wrapper.find('form').simulate('submit', {preventDefault: () => {}}); expect(props.actions.sendPasswordResetEmail).toHaveBeenCalledWith('[email protected]'); }); });
2,660
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/password_reset_send_link
petrpan-code/mattermost/mattermost/webapp/channels/src/components/password_reset_send_link/__snapshots__/password_reset_send_link.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/PasswordResetSendLink should match snapshot 1`] = ` <div> <BackButton url="/" /> <div className="col-sm-12" > <div className="signup-team__container" > <MemoizedFormattedMessage defaultMessage="Password Reset" id="password_send.title" tagName="h1" /> <form onSubmit={[Function]} > <p> <MemoizedFormattedMessage defaultMessage="To reset your password, enter the email address you used to sign up" id="password_send.description" /> </p> <div className="form-group" > <input autoFocus={true} className="form-control" id="passwordResetEmailInput" name="email" spellCheck="false" type="email" /> </div> <button className="btn btn-primary" id="passwordResetButton" type="submit" > <MemoizedFormattedMessage defaultMessage="Reset my password" id="password_send.reset" /> </button> </form> </div> </div> </div> `;
2,673
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/payment_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/payment_form/gather_intent/gather_intent.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as reactRedux from 'react-redux'; import { act, fireEvent, renderWithContext, screen, } from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import type {GatherIntentProps} from './gather_intent'; import {GatherIntent} from './gather_intent'; import type {GatherIntentModalProps} from './gather_intent_modal'; const DummyModal = ({onClose, onSave}: GatherIntentModalProps) => { return ( <> <button id='closeIcon' className='icon icon-close' aria-label='Close' title='Close' onClick={onClose} /> <p>{'Body'}</p> <button onClick={() => { onSave({ach: true, other: false, wire: true}); }} type='button' > {'Test'} </button> </> ); }; describe('components/gather_intent/gather_intent.tsx', () => { const gatherIntentText = 'gatherIntentText'; const useDispatchMock = jest.spyOn(reactRedux, 'useDispatch'); const initialState = { entities: { cloud: { customer: TestHelper.getCloudCustomerMock(), }, }, }; const baseProps: GatherIntentProps = { modalComponent: DummyModal as any, gatherIntentText, typeGatherIntent: 'monthlySubscription', }; it('should display modal if the user click on the modal opener', () => { renderWithContext( <GatherIntent {...baseProps}/>, initialState, ); fireEvent.click(screen.getByText(gatherIntentText)); expect(screen.getByText('Body')).toBeInTheDocument(); }); it('should display the modal opener after close the modal', () => { renderWithContext( <GatherIntent {...baseProps}/>, initialState, ); fireEvent.click(screen.getByText(gatherIntentText)); fireEvent.click(screen.getByLabelText('Close')); expect(screen.queryByText('Body')).not.toBeInTheDocument(); }); it('should render the submitted modal after save the configuration', async () => { useDispatchMock.mockReturnValue(jest.fn().mockImplementation(() => new Promise((resolve) => { resolve({}); }))); renderWithContext( <GatherIntent {...baseProps}/>, initialState, ); fireEvent.click(screen.getByText(gatherIntentText)); await act(async () => { fireEvent.click(screen.getByText('Test')); }); expect(screen.queryByText('Thanks for sharing feedback!')).toBeInTheDocument(); }); it('should render the submitted modal after save the configuration and reopening the modal', async () => { useDispatchMock.mockReturnValue(jest.fn().mockImplementation(() => new Promise((resolve) => { resolve({}); }))); renderWithContext( <GatherIntent {...baseProps}/>, initialState, ); fireEvent.click(screen.getByText(gatherIntentText)); await act(async () => { fireEvent.click(screen.getByText('Test')); }); fireEvent.click(screen.getByText('Done')); fireEvent.click(screen.getByText(gatherIntentText)); expect(screen.queryByText('Thanks for sharing feedback!')).toBeInTheDocument(); }); it('should render the submitted modal when the user has a feedback recorded', async () => { useDispatchMock.mockReturnValue(jest.fn().mockImplementation(() => new Promise((resolve) => { resolve({}); }))); const newState = JSON.parse(JSON.stringify(initialState)); newState.entities.cloud.customer = { ...newState.entities.cloud.customer, monthly_subscription_alt_payment_method: 'Dummy feedback', }; renderWithContext( <GatherIntent {...baseProps}/>, newState, ); fireEvent.click(screen.getByText(gatherIntentText)); expect(screen.queryByText('Thanks for sharing feedback!')).toBeInTheDocument(); }); });
2,675
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/payment_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/payment_form/gather_intent/gather_intent_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {fireEvent, renderWithContext, screen} from 'tests/react_testing_utils'; import {GatherIntentModal} from './gather_intent_modal'; import type {GatherIntentModalProps} from './gather_intent_modal'; describe('components/gather_intent/gather_intent_modal.tsx', () => { const baseProps: GatherIntentModalProps = { onClose: jest.fn(), onSave: jest.fn(), isSubmitting: false, showError: false, }; it('shouldn\'t be able to save the feedback if the user don\'t click on any option', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); expect(screen.queryByText('Save')).toBeDisabled(); }); it('shouldn\'t be able to save the feedback if the user only click in other and leave the input empty', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); fireEvent.click(screen.getByText('Other')); expect(screen.queryByText('Save')).toBeDisabled(); }); it('shouldn\'t be able to save the feedback if the user only click in other and write only white spaces in the input', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); fireEvent.click(screen.getByText('Other')); fireEvent.change(screen.getByPlaceholderText('Enter payment option here'), {target: {value: ' \n\t'}}); expect(screen.queryByText('Save')).toBeDisabled(); }); it('should be able to save the feedback if the user only click in other, leave the input empty and press other option', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); fireEvent.click(screen.getByText('Other')); fireEvent.click(screen.getByText('Wire')); expect(screen.queryByText('Save')).not.toHaveAttribute('disabled'); }); it('should be able save the feedback if the user click in Wire option', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); fireEvent.click(screen.getByText('Wire')); expect(screen.queryByText('Save')).not.toHaveAttribute('disabled'); }); it('should be able save the feedback if the user click in ACH option', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); fireEvent.click(screen.getByText('ACH')); expect(screen.queryByText('Save')).not.toHaveAttribute('disabled'); }); it('should be able save the feedback if the user click in other option and fill the option', () => { renderWithContext(<GatherIntentModal {...baseProps}/>); fireEvent.click(screen.getByText('Other')); fireEvent.change(screen.getByPlaceholderText('Enter payment option here'), {target: {value: 'Test'}}); expect(screen.queryByText('Save')).not.toBeDisabled(); }); });
2,682
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permalink_view/permalink_view.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ReactWrapper} from 'enzyme'; import {shallow} from 'enzyme'; import nock from 'nock'; import React from 'react'; import type {ComponentProps} from 'react'; import {act} from 'react-dom/test-utils'; import type {match} from 'react-router-dom'; import {getPostThread} from 'mattermost-redux/actions/posts'; import {Client4} from 'mattermost-redux/client'; import {Preferences} from 'mattermost-redux/constants'; import * as Channels from 'mattermost-redux/selectors/entities/channels'; import {focusPost} from 'components/permalink_view/actions'; import PermalinkView from 'components/permalink_view/permalink_view'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {getHistory} from 'utils/browser_history'; import {ErrorPageTypes} from 'utils/constants'; jest.mock('actions/channel_actions', () => ({ loadChannelsForCurrentUser: jest.fn(() => { return {type: 'MOCK_LOAD_CHANNELS_FOR_CURRENT_USER'}; }), })); jest.mock('actions/views/rhs.ts', () => ({ selectPostAndHighlight: jest.fn((post) => { return {type: 'MOCK_SELECT_POST_AND_HIGHLIGHT', args: [post]}; }), })); jest.mock('mattermost-redux/actions/posts', () => ({ getPostThread: jest.fn((postId) => { const post = {id: 'postid1', message: 'some message', channel_id: 'channelid1'}; const post2 = {id: 'postid2', message: 'some message', channel_id: 'channelid2'}; const replyPost1 = {id: 'replypostid1', message: 'some message', channel_id: 'channelid1', root_id: 'postid1'}; const dmPost = {id: 'dmpostid1', message: 'some message', channel_id: 'dmchannelid'}; const gmPost = {id: 'gmpostid1', message: 'some message', channel_id: 'gmchannelid'}; switch (postId) { case 'postid1': return {type: 'MOCK_GET_POST_THREAD', data: {posts: {replypostid1: replyPost1, postid1: post}, order: [post.id, replyPost1.id]}}; case 'postid2': return {type: 'MOCK_GET_POST_THREAD', data: {posts: {postid2: post2}, order: [post2.id]}}; case 'dmpostid1': return {type: 'MOCK_GET_POST_THREAD', data: {posts: {dmpostid1: dmPost}, order: [dmPost.id]}}; case 'gmpostid1': return {type: 'MOCK_GET_POST_THREAD', data: {posts: {gmpostid1: gmPost}, order: [gmPost.id]}}; case 'replypostid1': return {type: 'MOCK_GET_POST_THREAD', data: {posts: {replypostid1: replyPost1, postid1: post}, order: [post.id, replyPost1.id]}}; default: return {type: 'MOCK_GET_POST_THREAD'}; } }), })); jest.mock('mattermost-redux/actions/users', () => ({ getMissingProfilesByIds: (userIds: string[]) => ({type: 'MOCK_GET_MISSING_PROFILES', userIds}), })); jest.mock('mattermost-redux/actions/channels', () => ({ selectChannel: (...args: any) => ({type: 'MOCK_SELECT_CHANNEL', args}), joinChannel: (...args: any) => ({type: 'MOCK_JOIN_CHANNEL', args}), getChannelStats: (...args: any) => ({type: 'MOCK_GET_CHANNEL_STATS', args}), getChannel: jest.fn((channelId) => { switch (channelId) { case 'channelid2': return {type: 'MOCK_GET_CHANNEL', data: {id: 'channelid2', type: 'O', team_id: 'current_team_id'}}; default: return {type: 'MOCK_GET_CHANNEL', args: [channelId]}; } }), })); describe('components/PermalinkView', () => { const baseProps: ComponentProps<typeof PermalinkView> = { channelId: 'channel_id', match: {params: {postid: 'post_id'}} as match<{ postid: string }>, returnTo: 'return_to', teamName: 'team_name', actions: { focusPost: jest.fn(), }, currentUserId: 'current_user', }; test('should match snapshot', async () => { const wrapper = shallow( <PermalinkView {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should call baseProps.actions.focusPost on doPermalinkEvent', async () => { await act(async () => { mountWithIntl( <PermalinkView {...baseProps}/>, ); }); expect(baseProps.actions.focusPost).toHaveBeenCalledTimes(1); expect(baseProps.actions.focusPost).toBeCalledWith(baseProps.match.params.postid, baseProps.returnTo, baseProps.currentUserId); }); test('should call baseProps.actions.focusPost when postid changes', async () => { let wrapper: ReactWrapper<JSX.Element>; await act(async () => { wrapper = mountWithIntl( <PermalinkView {...baseProps}/>, ); }); const newPostid = `${baseProps.match.params.postid}_new`; await wrapper!.setProps({...baseProps, match: {params: {postid: newPostid}}} as any); expect(baseProps.actions.focusPost).toHaveBeenCalledTimes(2); expect(baseProps.actions.focusPost).toBeCalledWith(newPostid, baseProps.returnTo, baseProps.currentUserId); }); test('should match snapshot with archived channel', async () => { const props = {...baseProps, channelIsArchived: true}; let wrapper: ReactWrapper<any>; await act(async () => { wrapper = mountWithIntl( <PermalinkView {...props}/>, ); }); expect(wrapper!).toMatchSnapshot(); }); describe('actions', () => { const initialState = { entities: { general: {}, users: { currentUserId: 'current_user_id', profiles: { dmchannel: { id: 'dmchannel', username: 'otherUser', }, }, }, channels: { channels: { channelid1: {id: 'channelid1', name: 'channel1', type: 'O', team_id: 'current_team_id'}, dmchannelid: {id: 'dmchannelid', name: 'dmchannel__current_user_id', type: 'D', team_id: ''}, gmchannelid: {id: 'gmchannelid', name: 'gmchannel', type: 'G', team_id: ''}, }, myMembers: {channelid1: {channel_id: 'channelid1', user_id: 'current_user_id'}}, }, preferences: { myPreferences: {}, }, teams: { currentTeamId: 'current_team_id', teams: { current_team_id: { id: 'current_team_id', display_name: 'currentteam', name: 'currentteam', }, }, }, }, }; describe('focusPost', () => { test('should redirect to error page for DM channel not a member of', async () => { const testStore = await mockStore(initialState); await testStore.dispatch(focusPost('dmpostid1', undefined, baseProps.currentUserId)); expect(getPostThread).toHaveBeenCalledWith('dmpostid1'); expect(testStore.getActions()).toEqual([ {type: 'MOCK_GET_POST_THREAD', data: {posts: {dmpostid1: {id: 'dmpostid1', message: 'some message', channel_id: 'dmchannelid'}}, order: ['dmpostid1']}}, ]); expect(getHistory().replace).toHaveBeenCalledWith(`/error?type=${ErrorPageTypes.PERMALINK_NOT_FOUND}&returnTo=`); }); test('should redirect to error page for GM channel not a member of', async () => { const testStore = await mockStore(initialState); await testStore.dispatch(focusPost('gmpostid1', undefined, baseProps.currentUserId)); expect(getPostThread).toHaveBeenCalledWith('gmpostid1'); expect(testStore.getActions()).toEqual([ {type: 'MOCK_GET_POST_THREAD', data: {posts: {gmpostid1: {id: 'gmpostid1', message: 'some message', channel_id: 'gmchannelid'}}, order: ['gmpostid1']}}, ]); expect(getHistory().replace).toHaveBeenCalledWith(`/error?type=${ErrorPageTypes.PERMALINK_NOT_FOUND}&returnTo=`); }); test('should redirect to DM link with postId for permalink', async () => { const dateNowOrig = Date.now; Date.now = () => new Date(0).getMilliseconds(); const nextTick = () => new Promise((res) => process.nextTick(res)); TestHelper.initBasic(Client4); nock(Client4.getUsersRoute()). put('/current_user_id/preferences'). reply(200, {status: 'OK'}); const modifiedState = { entities: { ...initialState.entities, channels: { ...initialState.entities.channels, myMembers: { channelid1: {channel_id: 'channelid1', user_id: 'current_user_id'}, dmchannelid: {channel_id: 'dmchannelid', name: 'dmchannel', type: 'D', user_id: 'current_user_id'}, }, }, }, }; const testStore = mockStore(modifiedState); testStore.dispatch(focusPost('dmpostid1', undefined, baseProps.currentUserId)); await nextTick(); expect.assertions(3); expect(getPostThread).toHaveBeenCalledWith('dmpostid1'); expect(testStore.getActions()).toEqual([ {type: 'MOCK_GET_POST_THREAD', data: {posts: {dmpostid1: {id: 'dmpostid1', message: 'some message', channel_id: 'dmchannelid'}}, order: ['dmpostid1']}}, {type: 'MOCK_GET_MISSING_PROFILES', userIds: ['dmchannel']}, { type: 'RECEIVED_PREFERENCES', data: [ {user_id: 'current_user_id', category: Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, name: 'dmchannel', value: 'true'}, {user_id: 'current_user_id', category: Preferences.CATEGORY_CHANNEL_OPEN_TIME, name: 'dmchannelid', value: '0'}, ], }, {type: 'MOCK_SELECT_CHANNEL', args: ['dmchannelid']}, {type: 'RECEIVED_FOCUSED_POST', channelId: 'dmchannelid', data: 'dmpostid1'}, {type: 'MOCK_LOAD_CHANNELS_FOR_CURRENT_USER'}, {type: 'MOCK_GET_CHANNEL_STATS', args: ['dmchannelid']}, ]); expect(getHistory().replace).toHaveBeenCalledWith('/currentteam/messages/@otherUser/dmpostid1'); Date.now = dateNowOrig; TestHelper.tearDown(); }); test('should redirect to GM link with postId for permalink', async () => { const modifiedState = { entities: { ...initialState.entities, channels: { ...initialState.entities.channels, myMembers: { channelid1: {channel_id: 'channelid1', user_id: 'current_user_id'}, gmchannelid: {channel_id: 'gmchannelid', name: 'gmchannel', type: 'G', user_id: 'current_user_id'}, }, }, }, }; const testStore = await mockStore(modifiedState); await testStore.dispatch(focusPost('gmpostid1', undefined, baseProps.currentUserId)); expect(getPostThread).toHaveBeenCalledWith('gmpostid1'); expect(testStore.getActions()).toEqual([ {type: 'MOCK_GET_POST_THREAD', data: {posts: {gmpostid1: {id: 'gmpostid1', message: 'some message', channel_id: 'gmchannelid'}}, order: ['gmpostid1']}}, {type: 'MOCK_SELECT_CHANNEL', args: ['gmchannelid']}, {type: 'RECEIVED_FOCUSED_POST', channelId: 'gmchannelid', data: 'gmpostid1'}, {type: 'MOCK_LOAD_CHANNELS_FOR_CURRENT_USER'}, {type: 'MOCK_GET_CHANNEL_STATS', args: ['gmchannelid']}, ]); expect(getHistory().replace).toHaveBeenCalledWith('/currentteam/messages/gmchannel/gmpostid1'); }); test('should redirect to channel link with postId for permalink', async () => { const testStore = await mockStore(initialState); await testStore.dispatch(focusPost('postid1', undefined, baseProps.currentUserId)); expect(getPostThread).toHaveBeenCalledWith('postid1'); expect(testStore.getActions()).toEqual([ { type: 'MOCK_GET_POST_THREAD', data: { posts: { replypostid1: {id: 'replypostid1', message: 'some message', channel_id: 'channelid1', root_id: 'postid1'}, postid1: {id: 'postid1', message: 'some message', channel_id: 'channelid1'}, }, order: ['postid1', 'replypostid1'], }, }, {type: 'MOCK_SELECT_CHANNEL', args: ['channelid1']}, {type: 'RECEIVED_FOCUSED_POST', channelId: 'channelid1', data: 'postid1'}, {type: 'MOCK_LOAD_CHANNELS_FOR_CURRENT_USER'}, {type: 'MOCK_GET_CHANNEL_STATS', args: ['channelid1']}, ]); expect(getHistory().replace).toHaveBeenCalledWith('/currentteam/channels/channel1/postid1'); }); test('should not redirect to channel link with postId for a reply permalink when collapsedThreads enabled and option is set true', async () => { const newState = { entities: { ...initialState.entities, general: { config: { CollapsedThreads: 'default_on', }, }, }, }; jest.spyOn<typeof Channels, keyof typeof Channels>(Channels, 'getCurrentChannel').mockReturnValue({id: 'channelid1', name: 'channel1', type: 'O', team_id: 'current_team_id'}); const testStore = await mockStore(newState); await testStore.dispatch(focusPost('replypostid1', '#', initialState.entities.users.currentUserId, {skipRedirectReplyPermalink: true})); expect(getPostThread).toHaveBeenCalledWith('replypostid1'); expect(testStore.getActions()).toEqual([ { type: 'MOCK_GET_POST_THREAD', data: { posts: { replypostid1: {id: 'replypostid1', message: 'some message', channel_id: 'channelid1', root_id: 'postid1'}, postid1: {id: 'postid1', message: 'some message', channel_id: 'channelid1'}, }, order: ['postid1', 'replypostid1'], }, }, { type: 'MOCK_GET_POST_THREAD', data: { posts: { replypostid1: {id: 'replypostid1', message: 'some message', channel_id: 'channelid1', root_id: 'postid1'}, postid1: {id: 'postid1', message: 'some message', channel_id: 'channelid1'}, }, order: ['postid1', 'replypostid1'], }, }, {type: 'MOCK_SELECT_POST_AND_HIGHLIGHT', args: [{id: 'replypostid1', message: 'some message', channel_id: 'channelid1', root_id: 'postid1'}]}, {type: 'MOCK_LOAD_CHANNELS_FOR_CURRENT_USER'}, {type: 'MOCK_GET_CHANNEL_STATS', args: ['channelid1']}, ]); expect(getHistory().replace).not.toBeCalled(); }); }); }); });
2,684
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permalink_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permalink_view/__snapshots__/permalink_view.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/PermalinkView should match snapshot 1`] = ` <div className="app__content" id="app-content" /> `; exports[`components/PermalinkView should match snapshot with archived channel 1`] = ` <Memo(PermalinkView) actions={ Object { "focusPost": [MockFunction] { "calls": Array [ Array [ "post_id", "return_to", "current_user", ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, } } channelId="channel_id" channelIsArchived={true} currentUserId="current_user" match={ Object { "params": Object { "postid": "post_id", }, } } returnTo="return_to" teamName="team_name" > <div className="app__content" id="app-content" /> </Memo(PermalinkView)> `;
2,685
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/any_team_permission_gate/any_team_permission_gate.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import AnyTeamPermissionGate from 'components/permissions_gates/any_team_permission_gate'; import mockStore from 'tests/test_store'; describe('components/permissions_gates', () => { const state = { entities: { channels: { myMembers: { channel_id: {channel_id: 'channel_id', roles: 'channel_role'}, }, }, teams: { teams: { team_id: {id: 'team_id', delete_at: 0}, team_id2: {id: 'team_id2', delete_at: 0}, }, myMembers: { team_id: {team_id: 'team_id', roles: 'team_role'}, team_id2: {team_id: 'team_id2', roles: 'team_role2'}, }, }, users: { currentUserId: 'user_id', profiles: { user_id: { id: 'user_id', roles: 'system_role', }, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission']}, team_role: {permissions: ['test_team_permission']}, team_role2: {permissions: ['other_permission']}, channel_role: {permissions: ['test_channel_permission']}, }, }, }, }; const store = mockStore(state); describe('TeamPermissionGate', () => { test('should match snapshot when user have permission', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['test_team_permission']}> <p>{'Valid permission (shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have the permission in other team', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['other_permission']}> <p>{'Valid permission (shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have at least one of the permissions', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['test_team_permission', 'not_existing_permission']}> <p>{'Valid permission (shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['test_team_permission']} invert={true} > <p>{'Valid permission but inverted (not shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user not have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['invalid_permission']} invert={true} > <p>{'Invalid permission but inverted (shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have the permission in other team and use invert', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['other_permission']} invert={true} > <p>{'Valid permission but inverted (not shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user doesn\'t have permission', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['invalid_permission']} > <p>{'Invalid permission (not shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission system wide', () => { const wrapper = mount( <Provider store={store}> <AnyTeamPermissionGate permissions={['test_system_permission']} > <p>{'Valid permission (shown)'}</p> </AnyTeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); }); });
2,688
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/any_team_permission_gate
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/any_team_permission_gate/__snapshots__/any_team_permission_gate.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/permissions_gates TeamPermissionGate should match snapshot when user doesn't have permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) permissions={ Array [ "invalid_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={false} permissions={ Array [ "invalid_permission", ] } > <p /> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have at least one of the permissions 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) permissions={ Array [ "test_team_permission", "not_existing_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_team_permission", "not_existing_permission", ] } > <p> Valid permission (shown) </p> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) permissions={ Array [ "test_team_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_team_permission", ] } > <p> Valid permission (shown) </p> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) invert={true} permissions={ Array [ "test_team_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={true} invert={true} permissions={ Array [ "test_team_permission", ] } > <p /> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have permission system wide 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) permissions={ Array [ "test_system_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_system_permission", ] } > <p> Valid permission (shown) </p> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have the permission in other team 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) permissions={ Array [ "other_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={true} permissions={ Array [ "other_permission", ] } > <p> Valid permission (shown) </p> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have the permission in other team and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) invert={true} permissions={ Array [ "other_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={true} invert={true} permissions={ Array [ "other_permission", ] } > <p /> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user not have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) invert={true} permissions={ Array [ "invalid_permission", ] } > <Memo(AnyTeamPermissionGate) dispatch={[Function]} hasPermission={false} invert={true} permissions={ Array [ "invalid_permission", ] } > <p> Invalid permission but inverted (shown) </p> </Memo(AnyTeamPermissionGate)> </Connect(Component)> </Provider> `;
2,689
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/channel_permission_gate/channel_permission_gate.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import ChannelPermissionGate from 'components/permissions_gates/channel_permission_gate'; import TeamPermissionGate from 'components/permissions_gates/team_permission_gate'; import mockStore from 'tests/test_store'; describe('components/permissions_gates', () => { const state = { entities: { channels: { myMembers: { channel_id: {channel_id: 'channel_id', roles: 'channel_role'}, }, roles: { channel_id: ['channel_role'], }, }, teams: { myMembers: { team_id: {team_id: 'team_id', roles: 'team_role'}, }, }, users: { currentUserId: 'user_id', profiles: { user_id: { id: 'user_id', roles: 'system_role', }, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission']}, team_role: {permissions: ['test_team_permission']}, channel_role: {permissions: ['test_channel_permission']}, }, }, }, }; const store = mockStore(state); describe('ChannelPermissionGate', () => { test('should match snapshot when user have permission', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={'team_id'} permissions={['test_channel_permission']} > <p>{'Valid permission (shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have at least on of the permissions', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['test_team_permission', 'not_existing_permission']} > <p>{'Valid permission (shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={'team_id'} permissions={['test_channel_permission']} invert={true} > <p>{'Valid permission but inverted (not shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user not have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={'team_id'} permissions={['invalid_permission']} invert={true} > <p>{'Invalid permission but inverted (shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user haven\'t permission', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={'team_id'} permissions={['invalid_permission']} > <p>{'Invalid permission (not shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the channel doesn\'t exists', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'invalid_id'} teamId={'team_id'} permissions={['test_channel_permission']} > <p>{'Valid permission invalid channel (not shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission team wide', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={'team_id'} permissions={['test_team_permission']} > <p>{'Valid permission (shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission system wide', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={'team_id'} permissions={['test_system_permission']} > <p>{'Valid permission (shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permissions in DM and GM', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={''} permissions={['test_channel_permission']} > <p>{'Valid permission (shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user does not have permissions in DM and GM', () => { const wrapper = mount( <Provider store={store}> <ChannelPermissionGate channelId={'channel_id'} teamId={''} permissions={['invalid_permission']} > <p>{'Invalid permission (not shown)'}</p> </ChannelPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); }); });
2,693
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/channel_permission_gate
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/channel_permission_gate/__snapshots__/channel_permission_gate.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/permissions_gates ChannelPermissionGate should match snapshot when the channel doesn't exists 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="invalid_id" permissions={ Array [ "test_channel_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="invalid_id" dispatch={[Function]} hasPermission={false} permissions={ Array [ "test_channel_permission", ] } teamId="team_id" > <p /> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user does not have permissions in DM and GM 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" permissions={ Array [ "invalid_permission", ] } teamId="" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={false} permissions={ Array [ "invalid_permission", ] } teamId="" > <p /> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user have at least on of the permissions 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) permissions={ Array [ "test_team_permission", "not_existing_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={true} invert={false} permissions={ Array [ "test_team_permission", "not_existing_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </TeamPermissionGate> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user have permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" permissions={ Array [ "test_channel_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_channel_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" invert={true} permissions={ Array [ "test_channel_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={true} invert={true} permissions={ Array [ "test_channel_permission", ] } teamId="team_id" > <p /> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user have permission system wide 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" permissions={ Array [ "test_system_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_system_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user have permission team wide 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" permissions={ Array [ "test_team_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_team_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user have permissions in DM and GM 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" permissions={ Array [ "test_channel_permission", ] } teamId="" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_channel_permission", ] } teamId="" > <p> Valid permission (shown) </p> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user haven't permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={false} permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <p /> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `; exports[`components/permissions_gates ChannelPermissionGate should match snapshot when user not have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(Component) channelId="channel_id" invert={true} permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <Memo(ChannelPermissionGate) channelId="channel_id" dispatch={[Function]} hasPermission={false} invert={true} permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <p> Invalid permission but inverted (shown) </p> </Memo(ChannelPermissionGate)> </Connect(Component)> </Provider> `;
2,695
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/system_permission_gate/system_permission_gate.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import SystemPermissionGate from 'components/permissions_gates/system_permission_gate'; import mockStore from 'tests/test_store'; describe('components/permissions_gates', () => { const state = { entities: { channels: { myMembers: { channel_id: {channel_id: 'channel_id', roles: 'channel_role'}, }, }, teams: { myMembers: { team_id: {team_id: 'team_id', roles: 'team_role'}, }, }, users: { currentUserId: 'user_id', profiles: { user_id: { id: 'user_id', roles: 'system_role', }, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission']}, team_role: {permissions: ['test_team_permission']}, channel_role: {permissions: ['test_channel_permission']}, }, }, }, }; const store = mockStore(state); describe('SystemPermissionGate', () => { test('should match snapshot when user have permission', () => { const wrapper = mount( <Provider store={store}> <SystemPermissionGate permissions={['test_system_permission']}> <p>{'Valid permission (shown)'}</p> </SystemPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have at least on of the permissions', () => { const wrapper = mount( <Provider store={store}> <SystemPermissionGate permissions={['test_system_permission', 'not_existing_permission']}> <p>{'Valid permission (shown)'}</p> </SystemPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <SystemPermissionGate permissions={['test_system_permission']} invert={true} > <p>{'Valid permission but inverted (not shown)'}</p> </SystemPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user not have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <SystemPermissionGate permissions={['invalid_permission']} invert={true} > <p>{'Invalid permission but inverted (shown)'}</p> </SystemPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user haven\'t permission', () => { const wrapper = mount( <Provider store={store}> <SystemPermissionGate permissions={['invalid_permission']}> <p>{'Invalid permission (not shown)'}</p> </SystemPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); }); });
2,697
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/system_permission_gate
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/system_permission_gate/__snapshots__/system_permission_gate.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/permissions_gates SystemPermissionGate should match snapshot when user have at least on of the permissions 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(SystemPermissionGate) permissions={ Array [ "test_system_permission", "not_existing_permission", ] } > <SystemPermissionGate dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_system_permission", "not_existing_permission", ] } > <p> Valid permission (shown) </p> </SystemPermissionGate> </Connect(SystemPermissionGate)> </Provider> `; exports[`components/permissions_gates SystemPermissionGate should match snapshot when user have permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(SystemPermissionGate) permissions={ Array [ "test_system_permission", ] } > <SystemPermissionGate dispatch={[Function]} hasPermission={true} permissions={ Array [ "test_system_permission", ] } > <p> Valid permission (shown) </p> </SystemPermissionGate> </Connect(SystemPermissionGate)> </Provider> `; exports[`components/permissions_gates SystemPermissionGate should match snapshot when user have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(SystemPermissionGate) invert={true} permissions={ Array [ "test_system_permission", ] } > <SystemPermissionGate dispatch={[Function]} hasPermission={true} invert={true} permissions={ Array [ "test_system_permission", ] } /> </Connect(SystemPermissionGate)> </Provider> `; exports[`components/permissions_gates SystemPermissionGate should match snapshot when user haven't permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(SystemPermissionGate) permissions={ Array [ "invalid_permission", ] } > <SystemPermissionGate dispatch={[Function]} hasPermission={false} permissions={ Array [ "invalid_permission", ] } /> </Connect(SystemPermissionGate)> </Provider> `; exports[`components/permissions_gates SystemPermissionGate should match snapshot when user not have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(SystemPermissionGate) invert={true} permissions={ Array [ "invalid_permission", ] } > <SystemPermissionGate dispatch={[Function]} hasPermission={false} invert={true} permissions={ Array [ "invalid_permission", ] } > <p> Invalid permission but inverted (shown) </p> </SystemPermissionGate> </Connect(SystemPermissionGate)> </Provider> `;
2,699
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/team_permission_gate/team_permission_gate.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import TeamPermissionGate from 'components/permissions_gates/team_permission_gate'; import mockStore from 'tests/test_store'; describe('components/permissions_gates', () => { const state = { entities: { channels: { myMembers: { channel_id: {channel_id: 'channel_id', roles: 'channel_role'}, }, }, teams: { myMembers: { team_id: {team_id: 'team_id', roles: 'team_role'}, }, }, users: { currentUserId: 'user_id', profiles: { user_id: { id: 'user_id', roles: 'system_role', }, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission']}, team_role: {permissions: ['test_team_permission']}, channel_role: {permissions: ['test_channel_permission']}, }, }, }, }; const store = mockStore(state); describe('TeamPermissionGate', () => { test('should match snapshot when user have permission', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['test_team_permission']} > <p>{'Valid permission (shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have at least on of the permissions', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['test_team_permission', 'not_existing_permission']} > <p>{'Valid permission (shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['test_team_permission']} invert={true} > <p>{'Valid permission but inverted (not shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user not have permission and use invert', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['invalid_permission']} invert={true} > <p>{'Invalid permission but inverted (shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user haven\'t permission', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['invalid_permission']} > <p>{'Invalid permission (not shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the team doesn\'t exists', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'invalid_id'} permissions={['test_team_permission']} > <p>{'Valid permission invalid team (not shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user have permission system wide', () => { const wrapper = mount( <Provider store={store}> <TeamPermissionGate teamId={'team_id'} permissions={['test_system_permission']} > <p>{'Valid permission (shown)'}</p> </TeamPermissionGate> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); }); });
2,701
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/team_permission_gate
petrpan-code/mattermost/mattermost/webapp/channels/src/components/permissions_gates/team_permission_gate/__snapshots__/team_permission_gate.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/permissions_gates TeamPermissionGate should match snapshot when the team doesn't exists 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) permissions={ Array [ "test_team_permission", ] } teamId="invalid_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={false} invert={false} permissions={ Array [ "test_team_permission", ] } teamId="invalid_id" /> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have at least on of the permissions 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) permissions={ Array [ "test_team_permission", "not_existing_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={true} invert={false} permissions={ Array [ "test_team_permission", "not_existing_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </TeamPermissionGate> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) permissions={ Array [ "test_team_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={true} invert={false} permissions={ Array [ "test_team_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </TeamPermissionGate> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "test_team_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={true} invert={true} permissions={ Array [ "test_team_permission", ] } teamId="team_id" /> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user have permission system wide 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) permissions={ Array [ "test_system_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={true} invert={false} permissions={ Array [ "test_system_permission", ] } teamId="team_id" > <p> Valid permission (shown) </p> </TeamPermissionGate> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user haven't permission 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={false} invert={false} permissions={ Array [ "invalid_permission", ] } teamId="team_id" /> </Connect(TeamPermissionGate)> </Provider> `; exports[`components/permissions_gates TeamPermissionGate should match snapshot when user not have permission and use invert 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <TeamPermissionGate dispatch={[Function]} hasPermission={false} invert={true} permissions={ Array [ "invalid_permission", ] } teamId="team_id" > <p> Invalid permission but inverted (shown) </p> </TeamPermissionGate> </Connect(TeamPermissionGate)> </Provider> `;
2,703
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {MarketplacePlugin} from '@mattermost/types/marketplace'; import {AuthorType, ReleaseStage} from '@mattermost/types/marketplace'; import type {ActionFunc} from 'mattermost-redux/types/actions'; import {ModalIdentifiers} from 'utils/constants'; import type {GlobalState} from 'types/store'; import MarketplaceModal from './marketplace_modal'; import type {OpenedFromType} from './marketplace_modal'; import WebMarketplaceBanner from './web_marketplace_banner'; let mockState: GlobalState; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: jest.fn(() => (action: ActionFunc) => action), })); describe('components/marketplace/', () => { const samplePlugin: MarketplacePlugin = { homepage_url: 'https://github.com/mattermost/mattermost-plugin-nps', download_url: 'https://github.com/mattermost/mattermost-plugin-nps/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz', author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { id: 'com.mattermost.nps', name: 'User Satisfaction Surveys', description: 'This plugin sends quarterly user satisfaction surveys to gather feedback and help improve Mattermost', version: '1.0.3', min_server_version: '5.14.0', }, installed_version: '', }; const sampleInstalledPlugin: MarketplacePlugin = { homepage_url: 'https://github.com/mattermost/mattermost-test', download_url: 'https://github.com/mattermost/mattermost-test/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz', author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { id: 'com.mattermost.test', name: 'Test', description: 'This plugin is to test', version: '1.0.3', min_server_version: '5.14.0', }, installed_version: '1.0.3', }; const defaultProps = { openedFrom: 'actions_menu' as OpenedFromType, }; beforeEach(() => { mockState = { views: { modals: { modalState: { [ModalIdentifiers.PLUGIN_MARKETPLACE]: { open: true, }, }, }, marketplace: { plugins: [], apps: [], }, }, entities: { general: { firstAdminCompleteSetup: false, config: { FeatureFlagStreamlinedMarketplace: 'false', }, license: { Cloud: 'false', }, }, admin: { pluginStatuses: {}, }, }, } as unknown as GlobalState; }); test('should render default', () => { const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); expect(wrapper.shallow()).toMatchSnapshot(); }); test('should render with no plugins available', () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementationOnce(() => [false, setState]); const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); wrapper.update(); expect(wrapper.shallow()).toMatchSnapshot(); }); test('should render with plugins available', () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementationOnce(() => [false, setState]); mockState.views.marketplace.plugins = [ samplePlugin, ]; const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); wrapper.update(); expect(wrapper.shallow()).toMatchSnapshot(); }); test('should render with plugins installed', () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementationOnce(() => [false, setState]); mockState.views.marketplace.plugins = [ samplePlugin, sampleInstalledPlugin, ]; const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); wrapper.update(); expect(wrapper.shallow()).toMatchSnapshot(); }); test('should render with error banner', () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementation(() => [true, setState]); const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); wrapper.update(); expect(wrapper.shallow()).toMatchSnapshot(); }); test('hides search, shows web marketplace banner in FeatureFlags.StreamlinedMarketplace', () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementation(() => [true, setState]); mockState.views.marketplace.plugins = [ samplePlugin, sampleInstalledPlugin, ]; (mockState.entities.general.config as any).FeatureFlagStreamlinedMarketplace = 'true'; const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); wrapper.update(); const content = wrapper.shallow(); expect(content.exists('#searchMarketplaceTextbox')).toBe(false); expect(content.exists(WebMarketplaceBanner)).toBe(true); expect(content).toMatchSnapshot(); }); test("doesn't show web marketplace banner in FeatureFlags.StreamlinedMarketplace for Cloud", () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementation(() => [true, setState]); (mockState.entities.general.config as any).FeatureFlagStreamlinedMarketplace = 'true'; mockState.entities.general.license.Cloud = 'true'; const wrapper = shallow( <MarketplaceModal {...defaultProps}/>, ); wrapper.update(); const content = wrapper.shallow(); expect(content.exists(WebMarketplaceBanner)).toBe(false); expect(content).toMatchSnapshot(); }); });
2,706
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/__snapshots__/marketplace_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/marketplace/ doesn't show web marketplace banner in FeatureFlags.StreamlinedMarketplace for Cloud 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal streamlined-marketplace" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> </ModalHeader> <ModalBody bsClass="modal-body" className="divider" componentClass="div" > <div className="genericModalError" > <i className="icon icon-alert-outline" /> <span> Error connecting to the marketplace server. Please check your settings in the <Link key=".1" to="/admin_console/plugins/plugin_management" > System Console </Link> . </span> </div> <div className="GenericModal__body" > <LoadingScreen className="loading" /> </div> </ModalBody> </div> </Modal> `; exports[`components/marketplace/ hides search, shows web marketplace banner in FeatureFlags.StreamlinedMarketplace 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal streamlined-marketplace with-web-marketplace-link" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> </ModalHeader> <ModalBody bsClass="modal-body" className="divider" componentClass="div" > <div className="genericModalError" > <i className="icon icon-alert-outline" /> <span> Error connecting to the marketplace server. Please check your settings in the <Link key=".1" to="/admin_console/plugins/plugin_management" > System Console </Link> . </span> </div> <div className="GenericModal__body" > <LoadingScreen className="loading" /> </div> </ModalBody> <WebMarketplaceBanner /> </div> </Modal> `; exports[`components/marketplace/ should render default 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> <ForwardRef autoFocus={true} clearable={true} containerClassName="marketplace-modal-search" id="searchMarketplaceTextbox" inputClassName="search_input" inputPrefix={ <MagnifyIcon size={24} /> } inputSize="large" name="searchMarketplaceTextbox" onChange={[Function]} onClear={[Function]} placeholder="Search marketplace" type="text" useLegend={false} value="" /> </ModalHeader> <ModalBody bsClass="modal-body" className="" componentClass="div" > <div className="GenericModal__body" > <Uncontrolled(Tabs) activeKey="all" className="tabs" defaultActiveKey="all" id="marketplaceTabs" onSelect={[Function]} unmountOnExit={true} > <Tab eventKey="all" title="All" > <LoadingScreen className="loading" /> </Tab> <Tab eventKey="installed" title="Installed (0)" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={Array []} noResultsAction={ Object { "label": "Install plugins", "onClick": [Function], } } noResultsMessage="No plugins installed found" page={0} /> </Tab> </Uncontrolled(Tabs)> </div> </ModalBody> <ModalFooter bsClass="modal-footer" className="divider" componentClass="div" > <FooterPagination itemsPerPage={15} onNextPage={[Function]} onPreviousPage={[Function]} page={0} total={0} /> </ModalFooter> </div> </Modal> `; exports[`components/marketplace/ should render with error banner 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> <ForwardRef autoFocus={true} clearable={true} containerClassName="marketplace-modal-search" id="searchMarketplaceTextbox" inputClassName="search_input" inputPrefix={ <MagnifyIcon size={24} /> } inputSize="large" name="searchMarketplaceTextbox" onChange={[Function]} onClear={[Function]} placeholder="Search marketplace" type="text" useLegend={false} value="" /> </ModalHeader> <ModalBody bsClass="modal-body" className="" componentClass="div" > <div className="genericModalError" > <i className="icon icon-alert-outline" /> <span> Error connecting to the marketplace server. Please check your settings in the <Link key=".1" to="/admin_console/plugins/plugin_management" > System Console </Link> . </span> </div> <div className="GenericModal__body" > <Uncontrolled(Tabs) activeKey="all" className="tabs" defaultActiveKey="all" id="marketplaceTabs" onSelect={[Function]} unmountOnExit={true} > <Tab eventKey="all" title="All" > <LoadingScreen className="loading" /> </Tab> <Tab eventKey="installed" title="Installed (0)" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={Array []} noResultsAction={ Object { "label": "Install plugins", "onClick": [Function], } } noResultsMessage="No plugins installed found" page={0} /> </Tab> </Uncontrolled(Tabs)> </div> </ModalBody> <ModalFooter bsClass="modal-footer" className="divider" componentClass="div" > <FooterPagination itemsPerPage={15} onNextPage={[Function]} onPreviousPage={[Function]} page={0} total={0} /> </ModalFooter> </div> </Modal> `; exports[`components/marketplace/ should render with no plugins available 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> <ForwardRef autoFocus={true} clearable={true} containerClassName="marketplace-modal-search" id="searchMarketplaceTextbox" inputClassName="search_input" inputPrefix={ <MagnifyIcon size={24} /> } inputSize="large" name="searchMarketplaceTextbox" onChange={[Function]} onClear={[Function]} placeholder="Search marketplace" type="text" useLegend={false} value="" /> </ModalHeader> <ModalBody bsClass="modal-body" className="" componentClass="div" > <div className="GenericModal__body" > <Uncontrolled(Tabs) activeKey="all" className="tabs" defaultActiveKey="all" id="marketplaceTabs" onSelect={[Function]} unmountOnExit={true} > <Tab eventKey="all" title="All" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={Array []} noResultsMessage="No plugins found" page={0} /> </Tab> <Tab eventKey="installed" title="Installed (0)" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={Array []} noResultsAction={ Object { "label": "Install plugins", "onClick": [Function], } } noResultsMessage="No plugins installed found" page={0} /> </Tab> </Uncontrolled(Tabs)> </div> </ModalBody> <ModalFooter bsClass="modal-footer" className="divider" componentClass="div" > <FooterPagination itemsPerPage={15} onNextPage={[Function]} onPreviousPage={[Function]} page={0} total={0} /> </ModalFooter> </div> </Modal> `; exports[`components/marketplace/ should render with plugins available 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> <ForwardRef autoFocus={true} clearable={true} containerClassName="marketplace-modal-search" id="searchMarketplaceTextbox" inputClassName="search_input" inputPrefix={ <MagnifyIcon size={24} /> } inputSize="large" name="searchMarketplaceTextbox" onChange={[Function]} onClear={[Function]} placeholder="Search marketplace" type="text" useLegend={false} value="" /> </ModalHeader> <ModalBody bsClass="modal-body" className="" componentClass="div" > <div className="GenericModal__body" > <Uncontrolled(Tabs) activeKey="all" className="tabs" defaultActiveKey="all" id="marketplaceTabs" onSelect={[Function]} unmountOnExit={true} > <Tab eventKey="all" title="All" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={ Array [ Object { "author_type": "mattermost", "download_url": "https://github.com/mattermost/mattermost-plugin-nps/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz", "enterprise": false, "homepage_url": "https://github.com/mattermost/mattermost-plugin-nps", "installed_version": "", "manifest": Object { "description": "This plugin sends quarterly user satisfaction surveys to gather feedback and help improve Mattermost", "id": "com.mattermost.nps", "min_server_version": "5.14.0", "name": "User Satisfaction Surveys", "version": "1.0.3", }, "release_stage": "production", }, ] } noResultsMessage="No plugins found" page={0} /> </Tab> <Tab eventKey="installed" title="Installed (0)" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={Array []} noResultsAction={ Object { "label": "Install plugins", "onClick": [Function], } } noResultsMessage="No plugins installed found" page={0} /> </Tab> </Uncontrolled(Tabs)> </div> </ModalBody> <ModalFooter bsClass="modal-footer" className="divider" componentClass="div" > <FooterPagination itemsPerPage={15} onNextPage={[Function]} onPreviousPage={[Function]} page={0} total={1} /> </ModalFooter> </div> </Modal> `; exports[`components/marketplace/ should render with plugins installed 1`] = ` <Modal animation={true} aria-label="App Marketplace" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal GenericModal GenericModal__compassDesign marketplace-modal" dialogComponentClass={[Function]} enforceFocus={true} id="marketplace-modal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <div className="GenericModal__wrapper-enter-key-press-catcher" onKeyDown={[Function]} tabIndex={0} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <div className="GenericModal__header" > <h1 id="genericModalLabel" > App Marketplace </h1> </div> <ForwardRef autoFocus={true} clearable={true} containerClassName="marketplace-modal-search" id="searchMarketplaceTextbox" inputClassName="search_input" inputPrefix={ <MagnifyIcon size={24} /> } inputSize="large" name="searchMarketplaceTextbox" onChange={[Function]} onClear={[Function]} placeholder="Search marketplace" type="text" useLegend={false} value="" /> </ModalHeader> <ModalBody bsClass="modal-body" className="" componentClass="div" > <div className="GenericModal__body" > <Uncontrolled(Tabs) activeKey="all" className="tabs" defaultActiveKey="all" id="marketplaceTabs" onSelect={[Function]} unmountOnExit={true} > <Tab eventKey="all" title="All" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={ Array [ Object { "author_type": "mattermost", "download_url": "https://github.com/mattermost/mattermost-plugin-nps/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz", "enterprise": false, "homepage_url": "https://github.com/mattermost/mattermost-plugin-nps", "installed_version": "", "manifest": Object { "description": "This plugin sends quarterly user satisfaction surveys to gather feedback and help improve Mattermost", "id": "com.mattermost.nps", "min_server_version": "5.14.0", "name": "User Satisfaction Surveys", "version": "1.0.3", }, "release_stage": "production", }, Object { "author_type": "mattermost", "download_url": "https://github.com/mattermost/mattermost-test/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz", "enterprise": false, "homepage_url": "https://github.com/mattermost/mattermost-test", "installed_version": "1.0.3", "manifest": Object { "description": "This plugin is to test", "id": "com.mattermost.test", "min_server_version": "5.14.0", "name": "Test", "version": "1.0.3", }, "release_stage": "production", }, ] } noResultsMessage="No plugins found" page={0} /> </Tab> <Tab eventKey="installed" title="Installed (1)" > <MarketplaceList filter="" listRef={ Object { "current": null, } } listing={ Array [ Object { "author_type": "mattermost", "download_url": "https://github.com/mattermost/mattermost-test/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz", "enterprise": false, "homepage_url": "https://github.com/mattermost/mattermost-test", "installed_version": "1.0.3", "manifest": Object { "description": "This plugin is to test", "id": "com.mattermost.test", "min_server_version": "5.14.0", "name": "Test", "version": "1.0.3", }, "release_stage": "production", }, ] } noResultsAction={ Object { "label": "Install plugins", "onClick": [Function], } } noResultsMessage="No plugins installed found" page={0} /> </Tab> </Uncontrolled(Tabs)> </div> </ModalBody> <ModalFooter bsClass="modal-footer" className="divider" componentClass="div" > <FooterPagination itemsPerPage={15} onNextPage={[Function]} onPreviousPage={[Function]} page={0} total={2} /> </ModalFooter> </div> </Modal> `;
2,709
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item/marketplace_item_app/marketplace_item_app.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import MarketplaceItemApp from './marketplace_item_app'; import type {MarketplaceItemAppProps} from './marketplace_item_app'; describe('components/MarketplaceItemApp', () => { describe('MarketplaceItem', () => { const baseProps: MarketplaceItemAppProps = { id: 'id', name: 'name', description: 'test plugin', homepageUrl: 'http://example.com', installed: false, installing: false, trackEvent: jest.fn(() => {}), actions: { installApp: jest.fn(async () => Promise.resolve(true)), closeMarketplaceModal: jest.fn(() => {}), }, }; test('should render', () => { const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with no plugin description', () => { const props = {...baseProps}; delete props.description; const wrapper = shallow( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with no homepage url', () => { const props = {...baseProps}; delete props.homepageUrl; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with server error', () => { const props = { ...baseProps, error: 'An error occurred.', }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); it('when installing', () => { const props = { ...baseProps, isInstalling: true, }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render installed app', () => { const props = { ...baseProps, installed: true, }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with icon', () => { const props: MarketplaceItemAppProps = { ...baseProps, iconURL: 'http://localhost:8065/plugins/com.mattermost.apps/apps/com.mattermost.servicenow/static/now-mobile-icon.png', }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with empty list of labels', () => { const props = { ...baseProps, labels: [], }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with one labels', () => { const props = { ...baseProps, labels: [ { name: 'someName', description: 'some description', url: 'http://example.com/info', }, ], }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with two labels', () => { const props = { ...baseProps, labels: [ { name: 'someName', description: 'some description', url: 'http://example.com/info', }, { name: 'someName2', description: 'some description2', url: 'http://example.com/info2', }, ], }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); describe('install should trigger track event and close modal', () => { const props = { ...baseProps, isDefaultMarketplace: true, }; const wrapper = shallow<MarketplaceItemApp>( <MarketplaceItemApp {...props}/>, ); wrapper.instance().onInstall(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_install_app', { app_id: 'id', }); expect(props.actions.installApp).toHaveBeenCalledWith('id'); }); }); });
2,711
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item/marketplace_item_app
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item/marketplace_item_app/__snapshots__/marketplace_item_app.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MarketplaceItemApp MarketplaceItem should render 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installed={false} installing={false} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render installed app 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-installed" disabled={true} > <Memo(MemoizedFormattedMessage) defaultMessage="Installed" id="marketplace_modal.list.installed" /> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installed={true} installing={false} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with empty list of labels 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installed={false} installing={false} labels={Array []} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with icon 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" iconSource="http://localhost:8065/plugins/com.mattermost.apps/apps/com.mattermost.servicenow/static/now-mobile-icon.png" iconURL="http://localhost:8065/plugins/com.mattermost.apps/apps/com.mattermost.servicenow/static/now-mobile-icon.png" id="id" installed={false} installing={false} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with no homepage url 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" id="id" installed={false} installing={false} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with no plugin description 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } homepageUrl="http://example.com" id="id" installed={false} installing={false} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with one labels 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installed={false} installing={false} labels={ Array [ Object { "description": "some description", "name": "someName", "url": "http://example.com/info", }, ] } name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with server error 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Try Again" id="marketplace_modal.list.try_again" /> </Memo(LoadingWrapper)> </button> } description="test plugin" error="An error occurred." homepageUrl="http://example.com" id="id" installed={false} installing={false} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem should render with two labels 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installed={false} installing={false} labels={ Array [ Object { "description": "some description", "name": "someName", "url": "http://example.com/info", }, Object { "description": "some description2", "name": "someName2", "url": "http://example.com/info2", }, ] } name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `; exports[`components/MarketplaceItemApp MarketplaceItem when installing 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installApp": [MockFunction], } } button={ <button className="app-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installed={false} installing={false} isInstalling={true} name="name" trackEvent={[MockFunction]} updateDetails={null} versionLabel={null} /> </Fragment> `;
2,713
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item/marketplace_item_plugin/marketplace_item_plugin.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import type {PluginStatusRedux} from '@mattermost/types/plugins'; import ConfirmModal from 'components/confirm_modal'; import {mountWithIntl as mount} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import MarketplaceItemPlugin, {UpdateDetails, UpdateConfirmationModal} from './marketplace_item_plugin'; import type {UpdateDetailsProps, UpdateConfirmationModalProps, MarketplaceItemPluginProps} from './marketplace_item_plugin'; describe('components/MarketplaceItemPlugin', () => { describe('UpdateDetails', () => { const baseProps: UpdateDetailsProps = { version: '0.0.2', releaseNotesUrl: 'http://example.com/release', installedVersion: '0.0.1', isInstalling: false, onUpdate: () => {}, }; describe('should render nothing', () => { it('when no installed version', () => { const props = { ...baseProps, installedVersion: '', }; const wrapper = mount( <UpdateDetails {...props}/>, ); expect(wrapper.isEmptyRender()).toBe(true); }); it('when installed version matches available version', () => { const props = { ...baseProps, installedVersion: baseProps.version, }; const wrapper = mount( <UpdateDetails {...props}/>, ); expect(wrapper.isEmptyRender()).toBe(true); }); it('when installed version is newer than available version', () => { const props = { ...baseProps, installedVersion: '0.0.3', }; const wrapper = mount( <UpdateDetails {...props}/>, ); expect(wrapper.isEmptyRender()).toBe(true); }); it('when installing', () => { const props = { ...baseProps, isInstalling: true, }; const wrapper = mount( <UpdateDetails {...props}/>, ); expect(wrapper.isEmptyRender()).toBe(true); }); }); it('should render without release notes url', () => { const props = { ...baseProps, releaseNotesUrl: '', }; const wrapper = mount( <UpdateDetails {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); it('should render with release notes url', () => { const store = mockStore({ entities: { general: { config: {}, }, users: { currentUserId: 'currentUserId', }, }, }); const wrapper = mount( <Provider store={store}> <UpdateDetails {...baseProps}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); }); describe('UpdateConfirmationModal', () => { const baseProps: UpdateConfirmationModalProps = { show: true, name: 'pluginName', version: '0.0.2', releaseNotesUrl: 'http://example.com/release', installedVersion: '0.0.1', onUpdate: () => {}, onCancel: () => {}, }; describe('should render nothing', () => { it('if not installed', () => { const props = { ...baseProps, }; delete props.installedVersion; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); expect(wrapper.isEmptyRender()).toBe(true); }); it('when installed version is newer than available version', () => { const props = { ...baseProps, installedVersion: '0.0.3', }; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); expect(wrapper.isEmptyRender()).toBe(true); }); }); it('should propogate show to ConfirmModal', () => { const props = { ...baseProps, show: false, }; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); const modal = wrapper.find(ConfirmModal); expect(modal.exists()).toBe(true); expect(modal.props().show).toBe(false); }); it('should render without release notes url', () => { const props = { ...baseProps, }; delete props.releaseNotesUrl; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); expect(wrapper.find(ConfirmModal)).toMatchSnapshot(); }); it('should add extra warning for major version change', () => { const props = { ...baseProps, version: '1.0.0', }; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); expect(wrapper.find(ConfirmModal)).toMatchSnapshot(); }); it('should add extra warning for major version change, even without release notes', () => { const props = { ...baseProps, version: '1.0.0', }; delete props.releaseNotesUrl; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); expect(wrapper.find(ConfirmModal)).toMatchSnapshot(); }); it('should avoid exception on invalid semver', () => { const props = { ...baseProps, version: 'not-a-version', }; const wrapper = shallow( <UpdateConfirmationModal {...props}/>, ); expect(wrapper.find(ConfirmModal)).toMatchSnapshot(); }); }); describe('MarketplaceItem', () => { const baseProps: MarketplaceItemPluginProps = { id: 'id', name: 'name', description: 'test plugin', version: '1.0.0', homepageUrl: 'http://example.com', installedVersion: '', iconData: 'icon', installing: false, isDefaultMarketplace: true, trackEvent: jest.fn(() => {}), actions: { installPlugin: jest.fn(() => {}), closeMarketplaceModal: jest.fn(() => {}), }, }; test('should render', () => { const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with no plugin description', () => { const props = {...baseProps}; delete props.description; const wrapper = shallow( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with no plugin icon', () => { const props = {...baseProps}; delete props.iconData; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with no homepage url', () => { const props = {...baseProps}; delete props.homepageUrl; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with server error', () => { const props = { ...baseProps, error: 'An error occurred.', }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with plugin status error', () => { const pluginStatus: PluginStatusRedux = { active: true, description: '', id: baseProps.id, instances: [], name: baseProps.name, state: 0, version: '', error: 'plugin status error', }; const props = { ...baseProps, pluginStatus, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render installed plugin', () => { const props = { ...baseProps, installedVersion: '1.0.0', }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with update available', () => { const props = { ...baseProps, installedVersion: '0.9.9', }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with update and release notes available', () => { const props = { ...baseProps, installedVersion: '0.9.9', releaseNotesUrl: 'http://example.com/release', }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with empty list of labels', () => { const props = { ...baseProps, labels: [], }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with one labels', () => { const props = { ...baseProps, labels: [ { name: 'someName', description: 'some description', url: 'http://example.com/info', }, ], }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render with two labels', () => { const props = { ...baseProps, labels: [ { name: 'someName', description: 'some description', url: 'http://example.com/info', }, { name: 'someName2', description: 'some description2', url: 'http://example.com/info2', }, ], }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); describe('should track detailed event with default marketplace', () => { test('on install', () => { const props = { ...baseProps, isDefaultMarketplace: true, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); wrapper.instance().onInstall(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_download', { plugin_id: 'id', version: '1.0.0', installed_version: '', }); }); test('on update', () => { const props = { ...baseProps, version: '2.0.0', installedVersion: '1.0.0', isDefaultMarketplace: true, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); wrapper.instance().onUpdate(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_download_update', { plugin_id: 'id', version: '2.0.0', installed_version: '1.0.0', }); }); test('but not configure', () => { const props = { ...baseProps, version: '2.0.0', installedVersion: '1.0.0', isDefaultMarketplace: true, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); wrapper.instance().onConfigure(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_configure'); }); }); describe('should track limited event with non-default marketplace', () => { test('on install', () => { const props = { ...baseProps, isDefaultMarketplace: false, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); wrapper.instance().onInstall(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_download'); }); test('on update', () => { const props = { ...baseProps, version: '2.0.0', installedVersion: '1.0.0', isDefaultMarketplace: false, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); wrapper.instance().onUpdate(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_download_update'); }); test('on configure', () => { const props = { ...baseProps, version: '2.0.0', installedVersion: '1.0.0', isDefaultMarketplace: false, }; const wrapper = shallow<MarketplaceItemPlugin>( <MarketplaceItemPlugin {...props}/>, ); wrapper.instance().onConfigure(); expect(props.trackEvent).toBeCalledWith('plugins', 'ui_marketplace_configure'); }); }); }); });
2,715
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item/marketplace_item_plugin
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_item/marketplace_item_plugin/__snapshots__/marketplace_item_plugin.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MarketplaceItemPlugin MarketplaceItem should render 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render installed plugin 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <Link to="/admin_console/plugins/plugin_id" > <button className="plugin-configure" onClick={[Function]} > <Memo(MemoizedFormattedMessage) defaultMessage="Configure" id="marketplace_modal.list.configure" /> </button> </Link> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="1.0.0" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="1.0.0" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="1.0.0" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with empty list of labels 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} labels={Array []} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with no homepage url 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with no plugin description 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with no plugin icon 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with one labels 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} labels={ Array [ Object { "description": "some description", "name": "someName", "url": "http://example.com/info", }, ] } name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with plugin status error 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" error="plugin status error" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} name="name" pluginStatus={ Object { "active": true, "description": "", "error": "plugin status error", "id": "id", "instances": Array [], "name": "name", "state": 0, "version": "", } } trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with server error 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Try Again" id="marketplace_modal.list.try_again" /> </Memo(LoadingWrapper)> </button> } description="test plugin" error="An error occurred." homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with two labels 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <button className="plugin-install always-show-enabled" disabled={false} onClick={[Function]} > <Memo(LoadingWrapper) loading={false} text="Installing..." > <Memo(MemoizedFormattedMessage) defaultMessage="Install" id="marketplace_modal.list.install" /> </Memo(LoadingWrapper)> </button> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="" installing={false} isDefaultMarketplace={true} labels={ Array [ Object { "description": "some description", "name": "someName", "url": "http://example.com/info", }, Object { "description": "some description2", "name": "someName2", "url": "http://example.com/info2", }, ] } name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (1.0.0) </span> } /> <UpdateConfirmationModal installedVersion="" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with update and release notes available 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <Link to="/admin_console/plugins/plugin_id" > <button className="plugin-configure" onClick={[Function]} > <Memo(MemoizedFormattedMessage) defaultMessage="Configure" id="marketplace_modal.list.configure" /> </button> </Link> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="0.9.9" installing={false} isDefaultMarketplace={true} name="name" releaseNotesUrl="http://example.com/release" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="0.9.9" isInstalling={false} onUpdate={[Function]} releaseNotesUrl="http://example.com/release" version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (0.9.9) </span> } /> <UpdateConfirmationModal installedVersion="0.9.9" name="name" onCancel={[Function]} onUpdate={[Function]} releaseNotesUrl="http://example.com/release" show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin MarketplaceItem should render with update available 1`] = ` <Fragment> <MarketplaceItem actions={ Object { "closeMarketplaceModal": [MockFunction], "installPlugin": [MockFunction], } } button={ <Link to="/admin_console/plugins/plugin_id" > <button className="plugin-configure" onClick={[Function]} > <Memo(MemoizedFormattedMessage) defaultMessage="Configure" id="marketplace_modal.list.configure" /> </button> </Link> } description="test plugin" homepageUrl="http://example.com" iconData="icon" iconSource="icon" id="id" installedVersion="0.9.9" installing={false} isDefaultMarketplace={true} name="name" trackEvent={[MockFunction]} updateDetails={ <UpdateDetails installedVersion="0.9.9" isInstalling={false} onUpdate={[Function]} version="1.0.0" /> } version="1.0.0" versionLabel={ <span className="light subtitle" > (0.9.9) </span> } /> <UpdateConfirmationModal installedVersion="0.9.9" name="name" onCancel={[Function]} onUpdate={[Function]} show={false} version="1.0.0" /> </Fragment> `; exports[`components/MarketplaceItemPlugin UpdateConfirmationModal should add extra warning for major version change 1`] = ` <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Update" id="marketplace_modal.list.update_confirmation.confirm_button" /> } message={ Array [ <p> <Memo(MemoizedFormattedMessage) defaultMessage="Are you sure you want to update the pluginName plugin to 1.0.0?" id="marketplace_modal.list.update_confirmation.message.intro" values={ Object { "name": "pluginName", "version": "1.0.0", } } /> </p>, <p> <FormattedMarkdownMessage defaultMessage="You currently have {installedVersion} installed. View the [release notes](!{releaseNotesUrl}) to learn about the changes included in this update." id="marketplace_modal.list.update_confirmation.message.current_with_release_notes" values={ Object { "installedVersion": "0.0.1", "releaseNotesUrl": "http://example.com/release", } } /> </p>, <p className="alert alert-warning" > <FormattedMarkdownMessage defaultMessage="This update may contain breaking changes. Consult the [release notes](!{releaseNotesUrl}) before upgrading." id="marketplace_modal.list.update_confirmation.message.warning_major_version_with_release_notes" values={ Object { "releaseNotesUrl": "http://example.com/release", } } /> </p>, ] } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={true} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Confirm Plugin Update" id="marketplace_modal.list.update_confirmation.title" /> } /> `; exports[`components/MarketplaceItemPlugin UpdateConfirmationModal should add extra warning for major version change, even without release notes 1`] = ` <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Update" id="marketplace_modal.list.update_confirmation.confirm_button" /> } message={ Array [ <p> <Memo(MemoizedFormattedMessage) defaultMessage="Are you sure you want to update the pluginName plugin to 1.0.0?" id="marketplace_modal.list.update_confirmation.message.intro" values={ Object { "name": "pluginName", "version": "1.0.0", } } /> </p>, <p> <Memo(MemoizedFormattedMessage) defaultMessage="You currently have 0.0.1 installed." id="marketplace_modal.list.update_confirmation.message.current" values={ Object { "installedVersion": "0.0.1", } } /> </p>, <p className="alert alert-warning" > <Memo(MemoizedFormattedMessage) defaultMessage="This update may contain breaking changes." id="marketplace_modal.list.update_confirmation.message.warning_major_version" /> </p>, ] } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={true} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Confirm Plugin Update" id="marketplace_modal.list.update_confirmation.title" /> } /> `; exports[`components/MarketplaceItemPlugin UpdateConfirmationModal should avoid exception on invalid semver 1`] = `null`; exports[`components/MarketplaceItemPlugin UpdateConfirmationModal should render without release notes url 1`] = ` <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Update" id="marketplace_modal.list.update_confirmation.confirm_button" /> } message={ Array [ <p> <Memo(MemoizedFormattedMessage) defaultMessage="Are you sure you want to update the pluginName plugin to 0.0.2?" id="marketplace_modal.list.update_confirmation.message.intro" values={ Object { "name": "pluginName", "version": "0.0.2", } } /> </p>, <p> <Memo(MemoizedFormattedMessage) defaultMessage="You currently have 0.0.1 installed." id="marketplace_modal.list.update_confirmation.message.current" values={ Object { "installedVersion": "0.0.1", } } /> </p>, ] } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={true} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Confirm Plugin Update" id="marketplace_modal.list.update_confirmation.title" /> } /> `; exports[`components/MarketplaceItemPlugin UpdateDetails should render with release notes url 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <UpdateDetails installedVersion="0.0.1" isInstalling={false} onUpdate={[Function]} releaseNotesUrl="http://example.com/release" version="0.0.2" > <div className="update" > <FormattedMessage defaultMessage="Update available:" id="marketplace_modal.list.update_available" > <span> Update available: </span> </FormattedMessage> <UpdateVersion releaseNotesUrl="http://example.com/release" version="0.0.2" > <ExternalLink href="http://example.com/release" location="marketplace_item_plugin" > <a href="http://example.com/release" location="marketplace_item_plugin" onClick={[Function]} rel="noopener noreferrer" target="_blank" > 0.0.2 </a> </ExternalLink> </UpdateVersion> - <b> <a onClick={[Function]} > <FormattedMessage defaultMessage="Update" id="marketplace_modal.list.update" > <span> Update </span> </FormattedMessage> </a> </b> </div> </UpdateDetails> </Provider> `; exports[`components/MarketplaceItemPlugin UpdateDetails should render without release notes url 1`] = ` <UpdateDetails installedVersion="0.0.1" isInstalling={false} onUpdate={[Function]} releaseNotesUrl="" version="0.0.2" > <div className="update" > <FormattedMessage defaultMessage="Update available:" id="marketplace_modal.list.update_available" > <span> Update available: </span> </FormattedMessage> <UpdateVersion releaseNotesUrl="" version="0.0.2" > <span> 0.0.2 </span> </UpdateVersion> - <b> <a onClick={[Function]} > <FormattedMessage defaultMessage="Update" id="marketplace_modal.list.update" > <span> Update </span> </FormattedMessage> </a> </b> </div> </UpdateDetails> `;
2,716
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_list/marketplace_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {AuthorType, ReleaseStage} from '@mattermost/types/marketplace'; import type {MarketplacePlugin} from '@mattermost/types/marketplace'; import MarketplaceList, {ITEMS_PER_PAGE} from './marketplace_list'; import MarketplaceItem from '../marketplace_item/marketplace_item_plugin'; describe('components/marketplace/marketplace_list', () => { const samplePlugin: MarketplacePlugin = { homepage_url: 'https://github.com/mattermost/mattermost-plugin-nps', download_url: 'https://github.com/mattermost/mattermost-plugin-nps/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz', author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { id: 'com.mattermost.nps', name: 'User Satisfaction Surveys', description: 'This plugin sends quarterly user satisfaction surveys to gather feedback and help improve Mattermost', version: '1.0.3', min_server_version: '5.14.0', }, installed_version: '', }; it('should render default', () => { const wrapper = shallow( <MarketplaceList listing={[]} page={0} noResultsMessage='' />, ); expect(wrapper).toMatchSnapshot(); }); it('should render page with ITEMS_PER_PAGE plugins', () => { const wrapper = shallow( <MarketplaceList listing={[ samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, samplePlugin, ]} page={0} noResultsMessage='' />, ); expect(wrapper.find(MarketplaceItem)).toHaveLength(ITEMS_PER_PAGE); }); it('should render no results', () => { const wrapper = shallow( <MarketplaceList listing={[]} page={0} noResultsMessage='No plugins available' noResultsAction={{ label: 'action', onClick: jest.fn(), }} />, ); expect(wrapper.find('.icon__plugin').length).toEqual(1); expect(wrapper.find('.no_plugins__message').length).toEqual(1); expect(wrapper.find('.no_plugins__action').length).toEqual(1); }); });
2,718
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/plugin_marketplace/marketplace_list/__snapshots__/marketplace_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/marketplace/marketplace_list should render default 1`] = ` <div className="no_plugins" > <PluginIcon className="icon__plugin" /> <div className="no_plugins__message" /> </div> `;
2,721
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post/post_component.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {DeepPartial} from '@mattermost/types/utilities'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import {renderWithContext, screen, userEvent} from 'tests/react_testing_utils'; import {getHistory} from 'utils/browser_history'; import {Locations} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import PostComponent from './post_component'; import type {Props} from './post_component'; describe('PostComponent', () => { const currentTeam = TestHelper.getTeamMock(); const channel = TestHelper.getChannelMock({team_id: currentTeam.id}); const baseProps: Props = { center: false, currentTeam, currentUserId: 'currentUserId', displayName: '', hasReplies: false, isBot: false, isCollapsedThreadsEnabled: true, isFlagged: false, isMobileView: false, isPostAcknowledgementsEnabled: false, isPostPriorityEnabled: false, location: Locations.CENTER, post: TestHelper.getPostMock({channel_id: channel.id}), recentEmojis: [], replyCount: 0, team: currentTeam, pluginActions: [], actions: { markPostAsUnread: jest.fn(), emitShortcutReactToLastPostFrom: jest.fn(), setActionsMenuInitialisationState: jest.fn(), selectPost: jest.fn(), selectPostFromRightHandSideSearch: jest.fn(), removePost: jest.fn(), closeRightHandSide: jest.fn(), selectPostCard: jest.fn(), setRhsExpanded: jest.fn(), }, }; describe('reactions', () => { const baseState: DeepPartial<GlobalState> = { entities: { posts: { reactions: { [baseProps.post.id]: { [`${baseProps.currentUserId}-taco`]: TestHelper.getReactionMock({emoji_name: 'taco'}), }, }, }, }, }; test('should show reactions in the center channel', () => { renderWithContext(<PostComponent {...baseProps}/>, baseState); expect(screen.getByLabelText('reactions')).toBeInTheDocument(); }); test('should show reactions in thread view', () => { const state = mergeObjects(baseState, { views: { rhs: { selectedPostId: baseProps.post.id, }, }, }); let props: Props = { ...baseProps, location: Locations.RHS_ROOT, }; const {rerender} = renderWithContext(<PostComponent {...props}/>, state); expect(screen.getByLabelText('reactions')).toBeInTheDocument(); props = { ...baseProps, location: Locations.RHS_COMMENT, }; rerender(<PostComponent {...props}/>); expect(screen.getByLabelText('reactions')).toBeInTheDocument(); }); test('should show only show reactions in search results with pinned/saved posts visible', () => { let props = { ...baseProps, location: Locations.SEARCH, }; const {rerender} = renderWithContext(<PostComponent {...props}/>, baseState); expect(screen.queryByLabelText('reactions')).not.toBeInTheDocument(); props = { ...baseProps, location: Locations.SEARCH, isPinnedPosts: true, }; rerender(<PostComponent {...props}/>); expect(screen.getByLabelText('reactions')).toBeInTheDocument(); props = { ...baseProps, location: Locations.SEARCH, isFlaggedPosts: true, }; rerender(<PostComponent {...props}/>); expect(screen.getByLabelText('reactions')).toBeInTheDocument(); }); }); describe('thread footer', () => { test('should never show thread footer for a post that isn\'t part of a thread', () => { let props: Props = baseProps; const {rerender} = renderWithContext(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); props = { ...baseProps, location: Locations.SEARCH, }; rerender(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); }); // This probably shouldn't appear in the search results https://mattermost.atlassian.net/browse/MM-53078 test('should only show thread footer for a root post in the center channel and search results', () => { const rootPost = TestHelper.getPostMock({ id: 'rootPost', channel_id: channel.id, reply_count: 1, }); const state: DeepPartial<GlobalState> = { entities: { posts: { posts: { rootPost, }, }, }, }; let props = { ...baseProps, hasReplies: true, post: rootPost, replyCount: 1, }; const {rerender} = renderWithContext(<PostComponent {...props}/>, state); expect(screen.queryByText(/Follow|Following/)).toBeInTheDocument(); props = { ...props, location: Locations.RHS_ROOT, }; rerender(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); props = { ...props, location: Locations.SEARCH, }; rerender(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).toBeInTheDocument(); }); test('should never show thread footer for a comment', () => { let props = { ...baseProps, hasReplies: true, post: { ...baseProps.post, root_id: 'some_other_post_id', }, }; const {rerender} = renderWithContext(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); props = { ...props, location: Locations.RHS_COMMENT, }; rerender(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); props = { ...props, location: Locations.SEARCH, }; rerender(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); }); test('should not show thread footer with CRT disabled', () => { const rootPost = TestHelper.getPostMock({ id: 'rootPost', channel_id: channel.id, reply_count: 1, }); const state: DeepPartial<GlobalState> = { entities: { posts: { posts: { rootPost, }, }, }, }; let props = { ...baseProps, hasReplies: true, isCollapsedThreadsEnabled: false, post: rootPost, replyCount: 1, }; const {rerender} = renderWithContext(<PostComponent {...props}/>, state); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); props = { ...props, location: Locations.SEARCH, }; rerender(<PostComponent {...props}/>); expect(screen.queryByText(/Follow|Following/)).not.toBeInTheDocument(); }); describe('reply/X replies link', () => { const rootPost = TestHelper.getPostMock({ id: 'rootPost', channel_id: channel.id, reply_count: 1, }); const state: DeepPartial<GlobalState> = { entities: { posts: { posts: { rootPost, }, }, }, }; const propsForRootPost = { ...baseProps, hasReplies: true, post: rootPost, replyCount: 1, }; test('should select post in RHS when clicked in center channel', () => { renderWithContext(<PostComponent {...propsForRootPost}/>, state); userEvent.click(screen.getByText('1 reply')); // Yes, this action has a different name than the one you'd expect expect(propsForRootPost.actions.selectPostFromRightHandSideSearch).toHaveBeenCalledWith(rootPost); }); test('should select post in RHS when clicked in center channel in a DM/GM', () => { const props = { ...propsForRootPost, team: undefined, }; renderWithContext(<PostComponent {...props}/>, state); userEvent.click(screen.getByText('1 reply')); // Yes, this action has a different name than the one you'd expect expect(propsForRootPost.actions.selectPostFromRightHandSideSearch).toHaveBeenCalledWith(rootPost); expect(getHistory().push).not.toHaveBeenCalled(); }); test('should select post in RHS when clicked in a search result on the current team', () => { const props = { ...propsForRootPost, location: Locations.SEARCH, }; renderWithContext(<PostComponent {...props}/>, state); userEvent.click(screen.getByText('1 reply')); expect(propsForRootPost.actions.selectPostFromRightHandSideSearch).toHaveBeenCalledWith(rootPost); expect(getHistory().push).not.toHaveBeenCalled(); }); test('should jump to post when clicked in a search result on another team', () => { const props = { ...propsForRootPost, location: Locations.SEARCH, team: TestHelper.getTeamMock({id: 'another_team'}), }; renderWithContext(<PostComponent {...props}/>, state); userEvent.click(screen.getByText('1 reply')); expect(propsForRootPost.actions.selectPostFromRightHandSideSearch).not.toHaveBeenCalled(); expect(getHistory().push).toHaveBeenCalled(); }); }); }); });
2,727
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history/post_edit_history.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ComponentProps} from 'react'; import {Client4} from 'mattermost-redux/client'; import {renderWithContext, waitFor} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import PostEditHistory from './post_edit_history'; describe('components/post_edit_history', () => { const baseProps: ComponentProps<typeof PostEditHistory> = { channelDisplayName: 'channel_display_name', originalPost: TestHelper.getPostMock({ id: 'post_id', message: 'post message', }), dispatch: jest.fn(), }; const mock = jest.spyOn(Client4, 'getPostEditHistory'); test('should match snapshot', async () => { const data = [ TestHelper.getPostMock({ id: 'post_id_1', message: 'post message version 1', }), TestHelper.getPostMock({ id: 'post_id_2', message: 'post message version 2', }), ]; mock.mockResolvedValue(data); const wrapper = await waitFor(() => { return renderWithContext(<PostEditHistory {...baseProps}/>); }); expect(wrapper.container).toMatchSnapshot(); expect(mock).toBeCalledWith(baseProps.originalPost.id); }); test('should display error screen if errors are present', async () => { const error = new Error('An example error'); mock.mockRejectedValue(error); const wrapper = await waitFor(() => { return renderWithContext(<PostEditHistory {...baseProps}/>); }); expect(wrapper.container).toMatchSnapshot(); expect(mock).toBeCalledWith(baseProps.originalPost.id); }); });
2,730
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history/__snapshots__/post_edit_history.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_edit_history should display error screen if errors are present 1`] = ` <div> <div class="sidebar-right__body sidebar-right__edit-post-history" id="rhsContainer" > <div style="position: relative; overflow: hidden; width: 100%; height: 100%;" > <div class="scrollbar--view" style="position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; overflow: scroll; margin-right: 0px; margin-bottom: 0px;" > <div class="sidebar--right__header" > <span class="sidebar--right__title" > Edit History <div class="sidebar--right__title__channel" > channel_display_name </div> </span> <div class="pull-right" > <button class="sidebar--right__expand btn btn-icon btn-sm" type="button" > <i aria-label="Expand Sidebar Icon" class="icon icon-arrow-expand" /> <i aria-label="Collapse Sidebar Icon" class="icon icon-arrow-collapse" /> </button> <button aria-label="Close" class="sidebar--right__close btn btn-icon btn-sm" id="searchResultsCloseButton" type="button" > <i aria-label="Close Sidebar Icon" class="icon icon-close" /> </button> </div> </div> <div class="edit-post-history__error_container" > <div class="edit-post-history__error_item" > <svg fill="none" height="127" viewBox="0 0 110 100" width="127" xmlns="http://www.w3.org/2000/svg" > <path d="M26.4736 81.0278C23.2554 81.0278 21.7973 78.708 23.2333 75.8728L49.2438 24.7796C50.7166 21.9517 53.0364 21.9517 54.4798 24.7796L80.483 75.8728C81.9558 78.7006 80.483 81.0278 77.2427 81.0278H26.4736Z" fill="#FFBC1F" /> <path d="M47.7783 43.6764L50.4515 61.6378C50.4773 61.9942 50.6371 62.3276 50.8988 62.571C51.1604 62.8144 51.5045 62.9497 51.8618 62.9497C52.2192 62.9497 52.5632 62.8144 52.8249 62.571C53.0865 62.3276 53.2463 61.9942 53.2721 61.6378L55.9453 43.6764C56.4314 36.673 47.2849 36.673 47.7783 43.6764Z" fill="#2D3039" /> <path d="M51.8582 64.8853C52.6677 64.8867 53.4586 65.1281 54.1309 65.5789C54.8033 66.0297 55.327 66.6697 55.6358 67.418C55.9446 68.1663 56.0246 68.9893 55.8657 69.7831C55.7069 70.5769 55.3164 71.3058 54.7435 71.8777C54.1706 72.4496 53.441 72.8388 52.6469 72.9962C51.8529 73.1536 51.03 73.0721 50.2822 72.7619C49.5345 72.4518 48.8954 71.927 48.4458 71.2538C47.9963 70.5806 47.7563 69.7893 47.7563 68.9798C47.7563 68.4415 47.8624 67.9084 48.0686 67.4112C48.2749 66.9139 48.5772 66.4622 48.9582 66.0819C49.3392 65.7016 49.7914 65.4002 50.2891 65.1948C50.7867 64.9895 51.3199 64.8843 51.8582 64.8853Z" fill="#2D3039" /> </svg> <p class="edit-post-history__error_heading" > Unable to load edit history </p> <p class="edit-post-history__error_subheading" > There was an error loading the history for this message. Check your network connection or try again later. </p> </div> </div> </div> <div style="position: absolute; height: 6px; transition: opacity 500ms; opacity: 0; display: none; right: 2px; bottom: 2px; left: 2px; border-radius: 3px;" > <div class="scrollbar--horizontal" style="position: relative; display: block; height: 100%;" /> </div> <div style="position: absolute; width: 6px; transition: opacity 500ms; opacity: 0; display: none; right: 2px; bottom: 2px; top: 2px; border-radius: 3px;" > <div class="scrollbar--vertical" style="position: relative; display: block; width: 100%;" /> </div> </div> </div> </div> `; exports[`components/post_edit_history should match snapshot 1`] = ` <div> <div class="sidebar-right__body sidebar-right__edit-post-history" id="rhsContainer" > <div style="position: relative; overflow: hidden; width: 100%; height: 100%;" > <div class="scrollbar--view" style="position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; overflow: scroll; margin-right: 0px; margin-bottom: 0px;" > <div class="sidebar--right__header" > <span class="sidebar--right__title" > Edit History <div class="sidebar--right__title__channel" > channel_display_name </div> </span> <div class="pull-right" > <button class="sidebar--right__expand btn btn-icon btn-sm" type="button" > <i aria-label="Expand Sidebar Icon" class="icon icon-arrow-expand" /> <i aria-label="Collapse Sidebar Icon" class="icon icon-arrow-collapse" /> </button> <button aria-label="Close" class="sidebar--right__close btn btn-icon btn-sm" id="searchResultsCloseButton" type="button" > <i aria-label="Close Sidebar Icon" class="icon icon-close" /> </button> </div> </div> <div class="edit-post-history__container edit-post-history__container__background" > <div aria-label="At 12:00 AM Thursday, January 1, Someone wrote, post message" class="a11y__section post" id="searchResult_post_id" > <div aria-hidden="true" class="edit-post-history__title__container" > <div class="edit-post-history__date__badge__container" > <button aria-label="Toggle to see an old message." class="IconButtonRoot-hOPlUx gmplBN edit-post-history__icon__button" disabled="" > <i class="IconRoot-jSSaqj bQHSub icon-chevron-down" color="inherit" size="16" /> </button> <span class="edit-post-history__date" > <time datetime="1970-01-01T00:00:00.000" > January 01, 1970 at 12:00 AM </time> </span> <div class="edit-post-history__current__indicator" > Current Version </div> </div> </div> <div class="edit-post-history__content_container" > <div class="edit-post-history__header" > <span class="profile-icon" > <img alt="user profile image" class="Avatar Avatar-sm avatar-post-preview" loading="lazy" src="/api/v4/users/user_id/image?_=0" tabindex="0" /> </span> <div class="edit-post-history__header__username" > <div class="user-popover" > Someone </div> </div> </div> <div class="post__content" > <div class="search-item-snippet post__body" > <div class="post-message post-message--collapsed" > <div class="post-message__text-container" style="max-height: 600px;" > <div class="post-message__text" dir="auto" id="rhsPostMessageText_post_id" tabindex="0" > <p> post message </p> </div> </div> </div> </div> </div> </div> </div> </div> <div class="edit-post-history__container" > <div aria-label="At 12:00 AM Thursday, January 1, Someone wrote, post message version 1" class="a11y__section post" id="searchResult_post_id_1" > <div aria-hidden="true" class="edit-post-history__title__container" > <div class="edit-post-history__date__badge__container" > <button aria-label="Toggle to see an old message." class="IconButtonRoot-hOPlUx gmplBN edit-post-history__icon__button" disabled="" > <i class="IconRoot-jSSaqj bQHSub icon-chevron-right" color="inherit" size="16" /> </button> <span class="edit-post-history__date" > <time datetime="1970-01-01T00:00:00.000" > January 01, 1970 at 12:00 AM </time> </span> </div> <button aria-label="Select to restore an old message." class="IconButtonRoot-hOPlUx gBoGLw edit-post-history__icon__button restore-icon" > <i class="IconRoot-jSSaqj bQHSub icon-restore" color="inherit" size="16" /> </button> </div> </div> </div> <div class="edit-post-history__container" > <div aria-label="At 12:00 AM Thursday, January 1, Someone wrote, post message version 2" class="a11y__section post" id="searchResult_post_id_2" > <div aria-hidden="true" class="edit-post-history__title__container" > <div class="edit-post-history__date__badge__container" > <button aria-label="Toggle to see an old message." class="IconButtonRoot-hOPlUx gmplBN edit-post-history__icon__button" disabled="" > <i class="IconRoot-jSSaqj bQHSub icon-chevron-right" color="inherit" size="16" /> </button> <span class="edit-post-history__date" > <time datetime="1970-01-01T00:00:00.000" > January 01, 1970 at 12:00 AM </time> </span> </div> <button aria-label="Select to restore an old message." class="IconButtonRoot-hOPlUx gBoGLw edit-post-history__icon__button restore-icon" > <i class="IconRoot-jSSaqj bQHSub icon-restore" color="inherit" size="16" /> </button> </div> </div> </div> </div> <div style="position: absolute; height: 6px; transition: opacity 500ms; opacity: 0; display: none; right: 2px; bottom: 2px; left: 2px; border-radius: 3px;" > <div class="scrollbar--horizontal" style="position: relative; display: block; height: 100%;" /> </div> <div style="position: absolute; width: 6px; transition: opacity 500ms; opacity: 0; display: none; right: 2px; bottom: 2px; top: 2px; border-radius: 3px;" > <div class="scrollbar--vertical" style="position: relative; display: block; width: 100%;" /> </div> </div> </div> </div> `;
2,731
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history/edited_post_item/edited_post_item.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ComponentProps} from 'react'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import {ModalIdentifiers} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import EditedPostItem from './edited_post_item'; import RestorePostModal from '../restore_post_modal'; describe('components/post_edit_history/edited_post_item', () => { const baseProps: ComponentProps<typeof EditedPostItem> = { post: TestHelper.getPostMock({ id: 'post_id', message: 'post message', }), isCurrent: false, theme: {} as Theme, postCurrentVersion: TestHelper.getPostMock({ id: 'post_current_version_id', message: 'post current version message', }), actions: { editPost: jest.fn(), closeRightHandSide: jest.fn(), openModal: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow(<EditedPostItem {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when isCurrent is true', () => { const props = { ...baseProps, isCurrent: true, }; const wrapper = shallow(<EditedPostItem {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('clicking on the restore button should call openRestorePostModal', () => { const wrapper = shallow(<EditedPostItem {...baseProps}/>); // find the button with restore icon and click it wrapper.find('ForwardRef').filterWhere((button) => button.prop('icon') === 'restore').simulate('click'); expect(baseProps.actions.openModal).toHaveBeenCalledWith( expect.objectContaining({ modalId: ModalIdentifiers.RESTORE_POST_MODAL, dialogType: RestorePostModal, }), ); }); test('when isCurrent is true, should not render the restore button', () => { const props = { ...baseProps, isCurrent: true, }; const wrapper = shallow(<EditedPostItem {...props}/>); expect(wrapper.find('ForwardRef').filterWhere((button) => button.prop('icon') === 'refresh')).toHaveLength(0); }); test('when isCurrent is true, should render the current version text', () => { const props = { ...baseProps, isCurrent: true, }; const wrapper = shallow(<EditedPostItem {...props}/>); expect(wrapper.find('.edit-post-history__current__indicator')).toHaveLength(1); }); });
2,734
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history/edited_post_item
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_edit_history/edited_post_item/__snapshots__/edited_post_item.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_edit_history/edited_post_item should match snapshot 1`] = ` <CompassThemeProvider theme={Object {}} > <div className="edit-post-history__container" onClick={[Function]} > <PostAriaLabelDiv className="a11y__section post" id="searchResult_post_id" post={ Object { "channel_id": "", "create_at": 0, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "post_id", "is_pinned": false, "message": "post message", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } > <div aria-hidden="true" className="edit-post-history__title__container" > <div className="edit-post-history__date__badge__container" > <ForwardRef aria-label="Toggle to see an old message." className="edit-post-history__icon__button" compact={true} icon="chevron-right" size="sm" /> <span className="edit-post-history__date" > <Connect(injectIntl(Timestamp)) ranges={ Array [ Object { "display": <Memo(MemoizedFormattedMessage) defaultMessage="Today" id="date_separator.today" />, "equals": Array [ "day", 0, ], }, Object { "display": <Memo(MemoizedFormattedMessage) defaultMessage="Yesterday" id="date_separator.yesterday" />, "equals": Array [ "day", -1, ], }, ] } value={0} /> </span> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="hidden-xs" id="editPostRestoreTooltip" > Restore this version </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <ForwardRef aria-label="Select to restore an old message." className="edit-post-history__icon__button restore-icon" compact={true} icon="restore" onClick={[Function]} size="sm" /> </OverlayTrigger> </div> </PostAriaLabelDiv> </div> </CompassThemeProvider> `; exports[`components/post_edit_history/edited_post_item should match snapshot when isCurrent is true 1`] = ` <CompassThemeProvider theme={Object {}} > <div className="edit-post-history__container edit-post-history__container__background" onClick={[Function]} > <PostAriaLabelDiv className="a11y__section post" id="searchResult_post_id" post={ Object { "channel_id": "", "create_at": 0, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "post_id", "is_pinned": false, "message": "post message", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } > <div aria-hidden="true" className="edit-post-history__title__container" > <div className="edit-post-history__date__badge__container" > <ForwardRef aria-label="Toggle to see an old message." className="edit-post-history__icon__button" compact={true} icon="chevron-down" size="sm" /> <span className="edit-post-history__date" > <Connect(injectIntl(Timestamp)) ranges={ Array [ Object { "display": <Memo(MemoizedFormattedMessage) defaultMessage="Today" id="date_separator.today" />, "equals": Array [ "day", 0, ], }, Object { "display": <Memo(MemoizedFormattedMessage) defaultMessage="Yesterday" id="date_separator.yesterday" />, "equals": Array [ "day", -1, ], }, ] } value={0} /> </span> <div className="edit-post-history__current__indicator" > Current Version </div> </div> </div> <div className="edit-post-history__content_container" > <div className="edit-post-history__header" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_id/image?_=0" /> </span> <div className="edit-post-history__header__username" > <Connect(UserProfile) disablePopover={true} hasMention={true} userId="user_id" /> </div> </div> <div className="post__content" > <div className="search-item-snippet post__body" > <Connect(PostMessageView) isRHS={true} post={ Object { "channel_id": "", "create_at": 0, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "post_id", "is_pinned": false, "message": "post message", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } showPostEditedIndicator={false} /> </div> </div> </div> </PostAriaLabelDiv> </div> </CompassThemeProvider> `;
2,736
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_emoji/post_emoji.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {render, screen} from 'tests/react_testing_utils'; import PostEmoji from './post_emoji'; describe('PostEmoji', () => { const baseProps = { imageUrl: '/api/v4/emoji/1234/image', name: 'emoji', }; test('should render image when imageUrl is provided', () => { render(<PostEmoji {...baseProps}/>); expect(screen.getByTitle(':' + baseProps.name + ':')).toBeInTheDocument(); expect(screen.getByTitle(':' + baseProps.name + ':')).toHaveStyle(`backgroundImage: url(${baseProps.imageUrl})}`); }); test('should render shortcode text within span when imageUrl is provided', () => { render(<PostEmoji {...baseProps}/>); expect(screen.getByTitle(':' + baseProps.name + ':')).toHaveTextContent(`:${baseProps.name}:`); }); test('should render original text when imageUrl is empty', () => { const props = { ...baseProps, imageUrl: '', }; render(<PostEmoji {...props}/>); expect(screen.queryByTitle(':' + baseProps.name + ':')).not.toBeInTheDocument(); expect(screen.getByText(`:${props.name}:`)).toBeInTheDocument(); }); });
2,738
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_markdown/index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {TestHelper} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import {makeGetMentionKeysForPost} from './index'; describe('makeGetMentionKeysForPost', () => { const channel = TestHelper.getChannelMock({}); const team = TestHelper.getTeamMock({group_constrained: false}); let user = TestHelper.getUserMock({ username: 'a123', }); user = {...user, notify_props: { ...user.notify_props, channel: 'true', }}; const group = TestHelper.getGroupMock({ id: '123', name: 'developers', allow_reference: true, delete_at: 0, }); const baseState = { entities: { users: { currentUserId: user.id, profiles: { [user.id]: user, }, }, groups: { syncables: {}, groups: { [group.id]: group, }, myGroups: [ group.id, ], }, teams: { teams: { [team.id]: team, }, groupsAssociatedToTeam: { [team.id]: {ids: []}, }, }, channels: { channels: { [channel.id]: channel, }, groupsAssociatedToChannel: { [channel.id]: {ids: [group]}, }, }, general: { config: {}, }, preferences: { myPreferences: {}, }, }, } as GlobalState; it('should return all mentionKeys', () => { const post = TestHelper.getPostMock({ props: { disable_group_highlight: false, mentionHighlightDisabled: false, }, }); const getMentionKeysForPost = makeGetMentionKeysForPost(); const results = getMentionKeysForPost(baseState, post, channel); const expected = [{key: '@channel'}, {key: '@all'}, {key: '@here'}, {key: '@a123'}, {key: '@developers'}]; expect(results).toEqual(expected); }); it('should return mentionKeys without groups', () => { const post = TestHelper.getPostMock({ props: { disable_group_highlight: true, mentionHighlightDisabled: false, }, }); const getMentionKeysForPost = makeGetMentionKeysForPost(); const results = getMentionKeysForPost(baseState, post, channel); const expected = [{key: '@channel'}, {key: '@all'}, {key: '@here'}, {key: '@a123'}]; expect(results).toEqual(expected); }); it('should return group mentions and all mentions without channel mentions', () => { const post = TestHelper.getPostMock({ props: { disable_group_highlight: false, mentionHighlightDisabled: true, }, }); const getMentionKeysForPost = makeGetMentionKeysForPost(); const results = getMentionKeysForPost(baseState, post, channel); const expected = [{key: '@a123'}, {key: '@developers'}]; expect(results).toEqual(expected); }); it('should return all mentions without group mentions and channel mentions', () => { const post = TestHelper.getPostMock({ props: { disable_group_highlight: true, mentionHighlightDisabled: true, }, }); const getMentionKeysForPost = makeGetMentionKeysForPost(); const results = getMentionKeysForPost(baseState, post, channel); const expected = [{key: '@a123'}]; expect(results).toEqual(expected); }); });
2,740
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_markdown/post_markdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {Post, PostType} from '@mattermost/types/posts'; import {Posts} from 'mattermost-redux/constants'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import type {PluginComponent} from 'types/store/plugins'; import PostMarkdown from './post_markdown'; describe('components/PostMarkdown', () => { const baseProps = { imageProps: {} as Record<string, unknown>, pluginHooks: [], message: 'message', post: TestHelper.getPostMock(), mentionKeys: [{key: 'a'}, {key: 'b'}, {key: 'c'}], channelId: 'channel-id', channel: TestHelper.getChannelMock(), currentTeam: TestHelper.getTeamMock(), hideGuestTags: false, isMilitaryTime: false, timezone: '', highlightKeys: [], hasPluginTooltips: false, isUserCanManageMembers: false, isEnterpriseOrCloudOrSKUStarterFree: true, isEnterpriseReady: false, dispatch: jest.fn(), }; const state = {entities: { posts: { posts: {}, postsInThread: {}, }, channels: {}, teams: { teams: { currentTeamId: {}, }, }, preferences: { myPreferences: { }, }, groups: { groups: {}, myGroups: [], }, users: { currentUserId: '', profiles: {}, }, emojis: {customEmoji: {}}, general: {config: {}, license: {}}, }, }; test('should not error when rendering without a post', () => { const props = {...baseProps}; Reflect.deleteProperty(props, 'post'); renderWithContext(<PostMarkdown {...props}/>, state); expect(screen.getByText('message')).toBeInTheDocument(); }); test('should render properly with an empty post', () => { renderWithContext( <PostMarkdown {...baseProps} post={{} as any} />, state); expect(screen.getByText('message')).toBeInTheDocument(); }); test('should render properly with a post', () => { const props = { ...baseProps, message: 'See ~test', post: TestHelper.getPostMock({ props: { channel_mentions: { test: { display_name: 'Test', team_name: 'test', }, }, }, }), }; renderWithContext(<PostMarkdown {...props}/>, state); const link = screen.getByRole('link'); expect(screen.getByText('See')).toBeInTheDocument(); expect(link).toHaveAttribute('data-channel-mention', 'test'); expect(link).toHaveAttribute('data-channel-mention-team', 'test'); expect(link).toHaveAttribute('href', '/test/channels/test'); expect(link).toHaveClass('mention-link'); }); test('should render properly without highlight a post', () => { const props = { ...baseProps, message: 'No highlight', options: { mentionHighlight: false, }, post: TestHelper.getPostMock({ props: { channel_mentions: { test: { display_name: 'Test', team_name: 'test', }, }, }, }), }; renderWithContext(<PostMarkdown {...props}/>, state); expect(screen.getByText('No highlight')).toBeInTheDocument(); expect(screen.queryByRole('link')).not.toBeInTheDocument(); }); test('should render properly without group highlight on a post', () => { const props = { ...baseProps, message: 'No @group highlight', options: {}, post: TestHelper.getPostMock({ props: { disable_group_highlight: true, }, }), }; renderWithContext(<PostMarkdown {...props}/>, state); const groupMention = screen.getByText('@group'); expect(screen.getByText('No', {exact: false})).toBeInTheDocument(); expect(groupMention).toBeInTheDocument(); expect(groupMention).toHaveAttribute('data-mention', 'group'); expect(groupMention).not.toHaveClass('mention-link'); expect(screen.getByText('highlight', {exact: false})).toBeInTheDocument(); }); test('should correctly pass postId down', () => { const props = { ...baseProps, post: TestHelper.getPostMock({ id: 'post_id', }), }; renderWithContext(<PostMarkdown {...props}/>, state); expect(screen.getByText('message')).toBeInTheDocument(); }); test('should render header change properly', () => { const props = { ...baseProps, post: TestHelper.getPostMock({ id: 'post_id', type: Posts.POST_TYPES.HEADER_CHANGE as PostType, props: { username: 'user', old_header: 'see ~test', new_header: 'now ~test', channel_mentions: { test: { display_name: 'Test', team_name: 'test', }, }, }, }), }; renderWithContext(<PostMarkdown {...props}/>, state); expect(screen.getByText('@user')).toBeInTheDocument(); expect(screen.getByText('updated the channel header')).toBeInTheDocument(); expect(screen.getByText('From:')).toBeInTheDocument(); expect(screen.getByText('see')).toBeInTheDocument(); expect(screen.getByText('To:')).toBeInTheDocument(); expect(screen.getByText('now')).toBeInTheDocument(); const testLink = screen.getAllByRole('link', {name: '~Test'}); expect(testLink).toHaveLength(2); expect(testLink[0]).toHaveAttribute('data-channel-mention', 'test'); expect(testLink[0]).toHaveAttribute('data-channel-mention-team', 'test'); expect(testLink[0]).toHaveAttribute('href', '/test/channels/test'); expect(screen.getAllByRole('link')[0]).toHaveClass('mention-link'); expect(testLink[1]).toHaveAttribute('data-channel-mention', 'test'); expect(testLink[1]).toHaveAttribute('data-channel-mention-team', 'test'); expect(testLink[1]).toHaveAttribute('href', '/test/channels/test'); expect(screen.getAllByRole('link')[1]).toHaveClass('mention-link'); }); test('plugin hooks can build upon other hook message updates', () => { const props = { ...baseProps, message: 'world', post: TestHelper.getPostMock({ message: 'world', props: { channel_mentions: { test: { display_name: 'Test', }, }, }, }), pluginHooks: [ { hook: (post: Post, updatedMessage: string) => { return 'hello ' + updatedMessage; }, }, { hook: (post: Post, updatedMessage: string) => { return updatedMessage + '!'; }, }, ] as PluginComponent[], }; renderWithContext(<PostMarkdown {...props}/>, state); expect(screen.queryByText('world', {exact: true})).not.toBeInTheDocument(); // hook message expect(screen.getByText('hello world!')).toBeInTheDocument(); }); test('plugin hooks can overwrite other hooks messages', () => { const props = { ...baseProps, message: 'world', post: TestHelper.getPostMock({ message: 'world', props: { channel_mentions: { test: { display_name: 'Test', }, }, }, }), pluginHooks: [ { hook: (post: Post) => { return 'hello ' + post.message; }, }, { hook: (post: Post) => { return post.message + '!'; }, }, ] as PluginComponent[], }; renderWithContext(<PostMarkdown {...props}/>, state); expect(screen.queryByText('world', {exact: true})).not.toBeInTheDocument(); expect(screen.queryByText('world!', {exact: true})).toBeInTheDocument(); }); });
2,751
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_profile_picture/post_profile_picture.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ComponentProps} from 'react'; import {render, screen} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import PostProfilePicture from './post_profile_picture'; type Props = ComponentProps<typeof PostProfilePicture>; describe('components/PostProfilePicture', () => { const user = TestHelper.getUserMock({ id: 'defaultuser', }); const post = TestHelper.getPostMock({ user_id: 'defaultuser', }); const baseProps: Props = { availabilityStatusOnPosts: 'true', enablePostIconOverride: true, compactDisplay: true, hasImageProxy: true, isBusy: true, post, user, isBot: Boolean(user.is_bot), }; test('no status and post icon override specified, default props', () => { const props: Props = baseProps; render( <PostProfilePicture {...props}/>, ); expect(screen.queryByLabelText('Online Icon')).not.toBeInTheDocument(); // no status is given, 'Offline Icon' should be in the dom as a fallback expect(screen.getByLabelText('Offline Icon')).toBeInTheDocument(); }); test('status and post icon override specified, default props', () => { const props: Props = { ...baseProps, status: 'away', postIconOverrideURL: 'http://example.com/image.png', }; render( <PostProfilePicture {...props}/>, ); // status is given, 'Away Icon' should be in the dom expect(screen.getByLabelText('Away Icon')).toBeInTheDocument(); expect(screen.queryByLabelText('Online Icon')).not.toBeInTheDocument(); expect(screen.queryByLabelText('Offline Icon')).not.toBeInTheDocument(); expect(screen.getAllByRole('img')).toHaveLength(2); }); });
2,756
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel} from '@mattermost/types/channels'; import type {Team, TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {Constants} from 'utils/constants'; import {isChannelLoading} from './index'; describe('components/post_view/index', () => { test('should return false if loading a permalink view', () => { expect(isChannelLoading({postid: 'postId'})).toEqual(false); }); test('should return true if channel or if team data is not present', () => { expect(isChannelLoading({}, {id: 'channelId'} as Channel)).toEqual(true); expect(isChannelLoading({}, undefined, {id: 'teamId'} as Team)).toEqual(true); }); test('should return true if channel is a DM and indetifier is not the same as teammate name', () => { const channel = {type: Constants.DM_CHANNEL, name: 'myname'} as Channel; expect(isChannelLoading({identifier: 'otherUsername'}, channel, {id: 'teamId'} as Team, {username: 'diffrentName'} as UserProfile)).toEqual(true); }); test('should return true if channel is a GM and indetifier is not the same as channel name', () => { const channel = {type: Constants.GM_CHANNEL, name: 'username'} as Channel; expect(isChannelLoading({identifier: 'notTheSameName'}, channel, {id: 'teamId'} as Team)).toEqual(true); }); test('should return true if channel team id is not the same as current team id', () => { const channel = {type: Constants.DM_CHANNEL, name: 'username'} as Channel; expect(isChannelLoading({identifier: 'username'}, channel, {id: 'teamId'} as Team)).toEqual(false); }); test('should return true if teamMemberships exist but team is not part of membership', () => { const channel = {type: Constants.DM_CHANNEL, name: 'username'} as Channel; expect(isChannelLoading({identifier: 'username'}, channel, {id: 'teamId'} as Team, undefined, {differentTeamId: {} as TeamMembership})).toEqual(true); }); });
2,758
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_aria_label_div.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import * as reactIntl from 'react-intl'; import enMessages from 'i18n/en.json'; import esMessages from 'i18n/es.json'; import {mockStore} from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; import PostAriaLabelDiv from './post_aria_label_div'; import type {Props} from './post_aria_label_div'; jest.mock('react-intl', () => ({ ...jest.requireActual('react-intl'), useIntl: jest.fn(), })); describe('PostAriaLabelDiv', () => { const author = TestHelper.getUserMock({ username: 'some_user', }); const baseState = { entities: { emojis: { customEmoji: {}, }, general: { config: {}, }, posts: { reactions: {}, }, preferences: { myPreferences: {}, }, users: { profiles: { [author.id]: author, }, }, }, }; const baseProps = { post: TestHelper.getPostMock({ user_id: author.id, message: 'This is a test.', }), } as Omit<Props, 'ref'>; test('should render aria-label in the given locale', () => { const {mountOptions} = mockStore(baseState); (reactIntl.useIntl as jest.Mock).mockImplementation(() => reactIntl.createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'})); let wrapper = mount(<PostAriaLabelDiv {...baseProps}/>, mountOptions); let div = wrapper.childAt(0); expect(div.prop('aria-label')).toContain(author.username); expect(div.prop('aria-label')).toContain('January'); (reactIntl.useIntl as jest.Mock).mockImplementation(() => reactIntl.createIntl({locale: 'es', messages: esMessages, defaultLocale: 'es'})); wrapper = mount(<PostAriaLabelDiv {...baseProps}/>, mountOptions); div = wrapper.childAt(0); expect(div.prop('aria-label')).toContain(author.username); expect(div.prop('aria-label')).toContain('enero'); }); test('should pass other props through to the rendered div', () => { const {mountOptions} = mockStore(baseState); (reactIntl.useIntl as jest.Mock).mockImplementation(() => reactIntl.createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'})); let props = baseProps; let wrapper = mount(<PostAriaLabelDiv {...props}/>, mountOptions); let div = wrapper.childAt(0); expect(div.prop('className')).toBeUndefined(); expect(div.prop('data-something')).toBeUndefined(); expect(div.children()).toHaveLength(0); props = { ...props, className: 'some-class', 'data-something': 'something', } as Props; wrapper = mount( <PostAriaLabelDiv {...props}> <p>{'This is a paragraph.'}</p> </PostAriaLabelDiv >, mountOptions, ); div = wrapper.childAt(0); expect(div.prop('className')).toBe('some-class'); expect(div.prop('data-something')).toBe('something'); expect(div.children()).toHaveLength(1); }); });
2,761
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_view.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {Preferences} from 'mattermost-redux/constants'; import PostList from './post_list'; import PostView from './post_view'; describe('components/post_view/post_view', () => { const baseProps = { lastViewedAt: 12345678, isFirstLoad: false, channelLoading: false, channelId: '1234', focusedPostId: '12345', unreadScrollPosition: Preferences.UNREAD_SCROLL_POSITION_START_FROM_LEFT, }; jest.useFakeTimers(); let rafSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => setTimeout(cb, 16)); beforeEach(() => { rafSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => setTimeout(cb, 16)); }); afterEach(() => { rafSpy.mockRestore(); }); test('should match snapshot for channel loading', () => { const wrapper = shallow(<PostView {...{...baseProps, channelLoading: true}}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for loaderForChangeOfPostsChunk', () => { const wrapper = shallow(<PostView {...baseProps}/>); wrapper.setState({loaderForChangeOfPostsChunk: true}); expect(wrapper).toMatchSnapshot(); }); test('unreadChunkTimeStamp should be set for first load of channel', () => { const wrapper = shallow(<PostView {...{...baseProps, isFirstLoad: true}}/>); expect(wrapper.state('unreadChunkTimeStamp')).toEqual(baseProps.lastViewedAt); }); test('changeUnreadChunkTimeStamp', () => { const wrapper = shallow(<PostView {...{...baseProps, isFirstLoad: true}}/>); expect(wrapper.state('unreadChunkTimeStamp')).toEqual(baseProps.lastViewedAt); wrapper.find(PostList).prop<(lastViewedAt?: string) => void>('changeUnreadChunkTimeStamp')('1234678'); expect(wrapper.state('unreadChunkTimeStamp')).toEqual('1234678'); expect(wrapper.state('loaderForChangeOfPostsChunk')).toEqual(true); jest.runOnlyPendingTimers(); expect(wrapper.state('loaderForChangeOfPostsChunk')).toEqual(false); }); });
2,764
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/__snapshots__/post_view.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/post_view should match snapshot for channel loading 1`] = ` <div id="post-list" > <LoadingScreen centered={true} /> </div> `; exports[`components/post_view/post_view should match snapshot for loaderForChangeOfPostsChunk 1`] = ` <div id="post-list" > <LoadingScreen centered={true} /> </div> `;
2,770
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/channel_intro_message/add_members_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import type {Channel} from '@mattermost/types/channels'; import * as teams from 'mattermost-redux/selectors/entities/teams'; import mockStore from 'tests/test_store'; import AddMembersButton from './add_members_button'; describe('components/post_view/AddMembersButton', () => { const channel = { create_at: 1508265709607, creator_id: 'creator_id', delete_at: 0, display_name: 'test channel', header: 'test', id: 'channel_id', last_post_at: 1508265709635, name: 'testing', purpose: 'test', team_id: 'team-id', type: 'O', update_at: 1508265709607, } as Channel; const initialState = { entities: { teams: { currentTeamId: 'team-id', }, users: { profiles: { 'test-user-id': { id: 'test-user-id', roles: 'system_role', }, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission']}, team_role: {permissions: ['test_team_permission']}, channel_role: {permissions: ['test_channel_permission']}, }, }, }, }; const store = mockStore(initialState); jest.spyOn(teams, 'getCurrentTeamId').mockReturnValue('team-id'); test('should match snapshot, less than limit', () => { const props = { totalUsers: 10, usersLimit: 100, channel, }; const wrapper = mount( <Provider store={store}> <AddMembersButton {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, more than limit', () => { const props = { totalUsers: 100, usersLimit: 10, channel, }; const wrapper = mount( <Provider store={store}> <AddMembersButton {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, setHeader and pluginButtons', () => { const pluginButtons = ( <button> {'Create a board'} </button> ); const setHeader = ( <button> {'Create a board'} </button> ); const props = { totalUsers: 100, usersLimit: 10, channel, setHeader, pluginButtons, }; const wrapper = mount( <Provider store={store}> <AddMembersButton {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); });
2,772
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/channel_intro_message/channel_intro_message.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {Channel, ChannelType} from '@mattermost/types/channels'; import type {UserProfile} from '@mattermost/types/users'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {Constants} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import ChannelIntroMessage from './channel_intro_message'; describe('components/post_view/ChannelIntroMessages', () => { const channel = { create_at: 1508265709607, creator_id: 'creator_id', delete_at: 0, display_name: 'test channel', header: 'test', id: 'channel_id', last_post_at: 1508265709635, name: 'testing', purpose: 'test', team_id: 'team-id', type: 'O', update_at: 1508265709607, } as Channel; const user1 = {id: 'user1', roles: 'system_user'}; const users = [ {id: 'user1', roles: 'system_user'}, {id: 'guest1', roles: 'system_guest'}, {id: 'test-user-id', roles: 'system_user'}, ] as UserProfile[]; const baseProps = { currentUserId: 'test-user-id', channel, fullWidth: true, locale: 'en', channelProfiles: [], enableUserCreation: false, teamIsGroupConstrained: false, creatorName: 'creatorName', stats: {}, usersLimit: 10, actions: { getTotalUsersStats: jest.fn().mockResolvedValue([]), }, }; const initialState = { entities: { general: {config: {}}, users: { profiles: { user1: TestHelper.getUserMock({ id: 'user1', username: 'my teammate', }), }, }, roles: { roles: {}, }, channels: {roles: {channel_id: ['system_user']}, currentChannelId: 'channel_id', myMembers: {}, }, teams: { teams: {}, }, preferences: { myPreferences: {}, }, }, plugins: { components: {}, }, } as any; describe('test Open Channel', () => { test('should match component state, without boards', () => { renderWithContext( <ChannelIntroMessage{...baseProps}/>, initialState, ); const beginningHeading = screen.getByText('Beginning of test channel'); expect(beginningHeading).toBeInTheDocument(); expect(beginningHeading).toHaveClass('channel-intro__title'); expect(screen.getByText(`This is the start of the test channel channel, created by ${baseProps.creatorName} on October 17, 2017.`)); expect(screen.getByText('Any member can join and read this channel.')).toBeInTheDocument(); }); }); describe('test Group Channel', () => { const groupChannel = { ...channel, type: Constants.GM_CHANNEL as ChannelType, }; const props = { ...baseProps, channel: groupChannel, }; test('should match component state, no profiles', () => { renderWithContext( <ChannelIntroMessage {...props} />, initialState, ); expect(screen.queryByText('Beginning of test channel')).not.toBeInTheDocument(); expect(screen.queryByText('Any member can join and read this channel.')).not.toBeInTheDocument(); // there are no profiles in the dom, channel type is GM_CHANNEL, teammate text should be displayed expect(screen.getByText('This is the start of your group message history with these teammates. Messages and files shared here are not shown to people outside this area.')).toBeInTheDocument(); expect(screen.getByText('This is the start of your', {exact: false})).toHaveClass('channel-intro-text'); }); test('should match component state, with profiles', () => { renderWithContext( <ChannelIntroMessage {...props} channelProfiles={users} />, initialState, ); expect(screen.getByText('This is the start of your group message history with test channel', {exact: false})).toBeInTheDocument(); const headerDialog = screen.getByLabelText('Set a Header dialog'); expect(headerDialog).toBeInTheDocument(); expect(headerDialog).toHaveTextContent('Set a Header'); expect(headerDialog).toHaveClass('style--none intro-links color--link channelIntroButton'); // one for user1 and one for guest const image = screen.getAllByAltText('user profile image'); expect(image).toHaveLength(2); expect(image[0]).toHaveAttribute('src', '/api/v4/users/user1/image?_=0'); expect(image[0]).toHaveAttribute('loading', 'lazy'); expect(image[1]).toHaveAttribute('src', '/api/v4/users/guest1/image?_=0'); expect(image[1]).toHaveAttribute('loading', 'lazy'); const editIcon = screen.getByTitle('Edit Icon'); expect(editIcon).toBeInTheDocument(); expect(editIcon).toHaveClass('icon-pencil-outline'); const notificationPreferencesButton = screen.getByText('Notification Preferences'); expect(notificationPreferencesButton).toBeInTheDocument(); }); }); describe('test DIRECT Channel', () => { const directChannel = { ...channel, type: Constants.DM_CHANNEL as ChannelType, }; const props = { ...baseProps, channel: directChannel, }; test('should match component state, without teammate', () => { renderWithContext( <ChannelIntroMessage {...props} />, initialState, ); const message = screen.getByText('This is the start of your direct message history with this teammate', {exact: false}); expect(message).toBeInTheDocument(); expect(message).toHaveClass('channel-intro-text'); }); test('should match component state, with teammate', () => { renderWithContext( <ChannelIntroMessage {...props} teammate={user1 as UserProfile} teammateName='my teammate' />, initialState, ); expect(screen.getByText('This is the start of your direct message history with my teammate', {exact: false})).toBeInTheDocument(); const teammate = screen.getByLabelText('my teammate'); expect(teammate).toBeInTheDocument(); expect(teammate).toHaveTextContent('my teammate'); expect(teammate).toHaveClass('user-popover style--none'); const image = screen.getByRole('img'); expect(image).toBeInTheDocument(); expect(image).toHaveAttribute('src', '/api/v4/users/user1/image?_=0'); expect(image).toHaveAttribute('loading', 'lazy'); const headerDialog = screen.getByLabelText('Set a Header dialog'); expect(headerDialog).toBeInTheDocument(); expect(headerDialog).toHaveTextContent('Set a Header'); expect(headerDialog).toHaveClass('style--none intro-links color--link channelIntroButton'); const editIcon = screen.getByTitle('Edit Icon'); expect(editIcon).toBeInTheDocument(); expect(editIcon).toHaveClass('icon-pencil-outline'); }); }); describe('test DEFAULT Channel', () => { const directChannel = { ...channel, name: Constants.DEFAULT_CHANNEL, type: Constants.OPEN_CHANNEL as ChannelType, }; const props = { ...baseProps, channel: directChannel, }; test('should match component state, readonly', () => { renderWithContext( <ChannelIntroMessage {...props} isReadOnly={true} />, initialState, ); const beginningHeading = screen.getByText('Beginning of test channel'); expect(beginningHeading).toBeInTheDocument(); expect(beginningHeading).toHaveClass('channel-intro__title'); expect(screen.getByText('Welcome to test channel!')).toBeInTheDocument(); expect(screen.getByText('Messages can only be posted by system admins. Everyone automatically becomes a permanent member of this channel when they join the team.', {exact: false})).toBeInTheDocument(); }); test('should match component state without any permission', () => { renderWithContext( <ChannelIntroMessage {...props} teamIsGroupConstrained={true} />, initialState, ); //no permission is given, invite link should not be in the dom expect(screen.queryByText('Add other groups to this team')).not.toBeInTheDocument(); const beginningHeading = screen.getByText('Beginning of test channel'); expect(beginningHeading).toBeInTheDocument(); expect(beginningHeading).toHaveClass('channel-intro__title'); expect(screen.getByText('Welcome to test channel!')).toBeInTheDocument(); expect(screen.getByText('Post messages here that you want everyone to see. Everyone automatically becomes a permanent member of this channel when they join the team.', {exact: false})).toBeInTheDocument(); }); }); describe('test OFF TOPIC Channel', () => { const directChannel = { ...channel, type: Constants.OPEN_CHANNEL as ChannelType, name: Constants.OFFTOPIC_CHANNEL, display_name: Constants.OFFTOPIC_CHANNEL, }; const props = { ...baseProps, channel: directChannel, }; test('should match component state', () => { renderWithContext( <ChannelIntroMessage {...props} />, initialState, ); expect(screen.getByText('Beginning of off-topic')).toBeInTheDocument(); screen.getByText('This is the start of off-topic, a channel for non-work-related conversations.'); expect(screen.getByText('This is the start of off-topic, a channel for non-work-related conversations.')).toHaveClass('channel-intro__content'); // stats.total_users_count is not specified, loading icon should be in the dom screen.getByTitle('Loading Icon'); }); }); });
2,775
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/channel_intro_message
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/channel_intro_message/__snapshots__/add_members_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/AddMembersButton should match snapshot, less than limit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(AddMembersButton) channel={ Object { "create_at": 1508265709607, "creator_id": "creator_id", "delete_at": 0, "display_name": "test channel", "header": "test", "id": "channel_id", "last_post_at": 1508265709635, "name": "testing", "purpose": "test", "team_id": "team-id", "type": "O", "update_at": 1508265709607, } } totalUsers={10} usersLimit={100} > <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <TeamPermissionGate dispatch={[Function]} hasPermission={false} invert={false} permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" /> </Connect(TeamPermissionGate)> </Memo(AddMembersButton)> </Provider> `; exports[`components/post_view/AddMembersButton should match snapshot, more than limit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(AddMembersButton) channel={ Object { "create_at": 1508265709607, "creator_id": "creator_id", "delete_at": 0, "display_name": "test channel", "header": "test", "id": "channel_id", "last_post_at": 1508265709635, "name": "testing", "purpose": "test", "team_id": "team-id", "type": "O", "update_at": 1508265709607, } } totalUsers={100} usersLimit={10} > <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <TeamPermissionGate dispatch={[Function]} hasPermission={false} invert={false} permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" /> </Connect(TeamPermissionGate)> </Memo(AddMembersButton)> </Provider> `; exports[`components/post_view/AddMembersButton should match snapshot, setHeader and pluginButtons 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(AddMembersButton) channel={ Object { "create_at": 1508265709607, "creator_id": "creator_id", "delete_at": 0, "display_name": "test channel", "header": "test", "id": "channel_id", "last_post_at": 1508265709635, "name": "testing", "purpose": "test", "team_id": "team-id", "type": "O", "update_at": 1508265709607, } } pluginButtons={ <button> Create a board </button> } setHeader={ <button> Create a board </button> } totalUsers={100} usersLimit={10} > <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" > <TeamPermissionGate dispatch={[Function]} hasPermission={false} invert={false} permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team-id" /> </Connect(TeamPermissionGate)> </Memo(AddMembersButton)> </Provider> `;
2,778
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/combined_system_message/combined_system_message.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {UserProfile} from '@mattermost/types/users'; import {General, Posts} from 'mattermost-redux/constants'; import type {ActionFunc} from 'mattermost-redux/types/actions'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import CombinedSystemMessage from './combined_system_message'; import type {CombinedSystemMessage as CombinedSystemMessageType} from './combined_system_message'; describe('components/post_view/CombinedSystemMessage', () => { function emptyFunc() {} // eslint-disable-line no-empty-function const userProfiles = [ {id: 'added_user_id_1', username: 'AddedUser1'}, {id: 'added_user_id_2', username: 'AddedUser2'}, {id: 'removed_user_id_1', username: 'removed_username_1'}, {id: 'removed_user_id_2', username: 'removed_username_2'}, {id: 'current_user_id', username: 'current_username'}, {id: 'other_user_id', username: 'other_username'}, {id: 'user_id_1', username: 'User1'}, {id: 'user_id_2', username: 'User2'}, ] as unknown as UserProfile[]; const baseProps = { currentUserId: 'current_user_id', currentUsername: 'current_username', allUserIds: ['added_user_id_1', 'added_user_id_2', 'current_user_id', 'user_id_1'], allUsernames: [], messageData: [{ actorId: 'user_id_1', postType: Posts.POST_TYPES.ADD_TO_CHANNEL, userIds: ['added_user_id_1'], }, { actorId: 'user_id_1', postType: Posts.POST_TYPES.ADD_TO_CHANNEL, userIds: ['current_user_id'], }, { actorId: 'current_user_id', postType: Posts.POST_TYPES.ADD_TO_CHANNEL, userIds: ['added_user_id_2'], }], showJoinLeave: true, teammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, userProfiles, actions: { getMissingProfilesByIds: emptyFunc as unknown as (userIds: string[]) => ActionFunc, getMissingProfilesByUsernames: emptyFunc as unknown as (usernames: string[]) => ActionFunc, }, }; test('should match snapshot', () => { const wrapper = shallowWithIntl( <CombinedSystemMessage {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when join leave messages are turned off', () => { const wrapper = shallowWithIntl( <CombinedSystemMessage {...baseProps} showJoinLeave={false} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, "removed from channel" message when join leave messages are turned off', () => { const allUserIds = ['current_user_id', 'other_user_id_1', 'removed_user_id_1', 'removed_user_id_2']; const messageData = [{ actorId: 'current_user_id', postType: Posts.POST_TYPES.REMOVE_FROM_CHANNEL, userIds: ['removed_user_id_1'], }, { actorId: 'other_user_id_1', postType: Posts.POST_TYPES.REMOVE_FROM_CHANNEL, userIds: ['removed_user_id_2'], }]; const props = {...baseProps, messageData, allUserIds, showJoinLeave: false}; const wrapper = shallowWithIntl( <CombinedSystemMessage {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should call getMissingProfilesByIds and/or getMissingProfilesByUsernames on loadUserProfiles', () => { const props = { ...baseProps, allUserIds: [], actions: { getMissingProfilesByIds: jest.fn(), getMissingProfilesByUsernames: jest.fn(), }, }; const wrapper = shallowWithIntl( <CombinedSystemMessage {...props}/>, ); const instance = wrapper.instance() as CombinedSystemMessageType; instance.loadUserProfiles([], []); expect(props.actions.getMissingProfilesByIds).toHaveBeenCalledTimes(0); expect(props.actions.getMissingProfilesByUsernames).toHaveBeenCalledTimes(0); instance.loadUserProfiles(['user_id_1'], []); expect(props.actions.getMissingProfilesByIds).toHaveBeenCalledTimes(1); expect(props.actions.getMissingProfilesByIds).toHaveBeenCalledWith(['user_id_1']); expect(props.actions.getMissingProfilesByUsernames).toHaveBeenCalledTimes(0); instance.loadUserProfiles(['user_id_1', 'user_id_2'], ['user1']); expect(props.actions.getMissingProfilesByIds).toHaveBeenCalledTimes(2); expect(props.actions.getMissingProfilesByIds).toHaveBeenCalledWith(['user_id_1', 'user_id_2']); expect(props.actions.getMissingProfilesByUsernames).toHaveBeenCalledTimes(1); expect(props.actions.getMissingProfilesByUsernames).toHaveBeenCalledWith(['user1']); }); test('should render messages in chronological order', () => { const allUserIds = ['current_user_id', 'other_user_id_1', 'user_id_1', 'user_id_2', 'join_last']; const messageData = [{ actorId: 'current_user_id', postType: Posts.POST_TYPES.REMOVE_FROM_CHANNEL, userIds: ['removed_user_id_1'], }, { actorId: 'other_user_id_1', postType: Posts.POST_TYPES.ADD_TO_CHANNEL, userIds: ['removed_user_id_2'], }, { actorId: 'other_user_id_1', postType: Posts.POST_TYPES.REMOVE_FROM_CHANNEL, userIds: ['removed_user_id_2'], }, { actorId: 'user_id_1', postType: Posts.POST_TYPES.ADD_TO_CHANNEL, userIds: ['user_id_2'], }, { actorId: 'join_last', postType: Posts.POST_TYPES.JOIN_CHANNEL, userIds: [''], }]; const props = {...baseProps, messageData, allUserIds}; const wrapper = shallowWithIntl( <CombinedSystemMessage {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
2,781
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/combined_system_message/last_users.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Posts} from 'mattermost-redux/constants'; import {renderWithContext, screen, userEvent} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import LastUsers from './last_users'; describe('components/post_view/combined_system_message/LastUsers', () => { const formatOptions = { atMentions: true, mentionKeys: [{key: '@username2'}, {key: '@username3'}, {key: '@username4'}], mentionHighlight: false, }; const baseProps = { actor: 'user_1', expandedLocale: { id: 'combined_system_message.added_to_channel.many_expanded', defaultMessage: '{users} and {lastUser} **added to the channel** by {actor}.', }, formatOptions, postType: Posts.POST_TYPES.ADD_TO_CHANNEL, usernames: ['@username2', '@username3', '@username4 '], }; const initialState = { entities: { general: {config: {}}, users: { currentUserId: 'current_user_id', profiles: { user_1: TestHelper.getUserMock({}), }, }, groups: {groups: {}, myGroups: []}, emojis: {customEmoji: {}}, channels: {}, teams: { teams: {}, }, preferences: { myPreferences: {}, }, }, } as any; test('should match component state', () => { renderWithContext( <LastUsers {...baseProps}/>, initialState, ); expect(screen.getByText(getMentionKeyAt(0))).toBeInTheDocument(); expect(screen.getByText(getMentionKeyAt(0))).toHaveAttribute('data-mention', 'username2'); expect(screen.getByText('and')).toBeInTheDocument(); //there are 3 mention keys, so the text should read userEvent.click(screen.getByText(`${formatOptions.mentionKeys.length - 1} others`)); expect(screen.getByText('added to the channel')).toBeInTheDocument(); expect(screen.getByText(`by ${baseProps.actor}`, {exact: false})).toBeInTheDocument(); }); test('should match component state, expanded', () => { renderWithContext( <LastUsers {...baseProps}/>, initialState, ); //first key should be visible expect(screen.getByText(getMentionKeyAt(0))).toBeInTheDocument(); expect(screen.getByText(getMentionKeyAt(0))).toHaveAttribute('data-mention', 'username2'); //other keys should be hidden expect(screen.queryByText(getMentionKeyAt(1))).not.toBeInTheDocument(); expect(screen.queryByText(getMentionKeyAt(2))).not.toBeInTheDocument(); expect(screen.getByText('were', {exact: false})).toBeInTheDocument(); //setting {expand: true} in the state userEvent.click(screen.getByText(`${formatOptions.mentionKeys.length - 1} others`)); expect(screen.queryByText('were', {exact: false})).not.toBeInTheDocument(); //hidden keys should be visible expect(screen.getByText(getMentionKeyAt(1))).toBeInTheDocument(); expect(screen.getByText(getMentionKeyAt(1))).toHaveAttribute('data-mention', 'username3'); expect(screen.getByText(getMentionKeyAt(2))).toBeInTheDocument(); expect(screen.getByText(getMentionKeyAt(2))).toHaveAttribute('data-mention', 'username4'); expect(screen.getByText('added to the channel')).toBeInTheDocument(); expect(screen.getByText(`by ${baseProps.actor}`, {exact: false})).toBeInTheDocument(); }); function getMentionKeyAt(index: number) { return baseProps.formatOptions.mentionKeys[index].key; } });
2,783
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/combined_system_message
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/combined_system_message/__snapshots__/combined_system_message.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/CombinedSystemMessage should match snapshot 1`] = ` <Fragment> <Connect(Markdown) message="@AddedUser1 **added to the channel** by @User1." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@AddedUser1", }, Object { "key": undefined, }, Object { "key": "@User1", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="You were **added to the channel** by @User1." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "You", }, Object { "key": undefined, }, Object { "key": "@User1", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="@AddedUser2 **added to the channel** by you." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@AddedUser2", }, Object { "key": undefined, }, Object { "key": "you", }, ], "singleline": true, } } /> <br /> </Fragment> `; exports[`components/post_view/CombinedSystemMessage should match snapshot when join leave messages are turned off 1`] = ` <Fragment> <Connect(Markdown) message="You were **added to the channel** by @User1." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "You", }, Object { "key": undefined, }, Object { "key": "@User1", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="@AddedUser2 **added to the channel** by you." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@AddedUser2", }, Object { "key": undefined, }, Object { "key": "you", }, ], "singleline": true, } } /> <br /> </Fragment> `; exports[`components/post_view/CombinedSystemMessage should match snapshot, "removed from channel" message when join leave messages are turned off 1`] = ` <Fragment> <Connect(Markdown) message="@removed_username_1 was **removed from the channel**." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@removed_username_1", }, Object { "key": undefined, }, Object { "key": "you", }, ], "singleline": true, } } /> <br /> </Fragment> `; exports[`components/post_view/CombinedSystemMessage should render messages in chronological order 1`] = ` <Fragment> <Connect(Markdown) message="@removed_username_1 was **removed from the channel**." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@removed_username_1", }, Object { "key": undefined, }, Object { "key": "you", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="@removed_username_2 **added to the channel** by Someone." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@removed_username_2", }, Object { "key": undefined, }, Object { "key": "Someone", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="@removed_username_2 was **removed from the channel**." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@removed_username_2", }, Object { "key": undefined, }, Object { "key": "Someone", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="@User2 **added to the channel** by @User1." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "@User2", }, Object { "key": undefined, }, Object { "key": "@User1", }, ], "singleline": true, } } /> <br /> <Connect(Markdown) message="Someone **joined the channel**." options={ Object { "atMentions": true, "mentionHighlight": false, "mentionKeys": Array [ Object { "key": "Someone", }, Object { "key": undefined, }, Object { "key": "Someone", }, ], "singleline": true, } } /> <br /> </Fragment> `;
2,785
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/commented_on/commented_on.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import CommentedOn from 'components/post_view/commented_on/commented_on'; import CommentedOnFilesMessage from 'components/post_view/commented_on_files_message'; import {TestHelper} from 'utils/test_helper'; describe('components/post_view/CommentedOn', () => { const baseProps = { displayName: 'user_displayName', enablePostUsernameOverride: false, onCommentClick: jest.fn(), post: TestHelper.getPostMock({ id: 'post_id', message: 'text message', props: { from_webhook: 'true', override_username: 'override_username', }, update_at: 10, edit_at: 20, delete_at: 30, channel_id: 'channel_id', root_id: 'root_id', original_id: 'original_id', hashtags: 'hashtags', pending_post_id: 'pending_post_id', reply_count: 1, }), }; test('should match snapshot', () => { const wrapper = shallow(<CommentedOn {...baseProps}/>); expect(wrapper).toMatchSnapshot(); wrapper.setProps({enablePostUsernameOverride: true}); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(CommentedOnFilesMessage).exists()).toBe(false); const newPost = { id: 'post_id', message: '', file_ids: ['file_id_1', 'file_id_2'], }; wrapper.setProps({post: newPost, enablePostUsernameOverride: false}); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(CommentedOnFilesMessage).exists()).toBe(true); }); test('should match snapshots for post with props.pretext as message', () => { const newPost = { id: 'post_id', message: '', props: { from_webhook: 'true', override_username: 'override_username', attachments: [{ pretext: 'This is a pretext', }], }, }; const newProps = { ...baseProps, post: { ...baseProps.post, ...newPost, }, enablePostUsernameOverride: true, }; const wrapper = shallow(<CommentedOn {...newProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshots for post with props.title as message', () => { const newPost = { id: 'post_id', message: '', props: { from_webhook: 'true', override_username: 'override_username', attachments: [{ pretext: '', title: 'This is a title', }], }, }; const newProps = { ...baseProps, post: { ...baseProps.post, ...newPost, }, enablePostUsernameOverride: true, }; const wrapper = shallow(<CommentedOn {...newProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshots for post with props.text as message', () => { const newPost = { id: 'post_id', message: '', props: { from_webhook: 'true', override_username: 'override_username', attachments: [{ pretext: '', title: '', text: 'This is a text', }], }, }; const newProps = { ...baseProps, post: { ...baseProps.post, ...newPost, }, enablePostUsernameOverride: true, }; const wrapper = shallow(<CommentedOn {...newProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshots for post with props.fallback as message', () => { const newPost = { id: 'post_id', message: '', props: { from_webhook: 'true', override_username: 'override_username', attachments: [{ pretext: '', title: '', text: '', fallback: 'This is fallback message', }], }, }; const newProps = { ...baseProps, post: { ...baseProps.post, ...newPost, }, enablePostUsernameOverride: true, }; const wrapper = shallow(<CommentedOn {...newProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should call onCommentClick on click of text message', () => { const wrapper = shallow(<CommentedOn {...baseProps}/>); wrapper.find('a').first().simulate('click'); expect(baseProps.onCommentClick).toHaveBeenCalledTimes(1); }); test('Should trigger search with override_username', () => { const wrapper = shallow(<CommentedOn {...baseProps}/>); wrapper.setProps({enablePostUsernameOverride: true}); }); });
2,788
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/commented_on
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/commented_on/__snapshots__/commented_on.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/CommentedOn should match snapshot 1`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > text message </a> </span> </div> `; exports[`components/post_view/CommentedOn should match snapshot 2`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > text message </a> </span> </div> `; exports[`components/post_view/CommentedOn should match snapshot 3`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > <Connect(Component) parentPostId="post_id" /> </a> </span> </div> `; exports[`components/post_view/CommentedOn should match snapshots for post with props.fallback as message 1`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > This is fallback message </a> </span> </div> `; exports[`components/post_view/CommentedOn should match snapshots for post with props.pretext as message 1`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > This is a pretext </a> </span> </div> `; exports[`components/post_view/CommentedOn should match snapshots for post with props.text as message 1`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > This is a text </a> </span> </div> `; exports[`components/post_view/CommentedOn should match snapshots for post with props.title as message 1`] = ` <div className="post__link" data-testid="post-link" > <span> <MemoizedFormattedMessage defaultMessage="Commented on {name}'s message: " id="post_body.commentedOn" values={ Object { "name": <a className="theme user_name" > <Memo(Connect(UserProfile)) disablePopover={false} hasMention={true} userId="" /> </a>, } } /> <a className="theme" onClick={[MockFunction]} > This is a title </a> </span> </div> `;
2,789
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/commented_on_files_message/commented_on_files_message.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {render, renderWithContext, screen} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import CommentedOnFilesMessage from './commented_on_files_message'; describe('components/CommentedOnFilesMessage', () => { test('component state when no files', () => { render( <CommentedOnFilesMessage/>, ); //no file is given in props expect(screen.queryByTestId('fileInfo')).not.toBeInTheDocument(); }); test('should match component state for single file', () => { const fileInfos = [ TestHelper.getFileInfoMock({id: 'file_id_1', name: 'image_1.png', extension: 'png', create_at: 1}), ]; render( <CommentedOnFilesMessage fileInfos={fileInfos}/>, ); expect(screen.getByTestId('fileInfo')).toHaveTextContent('image_1.png'); }); test('should match component state for multiple files', () => { const fileInfos = [ TestHelper.getFileInfoMock({id: 'file_id_3', name: 'image_3.png', extension: 'png', create_at: 3}), TestHelper.getFileInfoMock({id: 'file_id_2', name: 'image_2.png', extension: 'png', create_at: 2}), TestHelper.getFileInfoMock({id: 'file_id_1', name: 'image_1.png', extension: 'png', create_at: 1}), ]; renderWithContext( <CommentedOnFilesMessage fileInfos={fileInfos}/>, ); // total files = 3 expect(screen.getByTestId('fileInfo')).toHaveTextContent('image_3.png plus 2 other files'); }); });
2,792
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/date_separator/date_separator.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import DateSeparator from './date_separator'; describe('components/post_view/DateSeparator', () => { const initialState = { entities: { general: { config: {}, }, preferences: { myPreferences: {}, }, }, } as any; test('should render Timestamp inside of a BasicSeparator and pass date/value to it', () => { const value = new Date('Fri Jan 12 2018 20:15:13 GMT+1200 (+12)'); renderWithContext( <DateSeparator date={value} />, initialState, ); expect(screen.getByTestId('basicSeparator')).toBeInTheDocument(); expect(screen.getByText('January 12, 2018')).toBeInTheDocument(); }); });
2,796
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings/button_binding/button_binding.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {AppBinding, AppCallResponse} from '@mattermost/types/apps'; import type {Post} from '@mattermost/types/posts'; import { renderWithContext, screen, userEvent, waitFor, } from 'tests/react_testing_utils'; import ButtonBinding from './button_binding'; describe('components/post_view/embedded_bindings/button_binding/', () => { const post = { id: 'some_post_id', channel_id: 'some_channel_id', root_id: 'some_root_id', } as Post; const binding: AppBinding = { app_id: 'some_app_id', label: 'some_label', location: 'some_location', form: { submit: { path: 'some_url', }, }, }; const callResponse: AppCallResponse = { type: 'ok', text: 'Nice job!', app_metadata: { bot_user_id: 'botuserid', bot_username: 'botusername', }, }; const baseProps = { post, userId: 'user_id', binding, actions: { handleBindingClick: jest.fn().mockResolvedValue({ data: callResponse, }), getChannel: jest.fn().mockResolvedValue({ data: { id: 'some_channel_id', team_id: 'some_team_id', }, }), postEphemeralCallResponseForPost: jest.fn(), openAppsModal: jest.fn(), }, }; const initialState = { entities: { general: {config: {}}, users: { profiles: { }, }, groups: {myGroups: []}, emojis: {}, channels: {}, teams: { teams: {}, }, preferences: { myPreferences: {}, }, }, }; test('should match default component state', () => { renderWithContext(<ButtonBinding {...baseProps}/>, initialState); screen.getByText('some_label'); }); test('should call doAppSubmit on click', async () => { renderWithContext(<ButtonBinding {...baseProps}/>, initialState); screen.getByText('some_label'); const submitButton = screen.getByRole('button'); userEvent.click(submitButton); expect(baseProps.actions.getChannel).toHaveBeenCalledWith('some_channel_id'); await waitFor(() => { expect(baseProps.actions.handleBindingClick).toHaveBeenCalledWith(binding, { app_id: 'some_app_id', channel_id: 'some_channel_id', location: '/in_post/some_location', post_id: 'some_post_id', root_id: 'some_root_id', team_id: 'some_team_id', }, expect.anything()); }); expect(baseProps.actions.postEphemeralCallResponseForPost).toHaveBeenCalledWith(callResponse, 'Nice job!', post); }); test('should handle error call response', async () => { const errorCallResponse = { type: 'error', text: 'The error', app_metadata: { bot_user_id: 'botuserid', }, }; const props = { ...baseProps, actions: { handleBindingClick: jest.fn().mockResolvedValue({ error: errorCallResponse, }), getChannel: jest.fn().mockResolvedValue({ data: { id: 'some_channel_id', team_id: 'some_team_id', }, }), postEphemeralCallResponseForPost: jest.fn(), openAppsModal: jest.fn(), }, }; renderWithContext(<ButtonBinding {...props}/>, initialState); screen.getByText('some_label'); const submitButton = screen.getByRole('button'); userEvent.click(submitButton); await waitFor(() => { expect(props.actions.postEphemeralCallResponseForPost).toHaveBeenCalledWith(errorCallResponse, 'The error', post); }); }); });
2,799
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings/embedded_binding/embedded_binding.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {AppBinding} from '@mattermost/types/apps'; import type {MessageAttachment as MessageAttachmentType} from '@mattermost/types/message_attachments'; import type {Post} from '@mattermost/types/posts'; import EmbeddedBinding from './embedded_binding'; describe('components/post_view/embedded_bindings/embedded_binding', () => { const post = { id: 'post_id', channel_id: 'channel_id', } as Post; const embed = { app_id: 'app_id', bindings: [] as AppBinding[], label: 'some text', description: 'some title', } as AppBinding; const baseProps = { post, embed, currentRelativeTeamUrl: 'dummy_team', }; test('should match snapshot', () => { const wrapper = shallow(<EmbeddedBinding {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the attachment has an emoji in the title', () => { const props = { ...baseProps, attachment: { title: 'Do you like :pizza:?', } as MessageAttachmentType, }; const wrapper = shallow(<EmbeddedBinding {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the attachment hasn\'t any emojis in the title', () => { const props = { ...baseProps, attachment: { title: 'Don\'t you like emojis?', } as MessageAttachmentType, }; const wrapper = shallow(<EmbeddedBinding {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the attachment has a link in the title', () => { const props = { ...baseProps, attachment: { title: 'Do you like https://mattermost.com?', } as MessageAttachmentType, }; const wrapper = shallow(<EmbeddedBinding {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
2,802
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings/embedded_binding
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings/embedded_binding/__snapshots__/embedded_binding.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/embedded_bindings/embedded_binding should match snapshot 1`] = ` <div className="attachment" onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--" > <h1 className="attachment__title" > <Connect(Markdown) message="some text" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" > <Connect(ShowMore) isAttachmentText={true} maxHeight={200} text="some title" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="some title" postId="post_id" /> </Connect(ShowMore)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/embedded_bindings/embedded_binding should match snapshot when the attachment has a link in the title 1`] = ` <div className="attachment" onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--" > <h1 className="attachment__title" > <Connect(Markdown) message="some text" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" > <Connect(ShowMore) isAttachmentText={true} maxHeight={200} text="some title" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="some title" postId="post_id" /> </Connect(ShowMore)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/embedded_bindings/embedded_binding should match snapshot when the attachment has an emoji in the title 1`] = ` <div className="attachment" onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--" > <h1 className="attachment__title" > <Connect(Markdown) message="some text" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" > <Connect(ShowMore) isAttachmentText={true} maxHeight={200} text="some title" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="some title" postId="post_id" /> </Connect(ShowMore)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/embedded_bindings/embedded_binding should match snapshot when the attachment hasn't any emojis in the title 1`] = ` <div className="attachment" onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--" > <h1 className="attachment__title" > <Connect(Markdown) message="some text" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" > <Connect(ShowMore) isAttachmentText={true} maxHeight={200} text="some title" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="some title" postId="post_id" /> </Connect(ShowMore)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `;
2,804
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/embedded_bindings/select_binding/select_binding.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {AppBinding, AppCallResponse} from '@mattermost/types/apps'; import type {Post} from '@mattermost/types/posts'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import SelectBinding, {RawSelectBinding} from './select_binding'; describe('components/post_view/embedded_bindings/select_binding', () => { const post = { id: 'some_post_id', channel_id: 'some_channel_id', root_id: 'some_root_id', } as Post; const binding = { app_id: 'some_app_id', location: '/some_location', bindings: [ { app_id: 'some_app_id', label: 'Option 1', location: 'option1', form: { submit: { path: 'some_url_1', }, }, }, { app_id: 'some_app_id', label: 'Option 2', location: 'option2', form: { submit: { path: 'some_url_2', }, }, }, ] as AppBinding[], } as AppBinding; const callResponse: AppCallResponse = { type: 'ok', text: 'Nice job!', app_metadata: { bot_user_id: 'botuserid', bot_username: 'botusername', }, }; const baseProps = { post, userId: 'user_id', binding, actions: { handleBindingClick: jest.fn().mockResolvedValue({ data: callResponse, }), getChannel: jest.fn().mockResolvedValue({ data: { id: 'some_channel_id', team_id: 'some_team_id', }, }), postEphemeralCallResponseForPost: jest.fn(), openAppsModal: jest.fn(), }, }; const intl = { formatMessage: (message: {id: string; defaultMessage: string}) => { return message.defaultMessage; }, } as any; test('should start with nothing selected', () => { const wrapper = shallowWithIntl(<SelectBinding {...baseProps}/>); expect(wrapper.state()).toMatchObject({}); }); describe('handleSelected', () => { test('should call handleBindingClick', async () => { const props = { ...baseProps, actions: { handleBindingClick: jest.fn().mockResolvedValue({ data: { type: 'ok', text: 'Nice job!', app_metadata: { bot_user_id: 'botuserid', bot_username: 'botusername', }, }, }), getChannel: jest.fn().mockResolvedValue({ data: { id: 'some_channel_id', team_id: 'some_team_id', }, }), postEphemeralCallResponseForPost: jest.fn(), openAppsModal: jest.fn(), }, intl, }; const wrapper = shallow<RawSelectBinding>(<RawSelectBinding {...props}/>); await wrapper.instance().handleSelected({ text: 'Option 1', value: 'option1', }); expect(props.actions.getChannel).toHaveBeenCalledWith('some_channel_id'); expect(props.actions.handleBindingClick).toHaveBeenCalledWith({ app_id: 'some_app_id', label: 'Option 1', location: 'option1', form: { submit: { path: 'some_url_1', }, }, }, { app_id: 'some_app_id', channel_id: 'some_channel_id', location: '/in_post/option1', post_id: 'some_post_id', root_id: 'some_root_id', team_id: 'some_team_id', }, expect.anything()); expect(props.actions.postEphemeralCallResponseForPost).toHaveBeenCalledWith(callResponse, 'Nice job!', post); }); }); test('should handle error call response', async () => { const errorResponse: AppCallResponse = { type: 'error', text: 'The error', app_metadata: { bot_user_id: 'botuserid', bot_username: 'botusername', }, }; const props = { ...baseProps, actions: { handleBindingClick: jest.fn().mockResolvedValue({ error: errorResponse, }), getChannel: jest.fn().mockResolvedValue({ data: { id: 'some_channel_id', team_id: 'some_team_id', }, }), postEphemeralCallResponseForPost: jest.fn(), openAppsModal: jest.fn(), }, intl, }; const wrapper = shallow<RawSelectBinding>(<RawSelectBinding {...props}/>); await wrapper.instance().handleSelected({ text: 'Option 1', value: 'option1', }); expect(props.actions.postEphemeralCallResponseForPost).toHaveBeenCalledWith(errorResponse, 'The error', post); }); });
2,806
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/failed_post_options/failed_post_options.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import FailedPostOptions from 'components/post_view/failed_post_options/failed_post_options'; import {renderWithContext, screen, userEvent} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; describe('components/post_view/FailedPostOptions', () => { const baseProps = { post: TestHelper.getPostMock(), actions: { createPost: jest.fn(), removePost: jest.fn(), }, }; test('should match default component state', () => { renderWithContext(<FailedPostOptions {...baseProps}/>); const retryLink = screen.getByText('Retry'); const cancelLink = screen.getByText('Cancel'); expect(retryLink).toBeInTheDocument(); expect(retryLink).toHaveClass('post-retry'); expect(retryLink).toHaveAttribute('href', '#'); expect(cancelLink).toBeInTheDocument(); expect(cancelLink).toHaveClass('post-cancel'); expect(cancelLink).toHaveAttribute('href', '#'); expect(screen.getAllByRole('link')).toHaveLength(2); }); test('should create post on retry', () => { const props = { ...baseProps, actions: { ...baseProps.actions, createPost: jest.fn(), }, }; renderWithContext(<FailedPostOptions {...props}/>); const retryLink = screen.getByText('Retry'); userEvent.click(retryLink); expect(props.actions.createPost.mock.calls.length).toBe(1); userEvent.click(retryLink); expect(props.actions.createPost.mock.calls.length).toBe(2); }); test('should remove post on cancel', () => { const props = { ...baseProps, actions: { ...baseProps.actions, removePost: jest.fn(), }, }; renderWithContext(<FailedPostOptions {...props}/>); const cancelLink = screen.getByText('Cancel'); userEvent.click(cancelLink); expect(props.actions.removePost.mock.calls.length).toBe(1); }); });
2,809
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/floating_timestamp/floating_timestamp.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import FloatingTimestamp from './floating_timestamp'; describe('components/post_view/FloatingTimestamp', () => { const baseProps = { isScrolling: true, createAt: 1234, toastPresent: true, isRhsPost: false, }; const initialState = { entities: { general: { config: {}, }, preferences: { myPreferences: {}, }, }, }; test('should match component state with given props', () => { renderWithContext(<FloatingTimestamp {...baseProps}/>, initialState); const floatingTimeStamp = screen.getByTestId('floatingTimestamp'); const time = screen.getByText('January 01, 1970'); expect(floatingTimeStamp).toBeInTheDocument(); expect(floatingTimeStamp).toHaveClass('post-list__timestamp scrolling toastAdjustment'); expect(time).toBeInTheDocument(); expect(time).toHaveAttribute('datetime', '1970-01-01T00:00:01.234'); }); });
2,814
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments/action_button/action_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Preferences} from 'mattermost-redux/constants'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import {changeOpacity} from 'mattermost-redux/utils/theme_utils'; import {renderWithContext, screen, userEvent} from 'tests/react_testing_utils'; import ActionButton from './action_button'; describe('components/post_view/message_attachments/action_button.jsx', () => { const baseProps = { action: {id: 'action_id_1', name: 'action_name_1', cookie: 'cookie-contents'}, handleAction: jest.fn(), theme: Preferences.THEMES.denim as unknown as Theme, }; test('should match default component state with given props', () => { renderWithContext(<ActionButton {...baseProps}/>); const button = screen.getByRole('button'); expect(button).toHaveAttribute('data-action-cookie', 'cookie-contents'); expect(button).toHaveAttribute('data-action-id', 'action_id_1'); const loadingIcon = screen.getByTitle('Loading Icon'); expect(loadingIcon).toHaveClass('fa fa-spinner fa-fw fa-pulse spinner'); }); test('should call handleAction on click', () => { renderWithContext(<ActionButton {...baseProps}/>); const button = screen.getByRole('button'); userEvent.click(button); expect(baseProps.handleAction).toHaveBeenCalledTimes(1); }); test('should have correct styles when provided color from theme', () => { const props = { ...baseProps, action: {...baseProps.action, style: 'onlineIndicator'}, }; renderWithContext(<ActionButton {...props}/>); const button = screen.getByRole('button'); expect(button).toHaveStyle(`background-color: ${changeOpacity(Preferences.THEMES.denim.onlineIndicator, 0.08)}`); expect(button).toHaveStyle(`color: ${Preferences.THEMES.denim.onlineIndicator}`); }); test('should have correct styles when provided color from not default theme', () => { const props = { ...baseProps, theme: Preferences.THEMES.indigo as unknown as Theme, action: {...baseProps.action, style: 'danger'}, }; renderWithContext(<ActionButton {...props}/>); const button = screen.getByRole('button'); expect(button).toHaveStyle(`background-color: ${changeOpacity(Preferences.THEMES.indigo.errorTextColor, 0.08)}`); expect(button).toHaveStyle(`color: ${Preferences.THEMES.indigo.errorTextColor}`); }); test('should have correct styles when provided status color', () => { const props = { ...baseProps, action: {...baseProps.action, style: 'success'}, }; renderWithContext(<ActionButton {...props}/>); const button = screen.getByRole('button'); expect(button).toHaveStyle(`background-color: ${changeOpacity('#339970', 0.08)}`); expect(button).toHaveStyle(`color: ${'#339970'}`); }); test('should have correct styles when provided hex color', () => { const props = { ...baseProps, action: {...baseProps.action, style: '#28a745'}, }; renderWithContext(<ActionButton {...props}/>); const button = screen.getByRole('button'); expect(button).toHaveStyle(`background-color: ${changeOpacity(props.action.style, 0.08)}`); expect(button).toHaveStyle(`color: ${props.action.style}`); }); test('should have no styles when provided invalid hex color', () => { const props = { ...baseProps, action: {...baseProps.action, style: '#wrong'}, }; renderWithContext(<ActionButton {...props}/>); const button = screen.getByRole('button'); expect(button.style.length).toBe(0); }); test('should have no styles when provided undefined', () => { const props = { ...baseProps, action: {...baseProps.action, style: undefined}, }; renderWithContext(<ActionButton {...props}/>); const button = screen.getByRole('button'); expect(button.style.length).toBe(0); }); });
2,817
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments/action_menu/action_menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import ActionMenu from './action_menu'; describe('components/post_view/message_attachments/ActionMenu', () => { const baseProps = { postId: 'post1', action: { name: 'action', options: [ { text: 'One', value: '1', }, { text: 'Two', value: '2', }, ], id: 'id', cookie: 'cookie', }, selected: undefined, autocompleteChannels: jest.fn(), autocompleteUsers: jest.fn(), selectAttachmentMenuAction: jest.fn(), }; test('should start with nothing selected', async () => { renderWithContext(<ActionMenu {...baseProps}/>); const autoCompleteSelector = screen.getByTestId('autoCompleteSelector'); const input = screen.getByPlaceholderText('action'); expect(autoCompleteSelector).toBeInTheDocument(); expect(autoCompleteSelector).toHaveClass('form-group'); //if nothing is selected or selected is undefined, baseProps.selectAttachmentMenuAction should not be called expect(baseProps.selectAttachmentMenuAction).not.toHaveBeenCalled(); expect(input).toHaveClass('form-control'); expect(input).toHaveAttribute('value', ''); }); test('should set selected based on default option', () => { const props = { ...baseProps, action: { ...baseProps.action, default_option: '2', }, }; renderWithContext(<ActionMenu {...props}/>); const input = screen.getByPlaceholderText('action'); //default_option is given in props expect(input).toHaveAttribute('value', 'Two'); }); });
2,821
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments/message_attachment/message_attachment.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {PostAction} from '@mattermost/types/integration_actions'; import type {MessageAttachment as MessageAttachmentType} from '@mattermost/types/message_attachments'; import type {PostImage} from '@mattermost/types/posts'; import ExternalImage from 'components/external_image'; import MessageAttachment from 'components/post_view/message_attachments/message_attachment/message_attachment'; import {Constants} from 'utils/constants'; describe('components/post_view/MessageAttachment', () => { const attachment = { pretext: 'pretext', author_name: 'author_name', author_icon: 'author_icon', author_link: 'author_link', title: 'title', title_link: 'title_link', text: 'short text', image_url: 'image_url', thumb_url: 'thumb_url', color: '#FFF', footer: 'footer', footer_icon: 'footer_icon', } as MessageAttachmentType; const baseProps = { postId: 'post_id', attachment, currentRelativeTeamUrl: 'dummy_team', actions: { doPostActionWithCookie: jest.fn(), openModal: jest.fn(), }, imagesMetadata: { image_url: { height: 200, width: 200, } as PostImage, thumb_url: { height: 200, width: 200, } as PostImage, } as Record<string, PostImage>, }; test('should match snapshot', () => { const wrapper = shallow(<MessageAttachment {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should change checkOverflow state on handleHeightReceived change', () => { const wrapper = shallow<MessageAttachment>(<MessageAttachment {...baseProps}/>); const instance = wrapper.instance(); wrapper.setState({checkOverflow: 0}); instance.handleHeightReceived(1); expect(wrapper.state('checkOverflow')).toEqual(1); instance.handleHeightReceived(0); expect(wrapper.state('checkOverflow')).toEqual(1); }); test('should match value on renderPostActions', () => { let wrapper = shallow<MessageAttachment>(<MessageAttachment {...baseProps}/>); expect(wrapper.instance().renderPostActions()).toMatchSnapshot(); const newAttachment = { ...attachment, actions: [ {id: 'action_id_1', name: 'action_name_1'}, {id: 'action_id_2', name: 'action_name_2'}, {id: 'action_id_3', name: 'action_name_3', type: 'select', data_source: 'users'}, ], }; const props = {...baseProps, attachment: newAttachment}; wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper.instance().renderPostActions()).toMatchSnapshot(); }); test('should call actions.doPostActionWithCookie on handleAction', () => { const promise = Promise.resolve({data: 123}); const doPostActionWithCookie = jest.fn(() => promise); const openModal = jest.fn(); const actionId = 'action_id_1'; const newAttachment = { ...attachment, actions: [{id: actionId, name: 'action_name_1', cookie: 'cookie-contents'}] as PostAction[], }; const props = {...baseProps, actions: {doPostActionWithCookie, openModal}, attachment: newAttachment}; const wrapper = shallow<MessageAttachment>(<MessageAttachment {...props}/>); expect(wrapper).toMatchSnapshot(); wrapper.instance().handleAction({ preventDefault: () => {}, // eslint-disable-line no-empty-function currentTarget: {getAttribute: () => { return 'attr_some_value'; }} as any, } as React.MouseEvent, []); expect(doPostActionWithCookie).toHaveBeenCalledTimes(1); expect(doPostActionWithCookie).toBeCalledWith(props.postId, 'attr_some_value', 'attr_some_value'); }); test('should call openModal when showModal is called', () => { const props = {...baseProps, src: 'https://example.com/image.png'}; const wrapper = shallow<MessageAttachment>( <MessageAttachment {...props}/>, ); wrapper.instance().showModal({preventDefault: () => {}}, 'https://example.com/image.png'); expect(props.actions.openModal).toHaveBeenCalledTimes(1); }); test('should match value on getFieldsTable', () => { let wrapper = shallow<MessageAttachment>(<MessageAttachment {...baseProps}/>); expect(wrapper.instance().getFieldsTable()).toMatchSnapshot(); const newAttachment = { ...attachment, fields: [ {title: 'title_1', value: 'value_1', short: false}, {title: 'title_2', value: 'value_2', short: false}, ], }; const props = {...baseProps, attachment: newAttachment}; wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper.instance().getFieldsTable()).toMatchSnapshot(); }); test('should use ExternalImage for images', () => { const props = { ...baseProps, attachment: { author_icon: 'http://example.com/author.png', image_url: 'http://example.com/image.png', thumb_url: 'http://example.com/thumb.png', // footer_icon is only rendered if footer is provided footer: attachment.footer, footer_icon: 'http://example.com/footer.png', } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper.find(ExternalImage)).toHaveLength(4); expect(wrapper.find(ExternalImage).find({src: props.attachment.author_icon}).exists()).toBe(true); expect(wrapper.find(ExternalImage).find({src: props.attachment.image_url}).exists()).toBe(true); expect(wrapper.find(ExternalImage).find({src: props.attachment.footer_icon}).exists()).toBe(true); expect(wrapper.find(ExternalImage).find({src: props.attachment.thumb_url}).exists()).toBe(true); }); test('should match snapshot when the attachment has an emoji in the title', () => { const props = { ...baseProps, attachment: { title: 'Do you like :pizza:?', } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the attachment hasn\'t any emojis in the title', () => { const props = { ...baseProps, attachment: { title: 'Don\'t you like emojis?', } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the attachment has a link in the title', () => { const props = { ...baseProps, attachment: { title: 'Do you like https://mattermost.com?', } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when no footer is provided (even if footer_icon is provided)', () => { const props = { ...baseProps, attachment: { ...attachment, footer: '', } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the footer is truncated', () => { const props = { ...baseProps, attachment: { title: 'footer', footer: 'a'.repeat(Constants.MAX_ATTACHMENT_FOOTER_LENGTH + 1), } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot and render a field with a number value', () => { const props = { ...baseProps, attachment: { ...attachment, fields: [ { title: 'this is the title', value: 1234, }, ], } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper.find('.attachment-field')).toMatchSnapshot(); }); test('should not render content box if there is no content', () => { const props = { ...baseProps, attachment: { pretext: 'This is a pretext.', } as MessageAttachmentType, }; const wrapper = shallow(<MessageAttachment {...props}/>); expect(wrapper.find('.attachment')).toMatchSnapshot(); }); });
2,823
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments/message_attachment
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/message_attachments/message_attachment/__snapshots__/message_attachment.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/MessageAttachment should call actions.doPostActionWithCookie on handleAction 1`] = ` <div className="attachment attachment--pretext" onClick={[Function]} > <div className="attachment__thumb-pretext" > <Connect(Markdown) message="pretext" postId="post_id" /> </div> <div className="attachment__content" > <div className="clearfix attachment__container" style={ Object { "borderLeftColor": "#FFF", } } > <ExternalLink href="author_link" key="attachment__author-name" location="message_attachment" > <Connect(Component) key="attachment__author-icon" src="author_icon" > <Component /> </Connect(Component)> <span className="attachment__author-name" key="attachment__author-name" > author_name </span> </ExternalLink> <h1 className="attachment__title" > <ExternalLink className="attachment__title-link" href="title_link" location="message_attachment" > title </ExternalLink> </h1> <div> <div className="attachment__body" > <Connect(ShowMore) checkOverflow={0} isAttachmentText={true} maxHeight={200} text="short text" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="short text" postId="post_id" /> </Connect(ShowMore)> <div className="attachment__image-container" > <Connect(Component) imageMetadata={ Object { "height": 200, "width": 200, } } src="image_url" > <Component /> </Connect(Component)> </div> <div className="attachment__footer-container" > <Connect(Component) src="footer_icon" > <Component /> </Connect(Component)> <span> footer </span> </div> <div className="attachment-actions" > <Connect(ActionButton) action={ Object { "cookie": "cookie-contents", "id": "action_id_1", "name": "action_name_1", } } actionExecuting={false} handleAction={[Function]} key="action_id_1" /> </div> </div> <div className="attachment__thumb-container" > <Connect(Component) imageMetadata={ Object { "height": 200, "width": 200, } } src="thumb_url" > <Component /> </Connect(Component)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match snapshot 1`] = ` <div className="attachment attachment--pretext" onClick={[Function]} > <div className="attachment__thumb-pretext" > <Connect(Markdown) message="pretext" postId="post_id" /> </div> <div className="attachment__content" > <div className="clearfix attachment__container" style={ Object { "borderLeftColor": "#FFF", } } > <ExternalLink href="author_link" key="attachment__author-name" location="message_attachment" > <Connect(Component) key="attachment__author-icon" src="author_icon" > <Component /> </Connect(Component)> <span className="attachment__author-name" key="attachment__author-name" > author_name </span> </ExternalLink> <h1 className="attachment__title" > <ExternalLink className="attachment__title-link" href="title_link" location="message_attachment" > title </ExternalLink> </h1> <div> <div className="attachment__body" > <Connect(ShowMore) checkOverflow={0} isAttachmentText={true} maxHeight={200} text="short text" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="short text" postId="post_id" /> </Connect(ShowMore)> <div className="attachment__image-container" > <Connect(Component) imageMetadata={ Object { "height": 200, "width": 200, } } src="image_url" > <Component /> </Connect(Component)> </div> <div className="attachment__footer-container" > <Connect(Component) src="footer_icon" > <Component /> </Connect(Component)> <span> footer </span> </div> </div> <div className="attachment__thumb-container" > <Connect(Component) imageMetadata={ Object { "height": 200, "width": 200, } } src="thumb_url" > <Component /> </Connect(Component)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match snapshot and render a field with a number value 1`] = ` <td className="attachment-field" key="attachment__field-0__1" > <Connect(Markdown) message="1234" postId="post_id" /> </td> `; exports[`components/post_view/MessageAttachment should match snapshot when no footer is provided (even if footer_icon is provided) 1`] = ` <div className="attachment attachment--pretext" onClick={[Function]} > <div className="attachment__thumb-pretext" > <Connect(Markdown) message="pretext" postId="post_id" /> </div> <div className="attachment__content" > <div className="clearfix attachment__container" style={ Object { "borderLeftColor": "#FFF", } } > <ExternalLink href="author_link" key="attachment__author-name" location="message_attachment" > <Connect(Component) key="attachment__author-icon" src="author_icon" > <Component /> </Connect(Component)> <span className="attachment__author-name" key="attachment__author-name" > author_name </span> </ExternalLink> <h1 className="attachment__title" > <ExternalLink className="attachment__title-link" href="title_link" location="message_attachment" > title </ExternalLink> </h1> <div> <div className="attachment__body" > <Connect(ShowMore) checkOverflow={0} isAttachmentText={true} maxHeight={200} text="short text" > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="short text" postId="post_id" /> </Connect(ShowMore)> <div className="attachment__image-container" > <Connect(Component) imageMetadata={ Object { "height": 200, "width": 200, } } src="image_url" > <Component /> </Connect(Component)> </div> </div> <div className="attachment__thumb-container" > <Connect(Component) imageMetadata={ Object { "height": 200, "width": 200, } } src="thumb_url" > <Component /> </Connect(Component)> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match snapshot when the attachment has a link in the title 1`] = ` <div className="attachment " onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--undefined" > <h1 className="attachment__title" > <Connect(Markdown) message="Do you like https://mattermost.com?" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" /> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match snapshot when the attachment has an emoji in the title 1`] = ` <div className="attachment " onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--undefined" > <h1 className="attachment__title" > <Connect(Markdown) message="Do you like :pizza:?" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" /> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match snapshot when the attachment hasn't any emojis in the title 1`] = ` <div className="attachment " onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--undefined" > <h1 className="attachment__title" > <Connect(Markdown) message="Don't you like emojis?" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" /> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match snapshot when the footer is truncated 1`] = ` <div className="attachment " onClick={[Function]} > <div className="attachment__content" > <div className="clearfix attachment__container attachment__container--undefined" > <h1 className="attachment__title" > <Connect(Markdown) message="footer" options={ Object { "autolinkedUrlSchemes": Array [], "mentionHighlight": false, "renderer": LinkOnlyRenderer { "options": Object {}, }, } } postId="post_id" /> </h1> <div> <div className="attachment__body attachment__body--no_thumb" > <div className="attachment__footer-container" > <span> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa… </span> </div> </div> <div style={ Object { "clear": "both", } } /> </div> </div> </div> </div> `; exports[`components/post_view/MessageAttachment should match value on getFieldsTable 1`] = `""`; exports[`components/post_view/MessageAttachment should match value on getFieldsTable 2`] = ` <div> <table className="attachment-fields" > <thead> <tr /> </thead> <tbody> <tr /> </tbody> </table> <table className="attachment-fields" > <thead> <tr> <th className="attachment-field__caption" > <Memo(Connect(Markdown)) message="title_1" options={ Object { "markdown": false, "mentionHighlight": false, } } postId="post_id" /> </th> </tr> </thead> <tbody> <tr> <td className="attachment-field" > <Memo(Connect(Markdown)) message="value_1" postId="post_id" /> </td> </tr> </tbody> </table> <table className="attachment-fields" > <thead> <tr> <th className="attachment-field__caption" > <Memo(Connect(Markdown)) message="title_2" options={ Object { "markdown": false, "mentionHighlight": false, } } postId="post_id" /> </th> </tr> </thead> <tbody> <tr> <td className="attachment-field" > <Memo(Connect(Markdown)) message="value_2" postId="post_id" /> </td> </tr> </tbody> </table> </div> `; exports[`components/post_view/MessageAttachment should match value on renderPostActions 1`] = `""`; exports[`components/post_view/MessageAttachment should match value on renderPostActions 2`] = ` <div className="attachment-actions" > <Memo(Connect(ActionButton)) action={ Object { "id": "action_id_1", "name": "action_name_1", } } actionExecuting={false} handleAction={[Function]} /> <Memo(Connect(ActionButton)) action={ Object { "id": "action_id_2", "name": "action_name_2", } } actionExecuting={false} handleAction={[Function]} /> <Memo(Connect(ActionMenu)) action={ Object { "data_source": "users", "id": "action_id_3", "name": "action_name_3", "type": "select", } } postId="post_id" /> </div> `; exports[`components/post_view/MessageAttachment should not render content box if there is no content 1`] = ` <div className="attachment attachment--pretext" onClick={[Function]} > <div className="attachment__thumb-pretext" > <Connect(Markdown) message="This is a pretext." postId="post_id" /> </div> </div> `;
2,824
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/new_message_separator/new_message_separator.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import NewMessageSeparator from './new_message_separator'; describe('components/post_view/new_message_separator', () => { test('should render new_message_separator', () => { renderWithContext( <NewMessageSeparator separatorId='1234' newMessagesSeparatorActions={[]} lastViewedAt={0} />, ); const newMessage = screen.getByText('New Messages'); const separator = screen.getByTestId('NotificationSeparator'); expect(newMessage).toBeInTheDocument(); expect(newMessage).toHaveClass('separator__text'); expect(separator).toBeInTheDocument(); expect(separator).toHaveClass('Separator NotificationSeparator'); }); });
2,827
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_add_channel_member/post_add_channel_member.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Post} from '@mattermost/types/posts'; import type {UserProfile} from '@mattermost/types/users'; import {sendAddToChannelEphemeralPost} from 'actions/global_actions'; import PostAddChannelMember from 'components/post_view/post_add_channel_member/post_add_channel_member'; import type {Props} from 'components/post_view/post_add_channel_member/post_add_channel_member'; import {TestHelper} from 'utils/test_helper'; jest.mock('actions/global_actions', () => { return { sendAddToChannelEphemeralPost: jest.fn(), }; }); describe('components/post_view/PostAddChannelMember', () => { const post: Post = TestHelper.getPostMock({ id: 'post_id_1', root_id: 'root_id', channel_id: 'channel_id', create_at: 1, }); const currentUser: UserProfile = TestHelper.getUserMock({ id: 'current_user_id', username: 'current_username', }); const requiredProps: Props = { currentUser, channelType: 'O', postId: 'post_id_1', post, userIds: ['user_id_1'], usernames: ['username_1'], actions: { removePost: jest.fn(), addChannelMember: jest.fn(), }, noGroupsUsernames: [], }; test('should match snapshot, empty postId', () => { const props: Props = { ...requiredProps, postId: '', }; const wrapper = shallow(<PostAddChannelMember {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, empty channelType', () => { const props: Props = { ...requiredProps, channelType: '', }; const wrapper = shallow(<PostAddChannelMember {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, public channel', () => { const wrapper = shallow(<PostAddChannelMember {...requiredProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, private channel', () => { const props: Props = { ...requiredProps, channelType: 'P', }; const wrapper = shallow(<PostAddChannelMember {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, more than 3 users', () => { const userIds = ['user_id_1', 'user_id_2', 'user_id_3', 'user_id_4']; const usernames = ['username_1', 'username_2', 'username_3', 'username_4']; const props: Props = { ...requiredProps, userIds, usernames, }; const wrapper = shallow(<PostAddChannelMember {...props}/>); expect(wrapper.state('expanded')).toEqual(false); expect(wrapper).toMatchSnapshot(); wrapper.find('.PostBody_otherUsersLink').simulate('click'); expect(wrapper.state('expanded')).toEqual(true); expect(wrapper).toMatchSnapshot(); }); test('actions should have been called', () => { const actions = { removePost: jest.fn(), addChannelMember: jest.fn(), }; const props: Props = {...requiredProps, actions}; const wrapper = shallow( <PostAddChannelMember {...props}/>, ); wrapper.find('.PostBody_addChannelMemberLink').simulate('click'); expect(actions.addChannelMember).toHaveBeenCalledTimes(1); expect(actions.addChannelMember).toHaveBeenCalledWith(post.channel_id, requiredProps.userIds[0], post.root_id); expect(sendAddToChannelEphemeralPost).toHaveBeenCalledTimes(1); expect(sendAddToChannelEphemeralPost).toHaveBeenCalledWith(props.currentUser, props.usernames[0], props.userIds[0], post.channel_id, post.root_id, 2); expect(actions.removePost).toHaveBeenCalledTimes(1); expect(actions.removePost).toHaveBeenCalledWith(post); }); test('addChannelMember should have been called multiple times', () => { const userIds = ['user_id_1', 'user_id_2', 'user_id_3', 'user_id_4']; const usernames = ['username_1', 'username_2', 'username_3', 'username_4']; const actions = { removePost: jest.fn(), addChannelMember: jest.fn(), }; const props: Props = {...requiredProps, userIds, usernames, actions}; const wrapper = shallow( <PostAddChannelMember {...props}/>, ); wrapper.find('.PostBody_addChannelMemberLink').simulate('click'); expect(actions.addChannelMember).toHaveBeenCalledTimes(4); }); test('should match snapshot, with no-groups usernames', () => { const props: Props = { ...requiredProps, noGroupsUsernames: ['user_id_2'], }; const wrapper = shallow(<PostAddChannelMember {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
2,829
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_add_channel_member
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_add_channel_member/__snapshots__/post_add_channel_member.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/PostAddChannelMember should match snapshot, empty channelType 1`] = `""`; exports[`components/post_view/PostAddChannelMember should match snapshot, empty postId 1`] = `""`; exports[`components/post_view/PostAddChannelMember should match snapshot, more than 3 users 1`] = ` <Fragment> <p> <span> <Connect(Component) channelId="channel_id" key="username_1" mentionName="username_1" /> <span key="1" > , </span> <a className="PostBody_otherUsersLink" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="{numOthers} others" id="post_body.check_for_out_of_channel_mentions.others" values={ Object { "numOthers": 2, } } /> </a> <MemoizedFormattedMessage defaultMessage=" and " id="post_body.check_for_out_of_channel_mentions.link.and" key="1" /> <Connect(Component) channelId="channel_id" key="username_4" mentionName="username_4" /> </span> <MemoizedFormattedMessage defaultMessage="did not get notified by this mention because they are not in the channel. Would you like to " id="post_body.check_for_out_of_channel_mentions.message.multiple" /> <a className="PostBody_addChannelMemberLink" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="add them to the channel" id="post_body.check_for_out_of_channel_mentions.link.public" /> </a> <MemoizedFormattedMessage defaultMessage="? They will have access to all message history." id="post_body.check_for_out_of_channel_mentions.message_last" /> </p> </Fragment> `; exports[`components/post_view/PostAddChannelMember should match snapshot, more than 3 users 2`] = ` <Fragment> <p> <span> <Connect(Component) channelId="channel_id" key="username_1" mentionName="username_1" /> <span key="1" > , </span> <Connect(Component) channelId="channel_id" key="username_2" mentionName="username_2" /> <span key="2" > , </span> <Connect(Component) channelId="channel_id" key="username_3" mentionName="username_3" /> <MemoizedFormattedMessage defaultMessage=" and " id="post_body.check_for_out_of_channel_mentions.link.and" key="3" /> <Connect(Component) channelId="channel_id" key="username_4" mentionName="username_4" /> </span> <MemoizedFormattedMessage defaultMessage="did not get notified by this mention because they are not in the channel. Would you like to " id="post_body.check_for_out_of_channel_mentions.message.multiple" /> <a className="PostBody_addChannelMemberLink" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="add them to the channel" id="post_body.check_for_out_of_channel_mentions.link.public" /> </a> <MemoizedFormattedMessage defaultMessage="? They will have access to all message history." id="post_body.check_for_out_of_channel_mentions.message_last" /> </p> </Fragment> `; exports[`components/post_view/PostAddChannelMember should match snapshot, private channel 1`] = ` <Fragment> <p> <Connect(Component) channelId="channel_id" mentionName="username_1" /> <MemoizedFormattedMessage defaultMessage="did not get notified by this mention because they are not in the channel. Would you like to " id="post_body.check_for_out_of_channel_mentions.message.one" /> <a className="PostBody_addChannelMemberLink" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="add them to this private channel" id="post_body.check_for_out_of_channel_mentions.link.private" /> </a> <MemoizedFormattedMessage defaultMessage="? They will have access to all message history." id="post_body.check_for_out_of_channel_mentions.message_last" /> </p> </Fragment> `; exports[`components/post_view/PostAddChannelMember should match snapshot, public channel 1`] = ` <Fragment> <p> <Connect(Component) channelId="channel_id" mentionName="username_1" /> <MemoizedFormattedMessage defaultMessage="did not get notified by this mention because they are not in the channel. Would you like to " id="post_body.check_for_out_of_channel_mentions.message.one" /> <a className="PostBody_addChannelMemberLink" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="add them to the channel" id="post_body.check_for_out_of_channel_mentions.link.public" /> </a> <MemoizedFormattedMessage defaultMessage="? They will have access to all message history." id="post_body.check_for_out_of_channel_mentions.message_last" /> </p> </Fragment> `; exports[`components/post_view/PostAddChannelMember should match snapshot, with no-groups usernames 1`] = ` <Fragment> <p> <Connect(Component) channelId="channel_id" mentionName="username_1" /> <MemoizedFormattedMessage defaultMessage="did not get notified by this mention because they are not in the channel. Would you like to " id="post_body.check_for_out_of_channel_mentions.message.one" /> <a className="PostBody_addChannelMemberLink" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="add them to the channel" id="post_body.check_for_out_of_channel_mentions.link.public" /> </a> <MemoizedFormattedMessage defaultMessage="? They will have access to all message history." id="post_body.check_for_out_of_channel_mentions.message_last" /> </p> <p> <Connect(Component) channelId="channel_id" mentionName="user_id_2" /> <MemoizedFormattedMessage defaultMessage="did not get notified by this mention because they are not in the channel. They cannot be added to the channel because they are not a member of the linked groups. To add them to this channel, they must be added to the linked groups." id="post_body.check_for_out_of_channel_groups_mentions.message" /> </p> </Fragment> `;
2,830
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_attachment_container/post_attachment_container.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {GlobalState} from '@mattermost/types/store'; import type {DeepPartial} from '@mattermost/types/utilities'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import PostAttachmentContainer from './post_attachment_container'; import type {Props} from './post_attachment_container'; describe('PostAttachmentContainer', () => { const baseProps: Props = { children: <p>{'some children'}</p>, className: 'permalink', link: '/test/pl/1', }; const initialState: DeepPartial<GlobalState> = { entities: { general: {config: {}}, users: { currentUserId: 'user1', profiles: {}, }, teams: { currentTeamId: 'current_team_id', teams: {}, }, posts: {posts: {}}, preferences: {myPreferences: {}}, }, }; test('should render correctly', () => { renderWithContext( <PostAttachmentContainer {...baseProps}/>, initialState, ); const button = screen.getByRole('button'); expect(button).toBeInTheDocument(); expect(button).toHaveClass('attachment attachment--permalink'); expect(button.children[0]).toHaveClass('attachment__content attachment__content--permalink'); expect(screen.getByText('some children')).toBeInTheDocument(); }); });
2,832
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_attachment_opengraph/get_nearest_point.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {getNearestPoint} from './get_nearest_point'; describe('getNearestPoint', () => { test('should return nearest point', () => { for (const data of [ { points: [ {width: 30, height: 40}, {width: 50, height: 50}, {width: 100, height: 2}, {width: 500, height: 200}, {width: 110, height: 20}, {width: 10, height: 20}, ], pivotPoint: {width: 10, height: 20}, nearestPoint: {width: 10, height: 20}, nearestPointLte: {width: 10, height: 20}, }, { points: [ {width: 50, height: 50}, {width: 100, height: 2}, {width: 500, height: 200}, {width: 110, height: 20}, {width: 100, height: 90}, {width: 30, height: 40}, ], pivotPoint: {width: 10, height: 20}, nearestPoint: {width: 30, height: 40}, nearestPointLte: {}, }, { points: [ {width: 50, height: 50}, {width: 1, height: 1}, {width: 15, height: 25}, {width: 100, height: 2}, {width: 500, height: 200}, {width: 110, height: 20}, ], pivotPoint: {width: 10, height: 20}, nearestPoint: {width: 15, height: 25}, nearestPointLte: {width: 1, height: 1}, }, ]) { const nearestPoint = getNearestPoint(data.pivotPoint, data.points); expect(nearestPoint.width).toEqual(data.nearestPoint.width); expect(nearestPoint.height).toEqual(data.nearestPoint.height); } }); });
2,836
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_attachment_opengraph/post_attachment_opengraph.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import {cloneDeep, set} from 'lodash'; import React from 'react'; import {Provider} from 'react-redux'; import type {OpenGraphMetadata, Post} from '@mattermost/types/posts'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import mockStore from 'tests/test_store'; import {Preferences} from 'utils/constants'; import {getBestImage, getIsLargeImage, PostAttachmentOpenGraphImage, PostAttachmentOpenGraphBody} from './post_attachment_opengraph'; import PostAttachmentOpenGraph from './index'; const preferenceKeys = { COLLAPSE_DISPLAY: getPreferenceKey(Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.COLLAPSE_DISPLAY), LINK_PREVIEW_DISPLAY: getPreferenceKey(Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.LINK_PREVIEW_DISPLAY), }; const openGraphData = { audios: null, description: 'Mattermost is a secure, open source platform for communication, collaboration, and workflow orchestration across tools and teams.', determiner: '', images: [{ height: 1256, secure_url: 'http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png', type: 'image/png', url: '', width: 2400}], locale: '', locales_alternate: null, site_name: 'Mattermost.com', title: 'Mattermost | Open Source Collaboration for Developers', type: 'website', url: 'https://www.mattermost.com', videos: null, }; const initialState = { entities: { general: { config: { EnableLinkPreviews: 'true', EnableSVGs: 'true', HasImageProxy: 'true', }, }, preferences: { myPreferences: { [preferenceKeys.COLLAPSE_DISPLAY]: {value: Preferences.COLLAPSE_DISPLAY_DEFAULT}, [preferenceKeys.LINK_PREVIEW_DISPLAY]: {value: Preferences.LINK_PREVIEW_DISPLAY_DEFAULT}, }, }, teams: { currentTeamId: 'team-id', }, users: { currentUserId: 'user-1', }, posts: { openGraph: { post_id_1: openGraphData, }, }, }, }; describe('PostAttachmentOpenGraph', () => { const imageUrl = 'http://mattermost.com/OpenGraphImage.jpg'; const toggleEmbedVisibility = jest.fn(); const post = { id: 'post_id_1', root_id: 'root_id', channel_id: 'channel_id', create_at: 1, message: 'https://mattermost.com', metadata: { images: { [imageUrl]: { format: 'png', frameCount: 0, height: 100, width: 100, }, }, }, } as unknown as Post; const baseProps = { post, postId: '', link: 'http://mattermost.com', currentUserId: '1234', openGraphData: { description: 'description', images: [{ secure_url: '', url: imageUrl, }], site_name: 'Mattermost', title: 'Mattermost Private Cloud Messaging', }, toggleEmbedVisibility, actions: { editPost: jest.fn(), }, }; test('should match snapshot', () => { const store = mockStore(initialState); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraph {...baseProps}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should render nothing without any data', () => { const state = cloneDeep(initialState); set(state, 'entities.posts.openGraph', {}); const store = mockStore(state); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraph {...baseProps}/> </Provider>, ); expect(wrapper).toEqual({}); }); test('should render nothing when link previews are disabled on the server', () => { const state = cloneDeep(initialState); set(state, 'entities.config.EnableLinkPreviews', 'false'); const store = mockStore(state); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraph {...baseProps}/> </Provider>, ); expect(wrapper).toEqual({}); }); test('should render nothing when link previews are disabled by the user', () => { const state = cloneDeep(initialState); set(state, `entities.preferences.EnableLinkPreviews["${preferenceKeys.LINK_PREVIEW_DISPLAY}"]`, 'false'); const store = mockStore(state); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraph {...baseProps}/> </Provider>, ); expect(wrapper).toEqual({}); }); }); describe('PostAttachmentOpenGraphBody', () => { const baseProps = { title: 'test-title', sitename: 'test-sitename', description: 'test-description', isInPermalink: false, }; test('should match snapshot', () => { const wrapper = mount(<PostAttachmentOpenGraphBody {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should not render without title', () => { const props = cloneDeep(baseProps); set(props, 'title', ''); const wrapper = mount(<PostAttachmentOpenGraphBody {...props}/>); expect(wrapper).toEqual({}); }); test('should add extra class for permalink view', () => { const props = cloneDeep(baseProps); set(props, 'isInPermalink', true); const wrapper = mount(<PostAttachmentOpenGraphBody {...props}/>); expect(wrapper.find('.isInPermalink').exists()).toBe(true); expect(wrapper.find('.sitename').exists()).toBe(false); }); test('should render without sitename', () => { const props = cloneDeep(baseProps); set(props, 'sitename', ''); const wrapper = mount(<PostAttachmentOpenGraphBody {...props}/>); expect(wrapper.find('.sitename').exists()).toBe(false); expect(wrapper.find('.title').exists()).toBe(true); expect(wrapper.find('.description').exists()).toBe(true); }); test('should render without description', () => { const props = cloneDeep(baseProps); set(props, 'description', ''); const wrapper = mount(<PostAttachmentOpenGraphBody {...props}/>); expect(wrapper.find('.sitename').exists()).toBe(true); expect(wrapper.find('.title').exists()).toBe(true); expect(wrapper.find('.description').exists()).toBe(false); }); test('should render with title only', () => { const props = cloneDeep(baseProps); set(props, 'sitename', ''); set(props, 'description', ''); const wrapper = mount(<PostAttachmentOpenGraphBody {...props}/>); expect(wrapper.find('.sitename').exists()).toBe(false); expect(wrapper.find('.title').exists()).toBe(true); expect(wrapper.find('.description').exists()).toBe(false); }); }); describe('PostAttachmentOpenGraphImage', () => { const baseProps = { imageMetadata: getBestImage(openGraphData), isInPermalink: false, toggleEmbedVisibility: jest.fn(), isEmbedVisible: true, title: 'test_image', }; test('should match snapshot', () => { const store = mockStore(initialState); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraphImage {...baseProps}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should not render when used in Permalink', () => { const props = cloneDeep(baseProps); set(props, 'isInPermalink', true); const store = mockStore(initialState); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraphImage {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot({}); }); test('should render a large image with toggle', () => { const store = mockStore(initialState); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraphImage {...baseProps}/> </Provider>, ); expect(wrapper.find('.PostAttachmentOpenGraph__image').exists()).toBe(true); expect(wrapper.find('.PostAttachmentOpenGraph__image.large').exists()).toBe(true); expect(wrapper.find('.PostAttachmentOpenGraph__image .preview-toggle').exists()).toBe(true); }); test('should render a small image without toggle', () => { const props = cloneDeep(baseProps); set(props, 'imageMetadata.height', 90); set(props, 'imageMetadata.width', 120); const store = mockStore(initialState); const wrapper = mount( <Provider store={store}> <PostAttachmentOpenGraphImage {...props}/> </Provider>, ); expect(wrapper.find('.PostAttachmentOpenGraph__image').exists()).toBe(true); expect(wrapper.find('.PostAttachmentOpenGraph__image.large').exists()).toBe(false); expect(wrapper.find('.PostAttachmentOpenGraph__image .preview-toggle').exists()).toBe(false); }); }); describe('PostAttachmentOpenGraphBody', () => { const baseProps = { title: 'test_title', isInPermalink: false, siteName: 'test_sitename', description: 'test_description', }; test('should match snapshot', () => { const wrapper = mount( <PostAttachmentOpenGraphBody {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); describe('permalink preview', () => { const props = { ...baseProps, isInPermalink: true, }; const wrapper = mount( <PostAttachmentOpenGraphBody {...props}/>, ); expect(wrapper.find('.isInPermalink').exists()).toBe(true); }); }); describe('Helpers', () => { describe('getBestImage', () => { test('should return nothing with missing OpenGraph images', () => { const openGraphData = {} as OpenGraphMetadata; const imageData = getBestImage(openGraphData); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toBeFalsy(); }); test('should return nothing with no OpenGraph images', () => { const openGraphData = { images: [], }; const imageData = getBestImage(openGraphData); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toBeFalsy(); }); test('should return secure_url if specified', () => { const openGraphData = { images: [{ secure_url: 'https://example.com/image.png', url: 'http://example.com/image.png', }], }; const imageData = getBestImage(openGraphData); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toEqual(openGraphData.images[0].secure_url); }); test('should handle undefined metadata', () => { const openGraphData = { images: [{ secure_url: 'https://example.com/image.png', url: 'http://example.com/image.png', }], }; const imagesMetadata = {}; const imageData = getBestImage(openGraphData, imagesMetadata); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toEqual(openGraphData.images[0].secure_url); }); test('should return url if secure_url is not specified', () => { const openGraphData = { images: [{ secure_url: '', url: 'http://example.com/image.png', }], }; const imageData = getBestImage(openGraphData); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toEqual(openGraphData.images[0].url); }); test('should pick the first image if no dimensions are specified', () => { const openGraphData = { images: [{ url: 'http://example.com/image.png', }, { url: 'http://example.com/image2.png', }], }; const imageData = getBestImage(openGraphData); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toEqual(openGraphData.images[0].url); }); test('should prefer images with dimensions closer to 80 by 80', () => { const openGraphData = { images: [{ url: 'http://example.com/image.png', height: 100, width: 100, }, { url: 'http://example.com/image2.png', height: 1000, width: 1000, }], }; const imageData = getBestImage(openGraphData); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toEqual(openGraphData.images[0].url); }); test('should use dimensions from post metadata if necessary', () => { const openGraphData = { images: [{ url: 'http://example.com/image.png', }, { url: 'http://example.com/image2.png', }], }; const imagesMetadata = { 'http://example.com/image.png': { format: 'png', frameCount: 0, height: 100, width: 100, }, 'http://example.com/image2.png': { format: 'png', frameCount: 0, height: 1000, width: 1000, }, }; const imageData = getBestImage(openGraphData, imagesMetadata); const imageUrl = imageData?.secure_url || imageData?.url; expect(imageUrl).toEqual(openGraphData.images[0].url); }); }); describe('isLargeImage', () => { test('should be a large image', () => { expect(getIsLargeImage({ format: 'png', frameCount: 0, height: 180, width: 400, })).toBe(true); }); test('should not be a large image', () => { expect(getIsLargeImage({ format: 'png', frameCount: 0, height: 100, width: 100, })).toBe(false); }); }); });
2,838
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_attachment_opengraph
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_attachment_opengraph/__snapshots__/post_attachment_opengraph.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`PostAttachmentOpenGraph should match snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Connect(PostAttachmentOpenGraph) actions={ Object { "editPost": [MockFunction], } } currentUserId="1234" link="http://mattermost.com" openGraphData={ Object { "description": "description", "images": Array [ Object { "secure_url": "", "url": "http://mattermost.com/OpenGraphImage.jpg", }, ], "site_name": "Mattermost", "title": "Mattermost Private Cloud Messaging", } } post={ Object { "channel_id": "channel_id", "create_at": 1, "id": "post_id_1", "message": "https://mattermost.com", "metadata": Object { "images": Object { "http://mattermost.com/OpenGraphImage.jpg": Object { "format": "png", "frameCount": 0, "height": 100, "width": 100, }, }, }, "root_id": "root_id", } } postId="" toggleEmbedVisibility={[MockFunction]} > <PostAttachmentOpenGraph actions={ Object { "editPost": [Function], } } currentUserId="user-1" enableLinkPreviews={true} imageCollapsed={false} link="http://mattermost.com" post={ Object { "channel_id": "channel_id", "create_at": 1, "id": "post_id_1", "message": "https://mattermost.com", "metadata": Object { "images": Object { "http://mattermost.com/OpenGraphImage.jpg": Object { "format": "png", "frameCount": 0, "height": 100, "width": 100, }, }, }, "root_id": "root_id", } } postId="" previewEnabled={true} toggleEmbedVisibility={[MockFunction]} /> </Connect(PostAttachmentOpenGraph)> </Provider> `; exports[`PostAttachmentOpenGraphBody should match snapshot 1`] = ` <Memo() description="test-description" isInPermalink={false} sitename="test-sitename" title="test-title" > <div className="PostAttachmentOpenGraph__body" > <span className="sitename" > test-sitename </span> <span className="title" > test-title </span> <span className="description" > test-description </span> </div> </Memo()> `; exports[`PostAttachmentOpenGraphBody should match snapshot 2`] = ` <Memo() description="test_description" isInPermalink={false} siteName="test_sitename" title="test_title" > <div className="PostAttachmentOpenGraph__body" > <span className="title" > test_title </span> <span className="description" > test_description </span> </div> </Memo()> `; exports[`PostAttachmentOpenGraphImage should match snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo() imageMetadata={ Object { "format": "png", "frameCount": 0, "height": 1256, "secure_url": "http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png", "type": "image/png", "url": "", "width": 2400, } } isEmbedVisible={true} isInPermalink={false} title="test_image" toggleEmbedVisibility={[MockFunction]} > <div className="PostAttachmentOpenGraph__image large" > <AutoHeightSwitcher showSlot={1} slot1={ <Memo(Connect(Component)) imageMetadata={ Object { "format": "png", "frameCount": 0, "height": 1256, "secure_url": "http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png", "type": "image/png", "url": "", "width": 2400, } } src="http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png" > [Function] </Memo(Connect(Component))> } slot2={ <button className="preview-toggle style--none" onClick={[Function]} > <MenuDownIcon color="currentColor" size={18} /> </button> } > <Transition appear={false} enter={true} exit={true} in={false} mountOnEnter={false} onEnter={[Function]} onEntered={[Function]} onEntering={[Function]} onExit={[Function]} onExited={[Function]} onExiting={[Function]} timeout={250} unmountOnExit={false} > <div className="AutoHeight" style={ Object { "height": "auto", "overflow": "visible", "transitionDuration": "250ms", "transitionProperty": "height", "transitionTimingFunction": "ease", "width": "100%", } } > <div> <Connect(Component) imageMetadata={ Object { "format": "png", "frameCount": 0, "height": 1256, "secure_url": "http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png", "type": "image/png", "url": "", "width": 2400, } } src="http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png" > <Memo(ExternalImage) dispatch={[Function]} enableSVGs={true} hasImageProxy={true} imageMetadata={ Object { "format": "png", "frameCount": 0, "height": 1256, "secure_url": "http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png", "type": "image/png", "url": "", "width": 2400, } } src="http://localhost:8065/api/v4/image?url=http%3A%2F%2Fmattermo…t.com%2Fwp-content%2Fuploads%2F2021%2F09%2FHomepage%402x.png" > <button className="preview-toggle style--none" onClick={[Function]} > <MenuDownIcon color="currentColor" size={18} > <svg fill="currentColor" height={18} version="1.1" viewBox="0 0 24 24" width={18} xmlns="http://www.w3.org/2000/svg" > <path d="M7,10L12,15L17,10H7Z" /> </svg> </MenuDownIcon> </button> <figure> <img alt="test_image" src="/api/v4/image?url=http%3A%2F%2Flocalhost%3A8065%2Fapi%2Fv4%2Fimage%3Furl%3Dhttp%253A%252F%252Fmattermo%E2%80%A6t.com%252Fwp-content%252Fuploads%252F2021%252F09%252FHomepage%25402x.png" /> </figure> </Memo(ExternalImage)> </Connect(Component)> </div> </div> </Transition> </AutoHeightSwitcher> </div> </Memo()> </Provider> `; exports[`PostAttachmentOpenGraphImage should not render when used in Permalink 1`] = `Object {}`;
2,840
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_body_additional_content/post_body_additional_content.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type { Post, PostEmbed, PostImage, PostMetadata, } from '@mattermost/types/posts'; import {getEmbedFromMetadata} from 'mattermost-redux/utils/post_utils'; import MessageAttachmentList from 'components/post_view/message_attachments/message_attachment_list'; import PostAttachmentOpenGraph from 'components/post_view/post_attachment_opengraph'; import PostImageComponent from 'components/post_view/post_image'; import YoutubeVideo from 'components/youtube_video'; import PostBodyAdditionalContent from './post_body_additional_content'; import type {Props} from './post_body_additional_content'; jest.mock('mattermost-redux/utils/post_utils', () => { const actual = jest.requireActual('mattermost-redux/utils/post_utils'); return { ...actual, getEmbedFromMetadata: jest.fn(actual.getEmbedFromMetadata), }; }); describe('PostBodyAdditionalContent', () => { const baseProps: Props = { children: <span>{'some children'}</span>, post: { id: 'post_id_1', root_id: 'root_id', channel_id: 'channel_id', create_at: 1, message: '', metadata: {} as PostMetadata, } as Post, isEmbedVisible: true, handleFileDropdownOpened: jest.fn(), actions: { toggleEmbedVisibility: jest.fn(), }, appsEnabled: false, }; describe('with an image preview', () => { const imageUrl = 'https://example.com/image.png'; const imageMetadata = {} as PostImage; // This can be empty since we're checking equality with === const imageBaseProps = { ...baseProps, post: { ...baseProps.post, message: imageUrl, metadata: { embeds: [{ type: 'image', url: imageUrl, }], images: { [imageUrl]: imageMetadata, }, emojis: [], files: [], reactions: [], } as PostMetadata, }, }; test('should render correctly', () => { const wrapper = shallow(<PostBodyAdditionalContent {...imageBaseProps}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(PostImageComponent).exists()).toBe(true); expect(wrapper.find(PostImageComponent).prop('imageMetadata')).toBe(imageMetadata); }); test('should render the toggle after a message containing more than just a link', () => { const props = { ...imageBaseProps, post: { ...imageBaseProps.post, message: 'This is an image: ' + imageUrl, }, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should not render content when isEmbedVisible is false', () => { const props = { ...imageBaseProps, isEmbedVisible: false, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(PostImageComponent).exists()).toBe(false); }); }); describe('with a message attachment', () => { const attachments: any[] = []; // This can be empty since we're checking equality with === const messageAttachmentBaseProps = { ...baseProps, post: { ...baseProps.post, metadata: { embeds: [{ type: 'message_attachment', }], } as PostMetadata, props: { attachments, }, }, }; test('should render correctly', () => { const wrapper = shallow(<PostBodyAdditionalContent {...messageAttachmentBaseProps}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(MessageAttachmentList).exists()).toBe(true); expect(wrapper.find(MessageAttachmentList).prop('attachments')).toBe(attachments); }); test('should render content when isEmbedVisible is false', () => { const props = { ...messageAttachmentBaseProps, isEmbedVisible: false, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(MessageAttachmentList).exists()).toBe(true); }); }); describe('with an opengraph preview', () => { const ogUrl = 'https://example.com/image.png'; const ogBaseProps = { ...baseProps, post: { ...baseProps.post, message: ogUrl, metadata: { embeds: [{ type: 'opengraph', url: ogUrl, }], } as PostMetadata, }, }; test('should render correctly', () => { const wrapper = shallow(<PostBodyAdditionalContent {...ogBaseProps}/>); expect(wrapper.find(PostAttachmentOpenGraph).exists()).toBe(true); expect(wrapper).toMatchSnapshot(); }); test('should render the toggle after a message containing more than just a link', () => { const props = { ...ogBaseProps, post: { ...ogBaseProps.post, message: 'This is a link: ' + ogUrl, }, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should render content when isEmbedVisible is false', () => { const props = { ...ogBaseProps, isEmbedVisible: false, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(PostAttachmentOpenGraph).exists()).toBe(true); }); }); describe('with a YouTube video', () => { const youtubeUrl = 'https://www.youtube.com/watch?v=d-YO3v-wJts'; const youtubeBaseProps = { ...baseProps, post: { ...baseProps.post, message: youtubeUrl, metadata: { embeds: [{ type: 'opengraph', url: youtubeUrl, }], } as PostMetadata, }, }; test('should render correctly', () => { const wrapper = shallow(<PostBodyAdditionalContent {...youtubeBaseProps}/>); expect(wrapper.find(YoutubeVideo).exists()).toBe(true); expect(wrapper).toMatchSnapshot(); }); test('should render the toggle after a message containing more than just a link', () => { const props = { ...youtubeBaseProps, post: { ...youtubeBaseProps.post, message: 'This is a video: ' + youtubeUrl, }, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should not render content when isEmbedVisible is false', () => { const props = { ...youtubeBaseProps, isEmbedVisible: false, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(YoutubeVideo).exists()).toBe(false); expect(wrapper).toMatchSnapshot(); }); }); describe('with a normal link', () => { const mp3Url = 'https://example.com/song.mp3'; const EmbedMP3 = () => <></>; const linkBaseProps = { ...baseProps, post: { ...baseProps.post, message: mp3Url, metadata: { embeds: [{ type: 'link', url: mp3Url, }], } as PostMetadata, }, }; test("Should render nothing if the registered plugins don't match", () => { const props = { ...linkBaseProps, pluginPostWillRenderEmbedComponents: [ { id: '', pluginId: '', match: () => false, toggleable: true, component: EmbedMP3, }, ], }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(EmbedMP3).exists()).toBe(false); expect(wrapper).toMatchSnapshot(); }); test('Should render the plugin component if it matches and is toggeable', () => { const props = { ...linkBaseProps, pluginPostWillRenderEmbedComponents: [ { id: '', pluginId: '', match: ({url}: PostEmbed) => url === mp3Url, toggleable: true, component: EmbedMP3, }, ], }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(EmbedMP3).exists()).toBe(true); expect(wrapper.find('button.post__embed-visibility').exists()).toBe(true); expect(wrapper).toMatchSnapshot(); }); test('Should render the plugin component if it matches and is not toggeable', () => { const props = { ...linkBaseProps, pluginPostWillRenderEmbedComponents: [ { id: '', pluginId: '', match: ({url}: PostEmbed) => url === mp3Url, toggleable: false, component: EmbedMP3, }, ], }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(EmbedMP3).exists()).toBe(true); expect(wrapper.find('button.post__embed-visibility').exists()).toBe(false); expect(wrapper).toMatchSnapshot(); }); test('Should render nothing if the plugin matches but isEmbedVisible is false', () => { const props = { ...linkBaseProps, pluginPostWillRenderEmbedComponents: [ { id: '', pluginId: '', match: ({url}: PostEmbed) => url === mp3Url, toggleable: false, component: EmbedMP3, }, ], isEmbedVisible: false, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper.find(EmbedMP3).exists()).toBe(false); expect(wrapper).toMatchSnapshot(); }); }); test('should call toggleEmbedVisibility with post id', () => { const wrapper = shallow<PostBodyAdditionalContent>(<PostBodyAdditionalContent {...baseProps}/>); wrapper.instance().toggleEmbedVisibility(); expect(baseProps.actions.toggleEmbedVisibility).toHaveBeenCalledTimes(1); expect(baseProps.actions.toggleEmbedVisibility).toBeCalledWith('post_id_1'); }); test('should call getEmbedFromMetadata with metadata', () => { const metadata = { embeds: [{ type: 'message_attachment', }], } as PostMetadata; const props = { ...baseProps, post: { ...baseProps.post, metadata, }, }; const wrapper = shallow<PostBodyAdditionalContent>(<PostBodyAdditionalContent {...props}/>); wrapper.instance().getEmbed(); expect(getEmbedFromMetadata).toHaveBeenCalledWith(metadata); }); describe('with a permalinklink', () => { const permalinkUrl = 'https://community.mattermost.com/core/pl/123456789'; const permalinkBaseProps = { ...baseProps, post: { ...baseProps.post, message: permalinkUrl, metadata: { embeds: [{ type: 'permalink', url: '', data: { post_id: 'post_id123', channel_display_name: 'channel1', team_name: 'core', channel_type: 'O', channel_id: 'channel_id', }, }], images: {}, emojis: [], files: [], reactions: [], } as PostMetadata, }, }; test('Render permalink preview', () => { const wrapper = shallow(<PostBodyAdditionalContent {...permalinkBaseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('Render permalink preview with no data', () => { const metadata = { embeds: [{ type: 'permalink', url: '', }], } as PostMetadata; const props = { ...permalinkBaseProps, post: { ...permalinkBaseProps.post, metadata, }, }; const wrapper = shallow(<PostBodyAdditionalContent {...props}/>); expect(wrapper).toMatchSnapshot(); }); }); });