level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
3,172
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_channel_link
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_channel_link/__snapshots__/sidebar_channel_link.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_channel/sidebar_channel_link should match snapshot 1`] = ` <Link aria-label="channel_label" className="SidebarLink" id="sidebarItem_" onClick={[Function]} tabIndex={0} to="http://a.fake.link" > <SidebarChannelIcon icon={null} isDeleted={false} /> <div className="SidebarChannelLinkLabel_wrapper" > <span className="SidebarChannelLinkLabel" > channel_label </span> <Connect(Pluggable) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } pluggableName="SidebarChannelLinkLabel" /> </div> <Connect(Component) id="channel_id" /> <ChannelMentionBadge hasUrgent={false} unreadMentions={0} /> <div className="SidebarMenu MenuWrapper" > <Connect(Component) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLink="http://a.fake.link" isUnread={false} onMenuToggle={[Function]} /> </div> </Link> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_link should match snapshot for desktop 1`] = ` <Link aria-label="channel_label" className="SidebarLink" id="sidebarItem_" onClick={[Function]} tabIndex={0} to="http://a.fake.link" > <SidebarChannelIcon icon={null} isDeleted={false} /> <div className="SidebarChannelLinkLabel_wrapper" > <span className="SidebarChannelLinkLabel" > channel_label </span> <Connect(Pluggable) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } pluggableName="SidebarChannelLinkLabel" /> </div> <Connect(Component) id="channel_id" /> <ChannelMentionBadge hasUrgent={false} unreadMentions={0} /> <div className="SidebarMenu MenuWrapper" > <Connect(Component) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLink="http://a.fake.link" isUnread={false} onMenuToggle={[Function]} /> </div> </Link> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_link should match snapshot when tooltip is enabled 1`] = ` <Link aria-label="channel_label" className="SidebarLink" id="sidebarItem_" onClick={[Function]} tabIndex={0} to="http://a.fake.link" > <SidebarChannelIcon icon={null} isDeleted={false} /> <div className="SidebarChannelLinkLabel_wrapper" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} onEntering={[Function]} overlay={ <Tooltip id="channel-displayname__tooltip" > channel_label </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div className="truncated" > <span className="SidebarChannelLinkLabel" > channel_label </span> </div> </OverlayTrigger> <Connect(Pluggable) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } pluggableName="SidebarChannelLinkLabel" /> </div> <Connect(Component) id="channel_id" /> <ChannelMentionBadge hasUrgent={false} unreadMentions={0} /> <div className="SidebarMenu MenuWrapper" > <Connect(Component) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLink="http://a.fake.link" isUnread={false} onMenuToggle={[Function]} /> </div> </Link> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_link should match snapshot with aria label prefix and unread mentions 1`] = ` <Link aria-label="channel_label aria_label_prefix_ 2 mentions" className="SidebarLink unread-title" id="sidebarItem_" onClick={[Function]} tabIndex={0} to="http://a.fake.link" > <SidebarChannelIcon icon={null} isDeleted={false} /> <div className="SidebarChannelLinkLabel_wrapper" > <span className="SidebarChannelLinkLabel" > channel_label </span> <Connect(Pluggable) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } pluggableName="SidebarChannelLinkLabel" /> </div> <Connect(Component) id="channel_id" /> <ChannelMentionBadge hasUrgent={false} unreadMentions={2} /> <div className="SidebarMenu MenuWrapper" > <Connect(Component) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLink="http://a.fake.link" isUnread={true} onMenuToggle={[Function]} /> </div> </Link> `;
3,174
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_channel_menu/sidebar_channel_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 type {ChannelType} from '@mattermost/types/channels'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import Constants from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import SidebarChannelMenu from './sidebar_channel_menu'; jest.mock('react-intl', () => ({ ...jest.requireActual('react-intl'), useIntl: () => ({ formatMessage: (message: {id: string; defaultMessage: string}) => { return message.defaultMessage; }, }), })); describe('components/sidebar/sidebar_channel/sidebar_channel_menu', () => { const testChannel = TestHelper.getChannelMock(); const testCategory = TestHelper.getCategoryMock(); const baseProps = { channel: testChannel, channelLink: 'http://a.fake.link', categories: [testCategory], currentUserId: 'user_id', currentCategory: testCategory, currentTeamId: 'team_id', isUnread: false, isFavorite: false, isMuted: false, managePublicChannelMembers: true, managePrivateChannelMembers: true, closeHandler: jest.fn(), isMenuOpen: true, onToggleMenu: jest.fn(), multiSelectedChannelIds: [], displayedChannels: [], markChannelAsRead: jest.fn(), markMostRecentPostInChannelAsUnread: jest.fn(), favoriteChannel: jest.fn(), unfavoriteChannel: jest.fn(), muteChannel: jest.fn(), unmuteChannel: jest.fn(), openModal: jest.fn(), createCategory: jest.fn(), addChannelsInSidebar: jest.fn(), onMenuToggle: jest.fn(), }; test('should match snapshot and contain correct buttons', () => { const wrapper = shallow( <SidebarChannelMenu {...baseProps}/>, ); expect(wrapper.find('#favorite-channel_id')).toHaveLength(1); expect(wrapper.find('#mute-channel_id')).toHaveLength(1); expect(wrapper.find('#copyLink-channel_id')).toHaveLength(1); expect(wrapper.find('#addMembers-channel_id')).toHaveLength(1); expect(wrapper.find('#leave-channel_id')).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is unread', () => { const props = { ...baseProps, isUnread: true, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#markAsRead-channel_id')).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is read', () => { const props = { ...baseProps, isUnread: false, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#markAsUnread-channel_id')).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is favorite', () => { const props = { ...baseProps, isFavorite: true, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#favorite-channel_id')).toHaveLength(0); expect(wrapper.find('#unfavorite-channel_id')).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is muted', () => { const props = { ...baseProps, isMuted: true, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#mute-channel_id')).toHaveLength(0); expect(wrapper.find('#unmute-channel_id')).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is private', () => { const props = { ...baseProps, channel: { ...baseProps.channel, type: 'P' as ChannelType, }, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#copyLink-channel_id')).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is DM', () => { const props = { ...baseProps, channel: { ...baseProps.channel, type: 'D' as ChannelType, }, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#copyLink-channel_id')).toHaveLength(0); expect(wrapper.find('#addMembers-channel_id')).toHaveLength(0); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu items when channel is Town Square', () => { const props = { ...baseProps, channel: { ...baseProps.channel, name: Constants.DEFAULT_CHANNEL, }, }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper.find('#leave-channel_id')).toHaveLength(0); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot of rendered items when multiselecting channels - public channels and DM category', () => { const props = { ...baseProps, categories: [ ...baseProps.categories, TestHelper.getCategoryMock({ id: 'dm_category_id', display_name: 'direct_messages', type: CategoryTypes.DIRECT_MESSAGES, }), ], multiSelectedChannelIds: ['not_a_dm_channel', 'channel_id'], displayedChannels: [ testChannel, TestHelper.getChannelMock({ id: 'not_a_dm_channel', }), ], }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot of rendered items when multiselecting channels - DM channels and public channels category', () => { const props = { ...baseProps, categories: [ ...baseProps.categories, TestHelper.getCategoryMock({ id: 'channels_category_id', display_name: 'channels', type: CategoryTypes.CHANNELS, }), ], multiSelectedChannelIds: ['a_dm_channel', 'channel_id'], displayedChannels: [ TestHelper.getChannelMock({ ...testChannel, type: 'D', }), TestHelper.getChannelMock({ id: 'a_dm_channel', type: 'D', }), ], }; const wrapper = shallow( <SidebarChannelMenu {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,176
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_channel_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_channel_menu/__snapshots__/sidebar_channel_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should match snapshot and contain correct buttons 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should match snapshot of rendered items when multiselecting channels - DM channels and public channels category 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should match snapshot of rendered items when multiselecting channels - public channels and DM category 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is DM 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Conversation" id="sidebar_left.sidebar_channel_menu.muteConversation" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "D", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Close Conversation" id="sidebar_left.sidebar_channel_menu.leaveConversation" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is Town Square 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "town-square", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is favorite 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="unfavorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Unfavorite" id="sidebar_left.sidebar_channel_menu.unfavoriteChannel" /> } leadingElement={ <StarIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is muted 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="unmute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Unmute Channel" id="sidebar_left.sidebar_channel_menu.unmuteChannel" /> } leadingElement={ <BellOffOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is private 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "P", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is read 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsUnread-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Unread" id="sidebar_left.sidebar_channel_menu.markAsUnread" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `; exports[`components/sidebar/sidebar_channel/sidebar_channel_menu should show correct menu items when channel is unread 1`] = ` <Menu menu={ Object { "aria-label": "Edit channel menu", "id": "SidebarChannelMenu-MenuList-channel_id", "onToggle": [MockFunction], } } menuButton={ Object { "aria-label": "Channel options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton", "id": "SidebarChannelMenu-Button-channel_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarChannelMenu-ButtonTooltip-channel_id", "text": "Channel options", } } > <MenuItem id="markAsRead-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mark as Read" id="sidebar_left.sidebar_channel_menu.markAsRead" /> } leadingElement={ <MarkAsUnreadIcon size={18} /> } onClick={[Function]} /> <MenuItem id="favorite-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Favorite" id="sidebar_left.sidebar_channel_menu.favoriteChannel" /> } leadingElement={ <StarOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem id="mute-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Channel" id="sidebar_left.sidebar_channel_menu.muteChannel" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <Memo(ChannelMoveToSubMenu) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <MenuItemSeparator /> <MenuItem id="copyLink-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Copy Link" id="sidebar_left.sidebar_channel_menu.copyLink" /> } leadingElement={ <LinkVariantIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup="true" id="addMembers-channel_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="sidebar_left.sidebar_channel_menu.addMembers" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="leave-channel_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Leave Channel" id="sidebar_left.sidebar_channel_menu.leaveChannel" /> } leadingElement={ <ExitToAppIcon size={18} /> } onClick={[Function]} /> </Menu> `;
3,178
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_direct_channel/sidebar_direct_channel.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ChannelType} from '@mattermost/types/channels'; import SidebarDirectChannel from 'components/sidebar/sidebar_channel/sidebar_direct_channel/sidebar_direct_channel'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; describe('components/sidebar/sidebar_channel/sidebar_direct_channel', () => { const baseProps = { channel: { id: 'channel_id', display_name: 'channel_display_name', create_at: 0, update_at: 0, delete_at: 0, team_id: '', type: 'O' as ChannelType, name: '', header: '', purpose: '', last_post_at: 0, last_root_post_at: 0, creator_id: '', scheme_id: '', group_constrained: false, }, teammate: TestHelper.getUserMock(), currentTeamName: 'team_name', currentUserId: 'current_user_id', redirectChannel: 'redirect-channel', active: false, isMobile: false, actions: { savePreferences: jest.fn(), leaveDirectChannel: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallowWithIntl( <SidebarDirectChannel {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot if DM is with current user', () => { const props = { ...baseProps, currentUserId: baseProps.teammate.id, }; const wrapper = shallowWithIntl( <SidebarDirectChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot if DM is with deleted user', () => { const props = { ...baseProps, teammate: { ...baseProps.teammate, delete_at: 1234, }, }; const wrapper = shallowWithIntl( <SidebarDirectChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot if DM is with bot with custom icon', () => { const props = { ...baseProps, teammate: { ...baseProps.teammate, is_bot: true, }, }; const wrapper = shallowWithIntl( <SidebarDirectChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,180
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_direct_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_direct_channel/__snapshots__/sidebar_direct_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_channel/sidebar_direct_channel should match snapshot 1`] = ` <Connect(SidebarChannelLink) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <ProfilePicture hasMention={false} isEmoji={false} newStatusIcon={true} popoverPlacement="right" size="xs" src="/api/v4/users/user_id/image" statusClass="DirectChannel__status-icon " wrapperClass="DirectChannel__profile-picture" /> } label="channel_display_name" link="/team_name/messages/@some-user" teammateId="user_id" /> `; exports[`components/sidebar/sidebar_channel/sidebar_direct_channel should match snapshot if DM is with bot with custom icon 1`] = ` <Connect(SidebarChannelLink) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <ProfilePicture hasMention={false} isEmoji={false} newStatusIcon={true} popoverPlacement="right" size="xs" src="/api/v4/users/user_id/image" status="" statusClass="DirectChannel__status-icon " wrapperClass="DirectChannel__profile-picture" /> } label="channel_display_name" link="/team_name/messages/@some-user" teammateId="user_id" /> `; exports[`components/sidebar/sidebar_channel/sidebar_direct_channel should match snapshot if DM is with current user 1`] = ` <Connect(SidebarChannelLink) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <ProfilePicture hasMention={false} isEmoji={false} newStatusIcon={true} popoverPlacement="right" size="xs" src="/api/v4/users/user_id/image" statusClass="DirectChannel__status-icon " wrapperClass="DirectChannel__profile-picture" /> } label="channel_display_name (you)" link="/team_name/messages/@some-user" teammateId="user_id" /> `; exports[`components/sidebar/sidebar_channel/sidebar_direct_channel should match snapshot if DM is with deleted user 1`] = ` <Connect(SidebarChannelLink) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "channel_display_name", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "team_id": "", "type": "O", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <i className="icon icon-archive-outline" /> } label="channel_display_name" link="/team_name/messages/@some-user" teammateId="user_id" /> `;
3,184
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_header/sidebar_header.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 IconButton from '@mattermost/compass-components/components/icon-button'; // eslint-disable-line no-restricted-imports import {CloudProducts} from 'utils/constants'; import {FileSizes} from 'utils/file_utils'; import SidebarHeader from './sidebar_header'; import type {Props} from './sidebar_header'; import AddChannelDropdown from '../add_channel_dropdown'; let props: Props; const mockDispatch = jest.fn(); let mockState: any; 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/SidebarHeader', () => { beforeEach(() => { props = { showNewChannelModal: jest.fn(), showMoreChannelsModal: jest.fn(), invitePeopleModal: jest.fn(), showCreateCategoryModal: jest.fn(), canCreateChannel: true, canJoinPublicChannel: true, handleOpenDirectMessagesModal: jest.fn(), unreadFilterEnabled: true, showCreateUserGroupModal: jest.fn(), userGroupsEnabled: false, canCreateCustomGroups: true, }; mockState = { entities: { general: { config: {}, }, preferences: { myPreferences: {}, }, teams: { currentTeamId: 'currentteam', teams: { currentteam: { id: 'currentteam', description: 'et iste illum reprehenderit aliquid in rem itaque in maxime eius.', }, }, }, users: { profiles: { uid: {}, }, currentUserId: 'uid', }, usage: { integrations: { enabled: 11, enabledLoaded: true, }, messages: { history: 10000, historyLoaded: true, }, files: { totalStorage: FileSizes.Gigabyte, totalStorageLoaded: true, }, teams: { active: 1, teamsLoaded: true, }, boards: { cards: 500, cardsLoaded: true, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, }, limits: { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, }, boards: { cards: 500, views: 5, }, }, }, }, }, views: { addChannelDropdown: { isOpen: false, }, }, }; }); it('should show AddChannelDropdown', () => { const wrapper = shallow(<SidebarHeader {...props}/>); expect(wrapper.find(AddChannelDropdown).length).toBe(1); }); it('should embed teams menu dropdown into heading', () => { const wrapper = shallow(<SidebarHeader {...props}/>); expect(wrapper.find(IconButton).length).toBe(0); expect(wrapper.find('i').prop('className')).toBe('icon icon-chevron-down'); }); });
3,187
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_list/sidebar_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 {MovementMode, DropResult} from 'react-beautiful-dnd'; import {CategorySorting} from '@mattermost/types/channel_categories'; import type {ChannelType} from '@mattermost/types/channels'; import type {TeamType} from '@mattermost/types/teams'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import {DraggingStates, DraggingStateTypes} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import SidebarList from './sidebar_list'; describe('SidebarList', () => { const currentChannel = TestHelper.getChannelMock({ id: 'channel_id', display_name: 'channel_display_name', create_at: 0, update_at: 0, delete_at: 0, team_id: '', type: 'O' as ChannelType, name: '', header: '', purpose: '', last_post_at: 0, last_root_post_at: 0, creator_id: '', scheme_id: '', group_constrained: false, }); const unreadChannel = { id: 'channel_id_2', display_name: 'channel_display_name_2', create_at: 0, update_at: 0, delete_at: 0, team_id: '', type: 'O' as ChannelType, name: '', header: '', purpose: '', last_post_at: 0, last_root_post_at: 0, creator_id: '', scheme_id: '', group_constrained: false, }; const baseProps = { currentTeam: TestHelper.getTeamMock({ id: 'kemjcpu9bi877yegqjs18ndp4r', invite_id: 'ojsnudhqzbfzpk6e4n6ip1hwae', name: 'test', create_at: 123, update_at: 123, delete_at: 123, display_name: 'test', description: 'test', email: 'test', type: 'O' as TeamType, company_name: 'test', allowed_domains: 'test', allow_open_invite: false, scheme_id: 'test', group_constrained: false, }), currentChannelId: currentChannel.id, categories: [ { id: 'category1', team_id: 'team1', user_id: '', type: CategoryTypes.CUSTOM, display_name: 'custom_category_1', sorting: CategorySorting.Alphabetical, channel_ids: ['channel_id', 'channel_id_2'], muted: false, collapsed: false, }, ], unreadChannelIds: ['channel_id_2'], displayedChannels: [currentChannel, unreadChannel], newCategoryIds: [], multiSelectedChannelIds: [], isUnreadFilterEnabled: false, draggingState: {}, categoryCollapsedState: {}, handleOpenMoreDirectChannelsModal: jest.fn(), onDragStart: jest.fn(), onDragEnd: jest.fn(), showUnreadsCategory: false, collapsedThreads: true, hasUnreadThreads: false, currentStaticPageId: '', staticPages: [], actions: { switchToChannelById: jest.fn(), switchToLhsStaticPage: jest.fn(), close: jest.fn(), moveChannelsInSidebar: jest.fn(), moveCategory: jest.fn(), removeFromCategory: jest.fn(), setDraggingState: jest.fn(), stopDragging: jest.fn(), clearChannelSelection: jest.fn(), multiSelectChannelAdd: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <SidebarList {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); const draggable = wrapper.find('Connect(Droppable)').first(); const children: any = draggable.prop('children')!; const inner = shallow( children({}, {}), ); expect(inner).toMatchSnapshot(); }); test('should close sidebar on mobile when channel is selected (ie. changed)', () => { const wrapper = shallow( <SidebarList {...baseProps}/>, ); wrapper.setProps({currentChannelId: 'new_channel_id'}); expect(baseProps.actions.close).toHaveBeenCalled(); }); test('should scroll to top when team changes', () => { const wrapper = shallow<SidebarList>( <SidebarList {...baseProps}/>, ); wrapper.instance().scrollbar = { current: { scrollToTop: jest.fn(), } as any, }; const newCurrentTeam = { ...baseProps.currentTeam, id: 'new_team', }; wrapper.setProps({currentTeam: newCurrentTeam}); expect(wrapper.instance().scrollbar.current!.scrollToTop).toHaveBeenCalled(); }); test('should display unread scroll indicator when channels appear outside visible area', () => { const wrapper = shallow<SidebarList>( <SidebarList {...baseProps}/>, ); const instance = wrapper.instance(); instance.scrollbar = { current: { getScrollTop: jest.fn(() => 0), getClientHeight: jest.fn(() => 500), } as any, }; instance.channelRefs.set(unreadChannel.id, { offsetTop: 1, offsetHeight: 0, } as any); instance.updateUnreadIndicators(); expect(instance.state.showTopUnread).toBe(true); instance.channelRefs.set(unreadChannel.id, { offsetTop: 501, offsetHeight: 0, } as any); instance.updateUnreadIndicators(); expect(instance.state.showBottomUnread).toBe(true); }); test('should scroll to correct position when scrolling to channel', () => { const wrapper = shallow<SidebarList>( <SidebarList {...baseProps}/>, ); const instance = wrapper.instance(); instance.scrollToPosition = jest.fn(); instance.scrollbar = { current: { scrollTop: jest.fn(), getScrollTop: jest.fn(() => 100), getClientHeight: jest.fn(() => 500), } as any, }; instance.channelRefs.set(unreadChannel.id, { offsetTop: 50, offsetHeight: 20, } as any); instance.scrollToChannel(unreadChannel.id); expect(instance.scrollToPosition).toBeCalledWith(8); // includes margin and category header height }); test('should set the dragging state based on type', () => { (global as any).document.querySelectorAll = jest.fn().mockReturnValue([{ style: {}, }]); const wrapper = shallow<SidebarList>( <SidebarList {...baseProps}/>, ); const categoryBefore = { draggableId: baseProps.categories[0].id, mode: 'SNAP' as MovementMode, }; const expectedCategoryBefore = { state: DraggingStates.CAPTURE, id: categoryBefore.draggableId, type: DraggingStateTypes.CATEGORY, }; wrapper.instance().onBeforeCapture(categoryBefore); expect(baseProps.actions.setDraggingState).toHaveBeenCalledWith(expectedCategoryBefore); const channelBefore = { draggableId: currentChannel.id, mode: 'SNAP' as MovementMode, }; const expectedChannelBefore = { state: DraggingStates.CAPTURE, id: channelBefore.draggableId, type: DraggingStateTypes.CHANNEL, }; wrapper.instance().onBeforeCapture(channelBefore); expect(baseProps.actions.setDraggingState).toHaveBeenCalledWith(expectedChannelBefore); }); test('should call correct action on dropping item', () => { const wrapper = shallow<SidebarList>( <SidebarList {...baseProps}/>, ); const categoryResult: DropResult = { reason: 'DROP', type: 'SIDEBAR_CATEGORY', source: { droppableId: 'droppable-categories', index: 0, }, destination: { droppableId: 'droppable-categories', index: 5, }, draggableId: baseProps.categories[0].id, mode: 'SNAP' as MovementMode, }; wrapper.instance().onDragEnd(categoryResult); expect(baseProps.actions.moveCategory).toHaveBeenCalledWith(baseProps.currentTeam.id, categoryResult.draggableId, categoryResult.destination!.index); const channelResult: DropResult = { reason: 'DROP', type: 'SIDEBAR_CHANNEL', source: { droppableId: baseProps.categories[0].id, index: 0, }, destination: { droppableId: baseProps.categories[0].id, index: 5, }, draggableId: baseProps.categories[0].id, mode: 'SNAP' as MovementMode, }; wrapper.instance().onDragEnd(channelResult); expect(baseProps.actions.moveChannelsInSidebar).toHaveBeenCalledWith(channelResult.destination!.droppableId, channelResult.destination!.index, channelResult.draggableId); }); });
3,189
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_list/__snapshots__/sidebar_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`SidebarList should match snapshot 1`] = ` <Fragment> <GlobalThreadsLink /> <Memo(DraftsLink) /> <div aria-label="channel sidebar region" className="SidebarNavContainer a11y__region" data-a11y-disable-nav={false} data-a11y-sort-order="7" id="sidebar-left" onTransitionEnd={[Function]} role="application" > <UnreadChannelIndicator content={ <Memo(MemoizedFormattedMessage) defaultMessage="More unreads" id="sidebar.unreads" /> } extraClass="nav-pills__unread-indicator-top" name="Top" onClick={[Function]} show={false} /> <UnreadChannelIndicator content={ <Memo(MemoizedFormattedMessage) defaultMessage="More unreads" id="sidebar.unreads" /> } extraClass="nav-pills__unread-indicator-bottom" name="Bottom" onClick={[Function]} show={false} /> <Scrollbars autoHeight={false} autoHeightMax={200} autoHeightMin={0} autoHide={true} autoHideDuration={500} autoHideTimeout={500} hideTracksWhenNotNeeded={false} onScroll={[Function]} renderThumbHorizontal={[Function]} renderThumbVertical={[Function]} renderTrackHorizontal={[Function]} renderTrackVertical={[Function]} renderView={[Function]} style={ Object { "position": "absolute", } } tagName="div" thumbMinSize={30} universal={false} > <DragDropContext onBeforeCapture={[Function]} onBeforeDragStart={[Function]} onDragEnd={[Function]} onDragStart={[Function]} > <Connect(Droppable) direction="vertical" droppableId="droppable-categories" getContainerForClone={[Function]} ignoreContainerClipping={false} isCombineEnabled={false} isDropDisabled={false} mode="standard" renderClone={null} type="SIDEBAR_CATEGORY" > <Component /> </Connect(Droppable)> </DragDropContext> </Scrollbars> </div> </Fragment> `; exports[`SidebarList should match snapshot 2`] = ` <div id="sidebar-droppable-categories" > <Connect(SidebarCategory) category={ Object { "channel_ids": Array [ "channel_id", "channel_id_2", ], "collapsed": false, "display_name": "custom_category_1", "id": "category1", "muted": false, "sorting": "alpha", "team_id": "team1", "type": "custom", "user_id": "", } } categoryIndex={0} handleOpenMoreDirectChannelsModal={[MockFunction]} isNewCategory={false} key="category1" setChannelRef={[Function]} /> </div> `;
3,192
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/unread_channel_indicator/unread_channel_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 UnreadChannelIndicator from './unread_channel_indicator'; describe('UnreadChannelIndicator', () => { const baseProps = { onClick: jest.fn(), show: true, }; test('should match snapshot', () => { const props = { ...baseProps, show: false, }; const wrapper = shallow( <UnreadChannelIndicator {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when show is set', () => { const wrapper = shallow( <UnreadChannelIndicator {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when content is text', () => { const props = { ...baseProps, content: 'foo', }; const wrapper = shallow( <UnreadChannelIndicator {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when content is an element', () => { const props = { ...baseProps, content: <div>{'foo'}</div>, }; const wrapper = shallow( <UnreadChannelIndicator {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have called onClick', () => { const props = { ...baseProps, content: <div>{'foo'}</div>, name: 'name', }; const wrapper = shallow( <UnreadChannelIndicator {...props}/>, ); wrapper.simulate('click'); expect(props.onClick).toHaveBeenCalledTimes(1); }); });
3,194
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/unread_channel_indicator
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/unread_channel_indicator/__snapshots__/unread_channel_indicator.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`UnreadChannelIndicator should match snapshot 1`] = ` <div className="nav-pills__unread-indicator" id="unreadIndicatorundefined" onClick={[MockFunction]} > <UnreadBelowIcon className="icon icon__unread" /> </div> `; exports[`UnreadChannelIndicator should match snapshot when content is an element 1`] = ` <div className="nav-pills__unread-indicator nav-pills__unread-indicator--visible" id="unreadIndicatorundefined" onClick={[MockFunction]} > <UnreadBelowIcon className="icon icon__unread" /> <div> foo </div> </div> `; exports[`UnreadChannelIndicator should match snapshot when content is text 1`] = ` <div className="nav-pills__unread-indicator nav-pills__unread-indicator--visible" id="unreadIndicatorundefined" onClick={[MockFunction]} > <UnreadBelowIcon className="icon icon__unread" /> foo </div> `; exports[`UnreadChannelIndicator should match snapshot when show is set 1`] = ` <div className="nav-pills__unread-indicator nav-pills__unread-indicator--visible" id="unreadIndicatorundefined" onClick={[MockFunction]} > <UnreadBelowIcon className="icon icon__unread" /> </div> `;
3,200
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/signup/signup.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 React from 'react'; import {IntlProvider} from 'react-intl'; import {BrowserRouter} from 'react-router-dom'; import type {ClientConfig} from '@mattermost/types/config'; import {RequestStatus} from 'mattermost-redux/constants'; import * as useCWSAvailabilityCheckAll from 'components/common/hooks/useCWSAvailabilityCheck'; import SaveButton from 'components/save_button'; import Signup from 'components/signup/signup'; import Input from 'components/widgets/inputs/input/input'; import PasswordInput from 'components/widgets/inputs/password_input/password_input'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {act, renderWithContext, screen} from 'tests/react_testing_utils'; import {WindowSizes} from 'utils/constants'; import type {GlobalState} from 'types/store'; let mockState: GlobalState; let mockLocation = {pathname: '', search: '', hash: ''}; const mockHistoryPush = jest.fn(); let mockLicense = {IsLicensed: 'true', Cloud: 'false'}; let mockConfig: Partial<ClientConfig>; let mockDispatch = jest.fn(); const intlProviderProps = { defaultLocale: 'en', locale: 'en', messages: {}, }; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom') as typeof import('react-router-dom'), useLocation: () => mockLocation, useHistory: () => ({ push: mockHistoryPush, }), })); jest.mock('mattermost-redux/selectors/entities/general', () => ({ ...jest.requireActual('mattermost-redux/selectors/entities/general') as typeof import('mattermost-redux/selectors/entities/general'), getLicense: () => mockLicense, getConfig: () => mockConfig, })); jest.mock('mattermost-redux/selectors/entities/users', () => ({ ...jest.requireActual('mattermost-redux/selectors/entities/users') as typeof import('mattermost-redux/selectors/entities/users'), getCurrentUserId: () => '', })); jest.mock('actions/team_actions', () => ({ ...jest.requireActual('actions/team_actions') as typeof import('actions/team_actions'), addUsersToTeamFromInvite: jest.fn().mockResolvedValue({name: 'teamName'}), })); jest.mock('mattermost-redux/actions/users', () => ({ ...jest.requireActual('mattermost-redux/actions/users') as typeof import('mattermost-redux/actions/users'), createUser: jest.fn().mockResolvedValue({data: {}}), })); jest.mock('actions/views/login', () => ({ ...jest.requireActual('actions/views/login') as typeof import('actions/views/login'), loginById: jest.fn().mockResolvedValue({data: {}}), })); jest.mock('actions/team_actions', () => ({ ...jest.requireActual('actions/team_actions') as typeof import('actions/team_actions'), addUserToTeamFromInvite: jest.fn().mockResolvedValue({data: {}}), })); jest.mock('actions/storage'); const actImmediate = (wrapper: ReactWrapper) => act( () => new Promise<void>((resolve) => { setImmediate(() => { wrapper.update(); resolve(); }); }), ); describe('components/signup/Signup', () => { beforeEach(() => { mockLocation = {pathname: '', search: '', hash: ''}; mockLicense = {IsLicensed: 'true', Cloud: 'false'}; mockState = { entities: { general: { config: {}, license: {}, }, users: { currentUserId: '', profiles: { user1: { id: 'user1', roles: '', }, }, }, teams: { currentTeamId: 'team1', teams: { team1: { id: 'team1', name: 'team-1', displayName: 'Team 1', }, }, myMembers: { team1: {roles: 'team_role'}, }, }, }, requests: { users: { logout: { status: RequestStatus.NOT_STARTED, }, }, }, storage: { initialized: true, }, views: { browser: { windowSize: WindowSizes.DESKTOP_VIEW, }, }, } as unknown as GlobalState; mockConfig = { EnableLdap: 'true', EnableSaml: 'true', EnableSignInWithEmail: 'true', EnableSignInWithUsername: 'true', EnableSignUpWithEmail: 'true', EnableSignUpWithGitLab: 'true', EnableSignUpWithOffice365: 'true', EnableSignUpWithGoogle: 'true', EnableSignUpWithOpenId: 'true', EnableOpenServer: 'true', LdapLoginFieldName: '', GitLabButtonText: '', GitLabButtonColor: '', OpenIdButtonText: '', OpenIdButtonColor: '', SamlLoginButtonText: '', EnableCustomBrand: 'false', CustomBrandText: '', CustomDescriptionText: '', SiteName: 'Mattermost', ExperimentalPrimaryTeam: '', }; }); it('should match snapshot for all signup options enabled with isLicensed enabled', () => { const wrapper = shallow( <Signup/>, ); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot for all signup options enabled with isLicensed disabled', () => { mockLicense = {IsLicensed: 'false', Cloud: 'false'}; const wrapper = shallow( <Signup/>, ); expect(wrapper).toMatchSnapshot(); }); it('should create user, log in and redirect to invite teamname', async () => { mockLocation.search = 'd=%7B"name"%3A"teamName"%7D'; mockDispatch = jest.fn(). mockResolvedValueOnce({}). // removeGlobalItem mockResolvedValueOnce({data: {id: 'userId', password: 'password', email: '[email protected]}'}}). // createUser mockResolvedValueOnce({error: {server_error_id: 'api.user.login.not_verified.app_error'}}); // loginById const wrapper = mountWithIntl( <IntlProvider {...intlProviderProps}> <BrowserRouter> <Signup/> </BrowserRouter> </IntlProvider>, ); const emailInput = wrapper.find(Input).first().find('input').first(); emailInput.simulate('change', {target: {value: '[email protected]'}}); const nameInput = wrapper.find('#input_name').first(); nameInput.simulate('change', {target: {value: 'jdoe'}}); const passwordInput = wrapper.find(PasswordInput).first().find('input').first(); passwordInput.simulate('change', {target: {value: 'password'}}); const saveButton = wrapper.find(SaveButton).first(); expect(saveButton.props().disabled).toEqual(false); saveButton.find('button').first().simulate('click'); await actImmediate(wrapper); expect(wrapper.find(Input).first().props().disabled).toEqual(true); expect(wrapper.find('#input_name').first().props().disabled).toEqual(true); expect(wrapper.find(PasswordInput).first().props().disabled).toEqual(true); expect(mockHistoryPush).toHaveBeenCalledWith('/should_verify_email?email=jdoe%40mm.com&teamname=teamName'); }); it('should create user, log in and redirect to default team', async () => { mockDispatch = jest.fn(). mockResolvedValueOnce({}). // removeGlobalItem mockResolvedValueOnce({data: {id: 'userId', password: 'password', email: '[email protected]}'}}). // createUser mockResolvedValueOnce({}); // loginById const wrapper = mountWithIntl( <IntlProvider {...intlProviderProps}> <BrowserRouter> <Signup/> </BrowserRouter> </IntlProvider>, ); const emailInput = wrapper.find(Input).first().find('input').first(); emailInput.simulate('change', {target: {value: '[email protected]'}}); const nameInput = wrapper.find('#input_name').first(); nameInput.simulate('change', {target: {value: 'jdoe'}}); const passwordInput = wrapper.find(PasswordInput).first().find('input').first(); passwordInput.simulate('change', {target: {value: 'password'}}); const saveButton = wrapper.find(SaveButton).first(); expect(saveButton.props().disabled).toEqual(false); saveButton.find('button').first().simulate('click'); await actImmediate(wrapper); expect(wrapper.find(Input).first().props().disabled).toEqual(true); expect(wrapper.find('#input_name').first().props().disabled).toEqual(true); expect(wrapper.find(PasswordInput).first().props().disabled).toEqual(true); }); it('should add user to team and redirect when team invite valid and logged in', async () => { mockLocation.search = '?id=ppni7a9t87fn3j4d56rwocdctc'; const wrapper = shallow( <Signup/>, ); setTimeout(() => { expect(mockHistoryPush).toHaveBeenCalledWith('/teamName/channels/town-square'); expect(wrapper).toMatchSnapshot(); }, 0); }); it('should handle failure adding user to team when team invite and logged in', () => { mockLocation.search = '?id=ppni7a9t87fn3j4d56rwocdctc'; const wrapper = shallow( <Signup/>, ); setTimeout(() => { expect(mockHistoryPush).not.toHaveBeenCalled(); expect(wrapper.find('.content-layout-column-title').text()).toEqual('This invite link is invalid'); }); }); it('should show newsletter check box opt-in for self-hosted non airgapped workspaces', async () => { jest.spyOn(useCWSAvailabilityCheckAll, 'default').mockImplementation(() => true); mockLicense = {IsLicensed: 'true', Cloud: 'false'}; const {container: signupContainer} = renderWithContext( <Signup/>, ); screen.getByTestId('signup-body-card-form-check-newsletter'); const checkInput = screen.getByTestId('signup-body-card-form-check-newsletter'); expect(checkInput).toHaveAttribute('type', 'checkbox'); expect(signupContainer).toHaveTextContent('I would like to receive Mattermost security updates via newsletter. By subscribing, I consent to receive emails from Mattermost with product updates, promotions, and company news. I have read the Privacy Policy and understand that I can unsubscribe at any time'); }); it('should NOT show newsletter check box opt-in for self-hosted AND airgapped workspaces', async () => { jest.spyOn(useCWSAvailabilityCheckAll, 'default').mockImplementation(() => false); mockLicense = {IsLicensed: 'true', Cloud: 'false'}; const {container: signupContainer} = renderWithContext( <Signup/>, ); expect(() => screen.getByTestId('signup-body-card-form-check-newsletter')).toThrow(); expect(signupContainer).toHaveTextContent('Interested in receiving Mattermost security, product, promotions, and company updates updates via newsletter?Sign up at https://mattermost.com/security-updates/.'); }); it('should show newsletter related opt-in or text for cloud', async () => { jest.spyOn(useCWSAvailabilityCheckAll, 'default').mockImplementation(() => true); mockLicense = {IsLicensed: 'true', Cloud: 'true'}; const {container: signupContainer} = renderWithContext( <Signup/>, ); screen.getByTestId('signup-body-card-form-check-newsletter'); const checkInput = screen.getByTestId('signup-body-card-form-check-newsletter'); expect(checkInput).toHaveAttribute('type', 'checkbox'); expect(signupContainer).toHaveTextContent('I would like to receive Mattermost security updates via newsletter. By subscribing, I consent to receive emails from Mattermost with product updates, promotions, and company news. I have read the Privacy Policy and understand that I can unsubscribe at any time'); }); });
3,202
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/signup
petrpan-code/mattermost/mattermost/webapp/channels/src/components/signup/__snapshots__/signup.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/signup/Signup should match snapshot for all signup options enabled with isLicensed disabled 1`] = ` <div className="signup-body" > <div className="signup-body-content" > <div className="signup-body-message with-alternate-link" > <h1 className="signup-body-message-title" > Let’s get started </h1> <p className="signup-body-message-subtitle" > Create your Mattermost account to start collaborating with your team </p> <div className="signup-body-message-svg" > <Svg /> </div> </div> <div className="signup-body-action" > <AlternateLink alternateLinkLabel="Log in" alternateLinkPath="/login" alternateMessage="Already have an account?" className="signup-body-alternate-link" /> <div className="signup-body-card" > <div className="signup-body-card-content" onKeyDown={[Function]} tabIndex={0} > <p className="signup-body-card-title" > Create your account </p> <div className="signup-body-card-form" > <ForwardRef autoFocus={true} className="signup-body-card-form-email-input" customMessage={null} disabled={false} inputSize="large" name="email" onBlur={[Function]} onChange={[Function]} placeholder="Email address" type="text" value="" /> <ForwardRef autoFocus={false} className="signup-body-card-form-name-input" customMessage={ Object { "type": "info", "value": "You can use lowercase letters, numbers, periods, dashes, and underscores.", } } disabled={false} inputSize="large" name="name" onBlur={[Function]} onChange={[Function]} placeholder="Choose a Username" type="text" value="" /> <ForwardRef className="signup-body-card-form-password-input" createMode={true} disabled={false} error="" info="Must be 5-64 characters long." inputSize="large" onBlur={[Function]} onChange={[Function]} value="" /> <div className="newsletter" > <span className="interested" > Interested in receiving Mattermost security, product, promotions, and company updates updates via newsletter? </span> <span className="link" > Sign up at <ExternalLink href="https://mattermost.com/security-updates/" key=".1" location="signup" > https://mattermost.com/security-updates/ </ExternalLink> . </span> </div> <SaveButton btnClass="" defaultMessage="Create account" disabled={true} extraClasses="signup-body-card-form-button-submit large" onClick={[Function]} saving={false} savingMessage="Creating account…" /> </div> <div className="signup-body-card-form-divider" > <span className="signup-body-card-form-divider-label" > or create an account with </span> </div> <div className="signup-body-card-form-login-options" > <ExternalLoginButton icon={<LoginGitlabIcon />} id="gitlab" key="gitlab" label="GitLab" onClick={[Function]} style={ Object { "borderColor": "", "color": "", } } url="/oauth/gitlab/signup" /> </div> <p className="signup-body-card-agreement" > <FormattedMarkdownMessage defaultMessage="By proceeding to create your account and use {siteName}, you agree to our [Terms of Use]({TermsOfServiceLink}) and [Privacy Policy]({PrivacyPolicyLink}). If you do not agree, you cannot use {siteName}." id="create_team.agreement" values={ Object { "PrivacyPolicyLink": "!undefined", "TermsOfServiceLink": "!undefined", "siteName": "Mattermost", } } /> </p> </div> </div> </div> </div> </div> `; exports[`components/signup/Signup should match snapshot for all signup options enabled with isLicensed enabled 1`] = ` <div className="signup-body" > <div className="signup-body-content" > <div className="signup-body-message with-alternate-link" > <h1 className="signup-body-message-title" > Let’s get started </h1> <p className="signup-body-message-subtitle" > Create your Mattermost account to start collaborating with your team </p> <div className="signup-body-message-svg" > <Svg /> </div> </div> <div className="signup-body-action" > <AlternateLink alternateLinkLabel="Log in" alternateLinkPath="/login" alternateMessage="Already have an account?" className="signup-body-alternate-link" /> <div className="signup-body-card" > <div className="signup-body-card-content" onKeyDown={[Function]} tabIndex={0} > <p className="signup-body-card-title" > Create your account </p> <div className="signup-body-card-form" > <ForwardRef autoFocus={true} className="signup-body-card-form-email-input" customMessage={null} disabled={false} inputSize="large" name="email" onBlur={[Function]} onChange={[Function]} placeholder="Email address" type="text" value="" /> <ForwardRef autoFocus={false} className="signup-body-card-form-name-input" customMessage={ Object { "type": "info", "value": "You can use lowercase letters, numbers, periods, dashes, and underscores.", } } disabled={false} inputSize="large" name="name" onBlur={[Function]} onChange={[Function]} placeholder="Choose a Username" type="text" value="" /> <ForwardRef className="signup-body-card-form-password-input" createMode={true} disabled={false} error="" info="Must be 5-64 characters long." inputSize="large" onBlur={[Function]} onChange={[Function]} value="" /> <div className="newsletter" > <span className="interested" > Interested in receiving Mattermost security, product, promotions, and company updates updates via newsletter? </span> <span className="link" > Sign up at <ExternalLink href="https://mattermost.com/security-updates/" key=".1" location="signup" > https://mattermost.com/security-updates/ </ExternalLink> . </span> </div> <SaveButton btnClass="" defaultMessage="Create account" disabled={true} extraClasses="signup-body-card-form-button-submit large" onClick={[Function]} saving={false} savingMessage="Creating account…" /> </div> <div className="signup-body-card-form-divider" > <span className="signup-body-card-form-divider-label" > or create an account with </span> </div> <div className="signup-body-card-form-login-options" > <ExternalLoginButton icon={<LoginGitlabIcon />} id="gitlab" key="gitlab" label="GitLab" onClick={[Function]} style={ Object { "borderColor": "", "color": "", } } url="/oauth/gitlab/signup" /> <ExternalLoginButton icon={<LoginGoggleIcon />} id="google" key="google" label="Google" onClick={[Function]} url="/oauth/google/signup" /> <ExternalLoginButton icon={<LoginOffice365Icon />} id="office365" key="office365" label="Office 365" onClick={[Function]} url="/oauth/office365/signup" /> <ExternalLoginButton icon={<LoginOpenIdIcon />} id="openid" key="openid" label="Open ID" onClick={[Function]} style={ Object { "borderColor": "", "color": "", } } url="/oauth/openid/signup" /> <ExternalLoginButton icon={<LockIcon />} id="ldap" key="ldap" label="AD/LDAP Credentials" onClick={[Function]} url="/login?extra=create_ldap" /> <ExternalLoginButton icon={<LockIcon />} id="saml" key="saml" label="SAML" onClick={[Function]} url="/login/sso/saml?action=signup" /> </div> <p className="signup-body-card-agreement" > <FormattedMarkdownMessage defaultMessage="By proceeding to create your account and use {siteName}, you agree to our [Terms of Use]({TermsOfServiceLink}) and [Privacy Policy]({PrivacyPolicyLink}). If you do not agree, you cannot use {siteName}." id="create_team.agreement" values={ Object { "PrivacyPolicyLink": "!undefined", "TermsOfServiceLink": "!undefined", "siteName": "Mattermost", } } /> </p> </div> </div> </div> </div> </div> `;
3,204
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/single_image_view/single_image_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 SingleImageView from 'components/single_image_view/single_image_view'; import SizeAwareImage from 'components/size_aware_image'; import {TestHelper} from 'utils/test_helper'; describe('components/SingleImageView', () => { const baseProps = { postId: 'original_post_id', fileInfo: TestHelper.getFileInfoMock({id: 'file_info_id'}), isRhsOpen: false, isEmbedVisible: true, actions: { toggleEmbedVisibility: jest.fn(), openModal: jest.fn(), getFilePublicLink: jest.fn(), }, enablePublicLink: false, }; test('should match snapshot', () => { const wrapper = shallow( <SingleImageView {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); wrapper.setState({loaded: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, SVG image', () => { const fileInfo = TestHelper.getFileInfoMock({ id: 'svg_file_info_id', name: 'name_svg', extension: 'svg', }); const props = {...baseProps, fileInfo}; const wrapper = shallow( <SingleImageView {...props}/>, ); wrapper.setState({viewPortWidth: 300}); expect(wrapper).toMatchSnapshot(); wrapper.setState({loaded: true}); expect(wrapper).toMatchSnapshot(); }); test('should call openModal on handleImageClick', () => { const wrapper = shallow( <SingleImageView {...baseProps}/>, ); wrapper.find('SizeAwareImage').at(0).simulate('click', {preventDefault: () => {}}); expect(baseProps.actions.openModal).toHaveBeenCalledTimes(1); }); test('should call toggleEmbedVisibility with post id', () => { const props = { ...baseProps, actions: { ...baseProps.actions, toggleEmbedVisibility: jest.fn(), }, }; const wrapper = shallow( <SingleImageView {...props}/>, ); const instance = wrapper.instance() as SingleImageView; instance.toggleEmbedVisibility(); expect(props.actions.toggleEmbedVisibility).toHaveBeenCalledTimes(1); expect(props.actions.toggleEmbedVisibility).toBeCalledWith('original_post_id'); }); test('should set loaded state on callback of onImageLoaded on SizeAwareImage component', () => { const wrapper = shallow( <SingleImageView {...baseProps}/>, ); expect(wrapper.state('loaded')).toEqual(false); wrapper.find(SizeAwareImage).prop('onImageLoaded')(); expect(wrapper.state('loaded')).toEqual(true); expect(wrapper).toMatchSnapshot(); }); test('should correctly pass prop down to surround small images with a container', () => { const wrapper = shallow( <SingleImageView {...baseProps}/>, ); expect(wrapper.find(SizeAwareImage).prop('handleSmallImageContainer')). toEqual(true); }); test('should not show filename when image is displayed', () => { const wrapper = shallow( <SingleImageView {...baseProps} isEmbedVisible={true} />, ); expect(wrapper.find('.image-header').text()).toHaveLength(0); }); test('should show filename when image is collapsed', () => { const wrapper = shallow( <SingleImageView {...baseProps} isEmbedVisible={false} />, ); expect(wrapper.find('.image-header').text()). toEqual(baseProps.fileInfo.name); }); describe('permalink preview', () => { test('should render with permalink styling if in permalink', () => { const props = { ...baseProps, isInPermalink: true, }; const wrapper = shallow(<SingleImageView {...props}/>); expect(wrapper.find('.image-permalink').exists()).toBe(true); expect(wrapper).toMatchSnapshot(); }); }); });
3,206
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/single_image_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/single_image_view/__snapshots__/single_image_view.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SingleImageView permalink preview should render with permalink styling if in permalink 1`] = ` <div className="file-view--single image-permalink" > <div className="file__image" > <div className="image-header image-header--expanded" > <button aria-label="Toggle Embed Visibility" className="style--none single-image-view__toggle" data-expanded={true} key="toggle" onClick={[Function]} > <span className="icon icon-menu-down" /> </button> </div> <div className="image-container image-permalink" style={Object {}} > <div className="image-loaded" style={Object {}} > <div className="image-permalink" > <SizeAwareImage className="image-permalink" dimensions={ Object { "height": 200, "width": 350, } } enablePublicLink={false} fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileURL="/api/v4/files/file_info_id" getFilePublicLink={[Function]} handleSmallImageContainer={true} onClick={[Function]} onImageLoaded={[Function]} showLoader={true} src="/api/v4/files/file_info_id/preview" /> </div> </div> </div> </div> </div> `; exports[`components/SingleImageView should match snapshot 1`] = ` <div className="file-view--single" > <div className="file__image" > <div className="image-header image-header--expanded" > <button aria-label="Toggle Embed Visibility" className="style--none single-image-view__toggle" data-expanded={true} key="toggle" onClick={[Function]} > <span className="icon icon-menu-down" /> </button> </div> <div className="image-container" style={Object {}} > <div className="image-loaded" style={Object {}} > <div className="" > <SizeAwareImage className="" dimensions={ Object { "height": 200, "width": 350, } } enablePublicLink={false} fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileURL="/api/v4/files/file_info_id" getFilePublicLink={[Function]} handleSmallImageContainer={true} onClick={[Function]} onImageLoaded={[Function]} showLoader={true} src="/api/v4/files/file_info_id/preview" /> </div> </div> </div> </div> </div> `; exports[`components/SingleImageView should match snapshot 2`] = ` <div className="file-view--single" > <div className="file__image" > <div className="image-header image-header--expanded" > <button aria-label="Toggle Embed Visibility" className="style--none single-image-view__toggle" data-expanded={true} key="toggle" onClick={[Function]} > <span className="icon icon-menu-down" /> </button> </div> <div className="image-container" style={Object {}} > <div className="image-loaded image-fade-in" style={Object {}} > <div className="" > <SizeAwareImage className="" dimensions={ Object { "height": 200, "width": 350, } } enablePublicLink={false} fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileURL="/api/v4/files/file_info_id" getFilePublicLink={[Function]} handleSmallImageContainer={true} onClick={[Function]} onImageLoaded={[Function]} showLoader={true} src="/api/v4/files/file_info_id/preview" /> </div> </div> </div> </div> </div> `; exports[`components/SingleImageView should match snapshot, SVG image 1`] = ` <div className="file-view--single" > <div className="file__image" > <div className="image-header image-header--expanded" > <button aria-label="Toggle Embed Visibility" className="style--none single-image-view__toggle" data-expanded={true} key="toggle" onClick={[Function]} > <span className="icon icon-menu-down" /> </button> </div> <div className="image-container" style={Object {}} > <div className="image-loaded svg" style={ Object { "width": "100%", } } > <div className="" > <SizeAwareImage className="" dimensions={ Object { "height": 200, "width": 350, } } enablePublicLink={false} fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "svg", "has_preview_image": true, "height": 200, "id": "svg_file_info_id", "mime_type": "mime_type", "name": "name_svg", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileURL="/api/v4/files/svg_file_info_id" getFilePublicLink={[Function]} handleSmallImageContainer={true} onClick={[Function]} onImageLoaded={[Function]} showLoader={true} src="/api/v4/files/svg_file_info_id/preview" /> </div> </div> </div> </div> </div> `; exports[`components/SingleImageView should match snapshot, SVG image 2`] = ` <div className="file-view--single" > <div className="file__image" > <div className="image-header image-header--expanded" > <button aria-label="Toggle Embed Visibility" className="style--none single-image-view__toggle" data-expanded={true} key="toggle" onClick={[Function]} > <span className="icon icon-menu-down" /> </button> </div> <div className="image-container" style={Object {}} > <div className="image-loaded image-fade-in svg" style={ Object { "width": "100%", } } > <div className="" > <SizeAwareImage className="" dimensions={ Object { "height": 200, "width": 350, } } enablePublicLink={false} fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "svg", "has_preview_image": true, "height": 200, "id": "svg_file_info_id", "mime_type": "mime_type", "name": "name_svg", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileURL="/api/v4/files/svg_file_info_id" getFilePublicLink={[Function]} handleSmallImageContainer={true} onClick={[Function]} onImageLoaded={[Function]} showLoader={true} src="/api/v4/files/svg_file_info_id/preview" /> </div> </div> </div> </div> </div> `; exports[`components/SingleImageView should set loaded state on callback of onImageLoaded on SizeAwareImage component 1`] = ` <div className="file-view--single" > <div className="file__image" > <div className="image-header image-header--expanded" > <button aria-label="Toggle Embed Visibility" className="style--none single-image-view__toggle" data-expanded={true} key="toggle" onClick={[Function]} > <span className="icon icon-menu-down" /> </button> </div> <div className="image-container" style={Object {}} > <div className="image-loaded image-fade-in" style={Object {}} > <div className="" > <SizeAwareImage className="" dimensions={ Object { "height": 200, "width": 350, } } enablePublicLink={false} fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileURL="/api/v4/files/file_info_id" getFilePublicLink={[Function]} handleSmallImageContainer={true} onClick={[Function]} onImageLoaded={[Function]} showLoader={true} src="/api/v4/files/file_info_id/preview" /> </div> </div> </div> </div> </div> `;
3,212
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/start_trial_form_modal/start_trial_form_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {BrowserRouter} from 'react-router-dom'; import type {DeepPartial} from '@mattermost/types/utilities'; import {trackEvent} from 'actions/telemetry_actions'; import { renderWithContext, screen, waitFor, } from 'tests/react_testing_utils'; import {ModalIdentifiers} from 'utils/constants'; import type {GlobalState} from 'types/store'; import StartTrialFormModal from '.'; jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); describe('components/start_trial_form_modal/start_trial_form_modal', () => { const state: DeepPartial<GlobalState> = { entities: { users: { currentUserId: 'user1', profiles: { user1: { id: 'user1', roles: '', email: '[email protected]', }, }, }, general: { license: { IsLicensed: 'true', Cloud: 'false', }, config: { TelemetryId: 'test123', }, }, }, views: { modals: { modalState: { [ModalIdentifiers.START_TRIAL_FORM_MODAL]: { open: true, }, }, }, admin: { navigationBlock: { blocked: true, }, }, }, }; const handleOnClose = jest.fn(); const props = { onClose: handleOnClose, page: 'some_modal', }; test('should match snapshot', async () => { const wrapper = await waitFor(() => { return renderWithContext( <BrowserRouter> <StartTrialFormModal {...props}/> </BrowserRouter>, state, ); }); expect(wrapper!).toMatchSnapshot(); }); test('should pre-fill email, fire trackEvent', () => { waitFor(() => { renderWithContext( <BrowserRouter> <StartTrialFormModal {...props}/> </BrowserRouter>, state, ); }); expect(screen.getByDisplayValue('[email protected]')).toBeInTheDocument(); expect(trackEvent).toHaveBeenCalled(); }); test('Start trial button should be disabled on load', () => { waitFor(() => { renderWithContext( <BrowserRouter> <StartTrialFormModal {...props}/> </BrowserRouter>, state, ); }); expect(screen.getByRole('button', {name: 'Start trial'})).toBeDisabled(); }); });
3,213
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/start_trial_form_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/start_trial_form_modal/__snapshots__/start_trial_form_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/start_trial_form_modal/start_trial_form_modal should match snapshot 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop in" /> <div class="fade StartTrialFormModal in modal" id="StartTrialFormModal" role="dialog" style="display: block; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal modal-dialog" > <div class="modal-content" role="document" > <div class="modal-header" > <button aria-label="Close" class="close" type="button" > <span aria-hidden="true" > × </span> <span class="sr-only" > Close </span> </button> <div class="title" > Start Trial </div> <div class="description" > Just a few quick items to help us tailor your trial experience. </div> </div> <div class="modal-body" > <div class="Input_container" > <fieldset class="Input_fieldset name_input" > <legend class="Input_legend" /> <div class="Input_wrapper" > <input aria-label="Name" class="Input form-control large" id="input_name" name="name" placeholder="Name" type="text" value="" /> </div> </fieldset> </div> <div class="Input_container" > <fieldset class="Input_fieldset email_input Input_fieldset___error Input_fieldset___legend" > <legend class="Input_legend Input_legend___focus" > Business Email </legend> <div class="Input_wrapper" > <input aria-label="Business Email" class="Input form-control large Input__focus" id="input_email" name="email" placeholder="Business Email" type="text" value="[email protected]" /> </div> </fieldset> <div class="Input___customMessage Input___error" > <i class="icon error icon-alert-circle-outline" /> <span> Please enter a valid business email address. </span> </div> </div> <div class="Input_container" > <fieldset class="Input_fieldset company_name_input" > <legend class="Input_legend" /> <div class="Input_wrapper" > <input aria-label="Company Name" class="Input form-control large" id="input_company_name" name="company_name" placeholder="Company Name" type="text" value="" /> </div> </fieldset> </div> <div class="DropdownInput Input_container" data-testid="" > <fieldset class="Input_fieldset company_size_dropdown" > <legend class="Input_legend" /> <div class="Input_wrapper" > <div class="Input company_size_dropdown css-2b097c-container" id="DropdownInput_company_size_dropdown" > <div class="DropdownInput__controlContainer" > <div class="DropDown__control css-1nr98fh-control" > <div class="DropDown__value-container css-1hwfws3" > <div class="DropDown__placeholder css-1wa3eu0-placeholder" > Company Size </div> <div class="css-1ed09z3-Input" > <div class="DropDown__input" style="display: inline-block;" > <input aria-autocomplete="list" autocapitalize="none" autocomplete="off" autocorrect="off" id="react-select-2-input" spellcheck="false" style="box-sizing: content-box; width: 2px; border: 0px; opacity: 1; outline: 0; padding: 0px;" tabindex="0" type="text" value="" /> <div style="position: absolute; top: 0px; left: 0px; visibility: hidden; height: 0px; overflow: scroll; white-space: pre; font-family: -webkit-small-control; letter-spacing: normal; text-transform: none;" /> </div> </div> </div> <div class="DropdownInput__indicatorsContainer" > <div class="DropDown__indicators css-1hb7zxy-IndicatorsContainer" > <i class="icon icon-chevron-down" /> </div> </div> </div> </div> </div> </div> </fieldset> </div> <div class="countries-section" > <div class="DropdownInput Input_container" data-testid="CountrySelector" > <fieldset class="Input_fieldset" > <legend class="Input_legend" /> <div class="Input_wrapper" > <div class="Input css-2b097c-container" id="DropdownInput_country_dropdown" > <div class="DropdownInput__controlContainer" > <div class="DropDown__control css-1nr98fh-control" > <div class="DropDown__value-container css-1hwfws3" > <div class="DropDown__placeholder css-1wa3eu0-placeholder" > Country </div> <div class="css-1ed09z3-Input" > <div class="DropDown__input" style="display: inline-block;" > <input aria-autocomplete="list" autocapitalize="none" autocomplete="off" autocorrect="off" id="react-select-3-input" spellcheck="false" style="box-sizing: content-box; width: 2px; border: 0px; opacity: 1; outline: 0; padding: 0px;" tabindex="0" type="text" value="" /> <div style="position: absolute; top: 0px; left: 0px; visibility: hidden; height: 0px; overflow: scroll; white-space: pre; font-family: -webkit-small-control; letter-spacing: normal; text-transform: none;" /> </div> </div> </div> <div class="DropdownInput__indicatorsContainer" > <div class="DropDown__indicators css-1hb7zxy-IndicatorsContainer" > <i class="icon icon-chevron-down" /> </div> </div> </div> </div> </div> </div> </fieldset> </div> </div> <div class="disclaimer" > By selecting Start trial, I agree to the <a href="https://mattermost.com/software-evaluation-agreement/?utm_source=mattermost&utm_medium=in-product&utm_content=start_trial_form_modal&uid=user1&sid=test123" location="start_trial_form_modal" rel="noopener noreferrer" target="_blank" > Mattermost Software Evaluation Agreement </a> , <a href="https://mattermost.com/pl/privacy-policy/?utm_source=mattermost&utm_medium=in-product&utm_content=start_trial_form_modal&uid=user1&sid=test123" location="start_trial_form_modal" rel="noopener noreferrer" target="_blank" > Privacy Policy </a> , and receiving product emails. </div> <div class="buttons" > <button class="confirm-btn btn btn-default" disabled="" type="button" > Start trial </button> </div> </div> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `;
3,216
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/status_dropdown/status_dropdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {CustomStatusDuration} from '@mattermost/types/users'; import type {UserProfile} from '@mattermost/types/users'; import {fakeDate} from 'tests/helpers/date'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import StatusDropdown from './status_dropdown'; describe('components/StatusDropdown', () => { let resetFakeDate: () => void; beforeEach(() => { resetFakeDate = fakeDate(new Date('2021-11-02T22:48:57Z')); }); afterEach(() => { resetFakeDate(); }); const actions = { openModal: jest.fn(), setStatus: jest.fn(), unsetCustomStatus: jest.fn(), setStatusDropdown: jest.fn(), savePreferences: jest.fn(), }; const baseProps = { actions, userId: '', currentUser: { id: 'user_id', first_name: 'Nev', last_name: 'Aa', } as UserProfile, userTimezone: { useAutomaticTimezone: 'true', automaticTimezone: 'America/New_York', manualTimezone: '', }, status: 'away', isMilitaryTime: false, isCustomStatusEnabled: false, isCustomStatusExpired: false, isStatusDropdownOpen: false, showCustomStatusPulsatingDot: false, showCompleteYourProfileTour: false, }; test('should match snapshot in default state', () => { const wrapper = shallowWithIntl( <StatusDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with profile picture URL', () => { const props = { ...baseProps, profilePicture: 'http://localhost:8065/api/v4/users/jsx5jmdiyjyuzp9rzwfaf5pwjo/image?_=1590519110944', }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with status dropdown open', () => { const props = { ...baseProps, isStatusDropdownOpen: true, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with custom status enabled', () => { const props = { ...baseProps, isStatusDropdownOpen: true, isCustomStatusEnabled: true, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with custom status pulsating dot enabled', () => { const props = { ...baseProps, isStatusDropdownOpen: true, isCustomStatusEnabled: true, showCustomStatusPulsatingDot: true, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with custom status and expiry', () => { const customStatus = { emoji: 'calendar', text: 'In a meeting', duration: CustomStatusDuration.TODAY, expires_at: '2021-05-03T23:59:59.000Z', }; const props = { ...baseProps, isStatusDropdownOpen: true, isCustomStatusEnabled: true, customStatus, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with custom status expired', () => { const customStatus = { emoji: 'calendar', text: 'In a meeting', duration: CustomStatusDuration.TODAY, expires_at: '2021-05-03T23:59:59.000Z', }; const props = { ...baseProps, isStatusDropdownOpen: true, isCustomStatusEnabled: true, isCustomStatusExpired: true, customStatus, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should show clear status button when custom status is set', () => { const customStatus = { emoji: 'calendar', text: 'In a meeting', duration: CustomStatusDuration.TODAY, expires_at: '2021-05-03T23:59:59.000Z', }; const props = { ...baseProps, isStatusDropdownOpen: true, isCustomStatusEnabled: true, isCustomStatusExpired: false, customStatus, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper.find('.status-dropdown-menu__clear-container').exists()).toBe(true); expect(wrapper).toMatchSnapshot(); }); test('should not show clear status button when custom status is not set', () => { const customStatus = undefined; const props = { ...baseProps, isStatusDropdownOpen: true, isCustomStatusEnabled: true, isCustomStatusExpired: false, customStatus, }; const wrapper = shallowWithIntl( <StatusDropdown {...props}/>, ); expect(wrapper.find('.status-dropdown-menu__clear-container').exists()).toBe(false); expect(wrapper).toMatchSnapshot(); }); });
3,218
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/status_dropdown
petrpan-code/mattermost/mattermost/webapp/channels/src/components/status_dropdown/__snapshots__/status_dropdown.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/StatusDropdown should match snapshot in default state 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header" onToggle={[Function]} open={false} > <button aria-controls="statusDropdownMenu" aria-expanded={false} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should match snapshot with custom status and expiry 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="In a meeting" className="MenuItem__primary-text custom_status__row" dialogType={[Function]} id="status-menu-custom-status" modalId="custom_status" show={true} > <span className="custom_status__container" > <span className="custom_status__icon" > <span className="d-flex" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginLeft": 0, } } showTooltip={false} /> </span> </span> <CustomStatusText className="custom_status__text" text="In a meeting" tooltipDirection="bottom" /> <Text color="disabled" margin="none" /> <div className="status-dropdown-menu__clear-container input-clear visible" onClick={[Function]} onTouchEnd={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="InputClearTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Clear" id="input.clear" /> </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <span aria-hidden="true" className="input-clear-x" > <i className="icon icon-close-circle" /> </span> </OverlayTrigger> </div> </span> <Memo(ExpiryTime) className="custom_status__expiry padded" time="2021-05-03T23:59:59.000Z" withinBrackets={true} /> </MenuItemToggleModalRedux> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should match snapshot with custom status enabled 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Set a Custom Status" className="MenuItem__primary-text custom_status__row" dialogType={[Function]} id="status-menu-custom-status" modalId="custom_status" show={true} > <span className="custom_status__container" > <span className="custom_status__icon" > <Memo(EmojiIcon) className="custom-status-emoji" /> </span> <CustomStatusText className="custom_status__text" text="" tooltipDirection="bottom" /> <Text color="disabled" margin="none" > Set a Custom Status </Text> </span> </MenuItemToggleModalRedux> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should match snapshot with custom status expired 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Set a Custom Status" className="MenuItem__primary-text custom_status__row" dialogType={[Function]} id="status-menu-custom-status" modalId="custom_status" show={true} > <span className="custom_status__container" > <span className="custom_status__icon" > <Memo(EmojiIcon) className="custom-status-emoji" /> </span> <CustomStatusText className="custom_status__text" text="" tooltipDirection="bottom" /> <Text color="disabled" margin="none" > Set a Custom Status </Text> </span> </MenuItemToggleModalRedux> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should match snapshot with custom status pulsating dot enabled 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Set a Custom Status" className="MenuItem__primary-text custom_status__row" dialogType={[Function]} id="status-menu-custom-status" modalId="custom_status" show={true} > <span className="custom_status__container" > <span className="custom_status__icon" > <Memo(EmojiIcon) className="custom-status-emoji" /> </span> <CustomStatusText className="custom_status__text" text="" tooltipDirection="bottom" /> <Text color="disabled" margin="none" > Set a Custom Status </Text> <PulsatingDot /> </span> </MenuItemToggleModalRedux> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should match snapshot with profile picture URL 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header" onToggle={[Function]} open={false} > <button aria-controls="statusDropdownMenu" aria-expanded={false} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <Memo(Avatar) size="sm" url="http://localhost:8065/api/v4/users/jsx5jmdiyjyuzp9rzwfaf5pwjo/image?_=1590519110944" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <Memo(Avatar) size="lg" url="http://localhost:8065/api/v4/users/jsx5jmdiyjyuzp9rzwfaf5pwjo/image?_=1590519110944" /> <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should match snapshot with status dropdown open 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should not show clear status button when custom status is not set 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Set a Custom Status" className="MenuItem__primary-text custom_status__row" dialogType={[Function]} id="status-menu-custom-status" modalId="custom_status" show={true} > <span className="custom_status__container" > <span className="custom_status__icon" > <Memo(EmojiIcon) className="custom-status-emoji" /> </span> <CustomStatusText className="custom_status__text" text="" tooltipDirection="bottom" /> <Text color="disabled" margin="none" > Set a Custom Status </Text> </span> </MenuItemToggleModalRedux> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/StatusDropdown should show clear status button when custom status is set 1`] = ` <MenuWrapper animationComponent={[Function]} className="status-dropdown-menu status-dropdown-menu-global-header active" onToggle={[Function]} open={true} > <button aria-controls="statusDropdownMenu" aria-expanded={true} aria-label="Current status: Away. Select to open profile and status menu." className="status-wrapper style--none" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": "6px", } } onClick={[Function]} showTooltip={true} tooltipDirection="bottom" /> <div className="status" > <StatusIcon size="sm" status="away" /> </div> </button> <Menu ariaLabel="Set a status" id="statusDropdownMenu" listId="status-drop-down-menu-list" > <Memo(MenuHeader) onClick={[Function]} > <div className="username-wrapper" > <Text className="bold" margin="none" > Nev Aa </Text> <Text className="" color="disabled" margin="none" > @undefined </Text> </div> </Memo(MenuHeader)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="out of office" extraText="Automatic Replies are enabled" onClick={[Function]} show={false} text="Out of office" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="In a meeting" className="MenuItem__primary-text custom_status__row" dialogType={[Function]} id="status-menu-custom-status" modalId="custom_status" show={true} > <span className="custom_status__container" > <span className="custom_status__icon" > <span className="d-flex" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginLeft": 0, } } showTooltip={false} /> </span> </span> <CustomStatusText className="custom_status__text" text="In a meeting" tooltipDirection="bottom" /> <Text color="disabled" margin="none" /> <div className="status-dropdown-menu__clear-container input-clear visible" onClick={[Function]} onTouchEnd={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="InputClearTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Clear" id="input.clear" /> </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <span aria-hidden="true" className="input-clear-x" > <i className="icon icon-close-circle" /> </span> </OverlayTrigger> </div> </span> <Memo(ExpiryTime) className="custom_status__expiry padded" time="2021-05-03T23:59:59.000Z" withinBrackets={true} /> </MenuItemToggleModalRedux> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction ariaLabel="online" icon={ <StatusIcon className="status-icon" status="online" /> } id="status-menu-online" onClick={[Function]} rightDecorator={false} show={true} text="Online" /> <MenuItemAction ariaLabel="away" icon={ <StatusIcon className="status-icon" status="away" /> } id="status-menu-away" onClick={[Function]} rightDecorator={ <CheckIcon color="var(--semantic-color-success)" size={16} /> } show={true} text="Away" /> <SubMenuItem ariaLabel="do not disturb. disables desktop, email and push notifications" direction="left" extraText="Disables all notifications" icon={ <StatusIcon className="status-icon" status="dnd" /> } id="status-menu-dnd" openUp={false} renderSelected={true} rightDecorator={false} show={true} subMenu={ Array [ Object { "direction": "right", "id": "dndSubMenu-header", "isHeader": true, "text": "Disable notifications until:", }, Object { "action": [Function], "direction": "right", "id": "dndTime-thirty_minutes", "text": "30 mins", }, Object { "action": [Function], "direction": "right", "id": "dndTime-one_hour", "text": "1 hour", }, Object { "action": [Function], "direction": "right", "id": "dndTime-two_hours", "text": "2 hours", }, Object { "action": [Function], "direction": "right", "id": "dndTime-tomorrow", "text": <React.Fragment> Tomorrow <span className="dndTime-tomorrow_timestamp" > <FormattedDate value={2021-11-03T22:48:57.000Z} weekday="short" /> , <FormattedTime hour12={true} timeStyle="short" value={2021-11-03T22:48:57.000Z} /> </span> </React.Fragment>, }, Object { "action": [Function], "direction": "right", "id": "dndTime-custom", "text": "Custom", }, ] } subMenuClass="pl-4" text="Do not disturb" /> <MenuItemAction ariaLabel="offline" icon={ <StatusIcon className="status-icon" status="offline" /> } id="status-menu-offline" onClick={[Function]} rightDecorator={false} show={true} text="Offline" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux ariaLabel="Profile" dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <AccountOutlineIcon size={16} /> } id="accountSettings" modalId="user_settings" show={true} text="Profile" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <ExitToAppIcon size={16} /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `;
3,219
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/channel_mention_provider.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. jest.mock('mattermost-redux/selectors/entities/channels', () => ({ getMyChannels: jest.fn(() => []), getMyChannelMemberships: jest.fn(() => {}), })); jest.mock('stores/redux_store'); import ChannelMentionProvider from './channel_mention_provider'; describe('ChannelMentionProvider.handlePretextChanged', () => { const autocompleteChannels = jest.fn(); const resultsCallback = jest.fn(); let provider: ChannelMentionProvider; beforeEach(() => { provider = new ChannelMentionProvider(autocompleteChannels, false); }); describe('basic cases', () => { test('should not match empty string', () => { const matched = provider.handlePretextChanged('', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); test('should not match plain text', () => { const matched = provider.handlePretextChanged('this is a test', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); test('should match a partial channel\'s name', () => { const matched = provider.handlePretextChanged('~town-sq', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town-sq', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('should match a channel\'s name', () => { const matched = provider.handlePretextChanged('~town-square', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town-square', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('should match a channel\'s partial display name', () => { const matched = provider.handlePretextChanged('~Town Sq', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town sq', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('should match a channel\'s display name', () => { const matched = provider.handlePretextChanged('~Town Square', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town square', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('should match part of the text', () => { const matched = provider.handlePretextChanged('this is ~town-squ', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town-squ', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('should only match at the end of the text', () => { const matched = provider.handlePretextChanged('this is ~town-square, not ~off-topic', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('off-topic', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('should lower case search term', () => { const matched = provider.handlePretextChanged('this is ~town SQUARE ', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town square ', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); }); describe('strikethrough text', () => { test('should not match the start of strikethrough text', () => { const matched = provider.handlePretextChanged('~~', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); test('should not match the middle of strikethrough text', () => { const matched = provider.handlePretextChanged('~~town square', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); test('should not match the end of strikethrough text', () => { const matched = provider.handlePretextChanged('~~this is a test~~', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); }); describe('matching text after completing a result', () => { test('should not continue to match a link that was just completed', () => { provider.handleCompleteWord('~town-square'); const matched = provider.handlePretextChanged('This is ~town-square', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); test('should not continue to match a link that was completed, even after typing more text', () => { provider.handleCompleteWord('~town-square'); const matched = provider.handlePretextChanged('This is ~town-square and a test', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); }); test('should start matching input again after another link is started', () => { provider.handleCompleteWord('~town-square'); const matched = provider.handlePretextChanged('This is ~town-square and not ~off', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('off', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); }); test('should not continue to match after receiving no results until another possible link starts', () => { autocompleteChannels.mockImplementationOnce((prefix, success) => { success([]); }); let matched = provider.handlePretextChanged('This is ~no-results', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('no-results', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalledTimes(2); autocompleteChannels.mockReset(); resultsCallback.mockReset(); matched = provider.handlePretextChanged('This is ~no-results in a test', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); matched = provider.handlePretextChanged('This is ~no-results in a test using ~town', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('town', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); describe('delayed autocomplete', () => { test('with the setting enabled, should not match a link shorter than the minimum length', () => { provider.setProps({delayChannelAutocomplete: true}); let matched = provider.handlePretextChanged('~', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); matched = provider.handlePretextChanged('~t', resultsCallback); expect(matched).toBe(false); expect(autocompleteChannels).not.toHaveBeenCalled(); expect(resultsCallback).not.toHaveBeenCalled(); matched = provider.handlePretextChanged('~to', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('to', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); test('with the setting disabled, should match a link shorter than the minimum length', () => { provider.setProps({delayChannelAutocomplete: false}); const matched = provider.handlePretextChanged('~', resultsCallback); expect(matched).toBe(true); expect(autocompleteChannels).toHaveBeenCalledWith('', expect.anything(), expect.anything()); expect(resultsCallback).toHaveBeenCalled(); }); }); });
3,230
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/search_channel_with_permissions_provider.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import store from 'stores/redux_store'; import mockStore from 'tests/test_store'; import SearchChannelWithPermissionsProvider from './search_channel_with_permissions_provider'; const getState = store.getState; jest.mock('stores/redux_store', () => ({ dispatch: jest.fn(), getState: jest.fn(), })); describe('components/SearchChannelWithPermissionsProvider', () => { const defaultState = { entities: { general: { config: {}, }, teams: { currentTeamId: 'someTeamId', myMembers: { someTeamId: { roles: '', }, }, }, channels: { myMembers: { somePublicMemberChannelId: { }, somePrivateMemberChannelId: { }, someDirectConversation: { }, someGroupConversation: { }, }, roles: { somePublicMemberChannelId: [], somePrivateMemberChannelId: [], someDirectConversation: [], someGroupConversation: [], }, channels: { somePublicMemberChannelId: { id: 'somePublicMemberChannelId', type: 'O', name: 'some-public-member-channel', display_name: 'Some Public Member Channel', delete_at: 0, }, somePrivateMemberChannelId: { id: 'somePrivateMemberChannelId', type: 'P', name: 'some-private-member-channel', display_name: 'Some Private Member Channel', delete_at: 0, }, somePublicNonMemberChannelId: { id: 'somePublicNonMemberChannelId', type: 'O', name: 'some-public-non-member-channel', display_name: 'Some Public Non-Member Channel', delete_at: 0, }, somePrivateNonMemberChannelId: { id: 'somePrivateNonMemberChannelId', type: 'P', name: 'some-private=non-member-channel', display_name: 'Some Private Non-Member Channel', delete_at: 0, }, someDirectConversation: { id: 'someDirectConversation', type: 'D', name: 'some-direct-conversation', display_name: 'Some Direct Conversation', delete_at: 0, }, someGroupConversation: { id: 'someGroupConversation', type: 'GM', name: 'some-group-conversation', display_name: 'Some Group Conversation', delete_at: 0, }, }, channelsInTeam: { someTeamId: [ 'somePublicMemberChannelId', 'somePrivateMemberChannelId', 'somePublicNonMemberChannelId', 'somePrivateNonMemberChannelId', 'someDirectConversation', 'someGroupConversation', ], }, }, roles: { roles: { public_channels_manager: { permissions: ['manage_public_channel_members'], }, private_channels_manager: { permissions: ['manage_private_channel_members'], }, }, }, users: { profiles: {}, }, }, }; let searchProvider: SearchChannelWithPermissionsProvider; beforeEach(() => { const channelSearchFunc = jest.fn(); searchProvider = new SearchChannelWithPermissionsProvider(channelSearchFunc); }); it('should show public channels if user has public channel manage permission', () => { const roles = 'public_channels_manager'; const resultsCallback = jest.fn(); const state = { ...defaultState, entities: { ...defaultState.entities, teams: { currentTeamId: 'someTeamId', myMembers: { someTeamId: { roles, }, }, }, }, }; const store = mockStore(state); getState.mockImplementation(store.getState); const searchText = 'some'; searchProvider.handlePretextChanged(searchText, resultsCallback); expect(resultsCallback).toHaveBeenCalled(); const args = resultsCallback.mock.calls[0][0]; expect(args.items[0].channel.id).toEqual('somePublicMemberChannelId'); expect(args.items.length).toEqual(1); }); it('should show private channels if user has private channel manage permission', () => { const roles = 'private_channels_manager'; const resultsCallback = jest.fn(); const state = { ...defaultState, entities: { ...defaultState.entities, teams: { currentTeamId: 'someTeamId', myMembers: { someTeamId: { roles, }, }, }, }, }; const store = mockStore(state); getState.mockImplementation(store.getState); const searchText = 'some'; searchProvider.handlePretextChanged(searchText, resultsCallback); expect(resultsCallback).toHaveBeenCalled(); const args = resultsCallback.mock.calls[0][0]; expect(args.items[0].channel.id).toEqual('somePrivateMemberChannelId'); expect(args.items.length).toEqual(1); }); it('should show both public and private channels if user has public and private channel manage permission', () => { const roles = 'public_channels_manager private_channels_manager'; const resultsCallback = jest.fn(); const state = { ...defaultState, entities: { ...defaultState.entities, teams: { currentTeamId: 'someTeamId', myMembers: { someTeamId: { roles, }, }, }, }, }; const store = mockStore(state); getState.mockImplementation(store.getState); const searchText = 'some'; searchProvider.handlePretextChanged(searchText, resultsCallback); expect(resultsCallback).toHaveBeenCalled(); const args = resultsCallback.mock.calls[0][0]; expect(args.items[0].channel.id).toEqual('somePublicMemberChannelId'); expect(args.items[1].channel.id).toEqual('somePrivateMemberChannelId'); expect(args.items.length).toEqual(2); }); it('should show nothing if the user does not have permissions to manage channels', () => { const roles = ''; const resultsCallback = jest.fn(); const state = { ...defaultState, entities: { ...defaultState.entities, teams: { currentTeamId: 'someTeamId', myMembers: { someTeamId: { roles, }, }, }, }, }; const store = mockStore(state); getState.mockImplementation(store.getState); const searchText = 'some'; searchProvider.handlePretextChanged(searchText, resultsCallback); expect(resultsCallback).toHaveBeenCalled(); const args = resultsCallback.mock.calls[0][0]; expect(args.items.length).toEqual(0); }); it('should show nothing if the search does not match', () => { const roles = 'public_channels_manager private_channels_manager'; const resultsCallback = jest.fn(); const state = { ...defaultState, entities: { ...defaultState.entities, teams: { currentTeamId: 'someTeamId', myMembers: { someTeamId: { roles, }, }, }, }, }; const store = mockStore(state); getState.mockImplementation(store.getState); const searchText = 'not matching text'; searchProvider.handlePretextChanged(searchText, resultsCallback); expect(resultsCallback).toHaveBeenCalled(); const args = resultsCallback.mock.calls[0][0]; expect(args.items.length).toEqual(0); }); });
3,233
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/search_suggestion_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 SearchSuggestionList from 'components/suggestion/search_suggestion_list'; import {TestHelper} from 'utils/test_helper'; describe('components/SearchSuggestionList', () => { const baseProps = { open: true, onCompleteWord: jest.fn(), pretext: '', cleared: false, matchedPretext: [], items: [], terms: [], selection: '', components: [], onItemHover: jest.fn(), }; test('should not throw error when currentLabel is null and label is generated', () => { const userProfile = TestHelper.getUserMock(); const item = { ...userProfile, type: 'item_type', display_name: 'item_display_name', name: 'item_name', }; const wrapper = shallow( <SearchSuggestionList {...baseProps} ariaLiveRef={React.createRef()} />, ); const instance = wrapper.instance() as SearchSuggestionList; instance.currentLabel = null as any; instance.generateLabel(item); }); });
3,238
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/suggestion_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 SuggestionList from 'components/suggestion/suggestion_list'; describe('components/SuggestionList', () => { const baseProps = { open: true, onCompleteWord: jest.fn(), pretext: '', cleared: false, matchedPretext: [], items: [], terms: [], selection: '', components: [], onItemHover: jest.fn(), }; test('should not throw error when currentLabel is null and label is generated', () => { const wrapper = shallow<SuggestionList>( <SuggestionList {...baseProps} ariaLiveRef={React.createRef()} />, ); const instance = wrapper.instance(); instance.currentLabel = null; instance.generateLabel({}); }); });
3,240
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/switch_channel_provider.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {UserProfile} from '@mattermost/types/users'; import {Preferences} from 'mattermost-redux/constants'; import Store from 'stores/redux_store'; import mockStore from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; import SwitchChannelProvider from './switch_channel_provider'; const getState = Store.getState; const latestPost = TestHelper.getPostMock({ id: 'latest_post_id', user_id: 'current_user_id', message: 'test msg', channel_id: 'other_gm_channel', create_at: Date.now(), }); jest.mock('stores/redux_store', () => ({ dispatch: jest.fn(), getState: jest.fn(), })); jest.mock('mattermost-redux/client', () => { const original = jest.requireActual('mattermost-redux/client'); return { ...original, Client4: { ...original.Client4, autocompleteUsers: jest.fn().mockResolvedValue([]), }, }; }); jest.mock('mattermost-redux/actions/channels', () => ({ ...jest.requireActual('mattermost-redux/actions/channels'), searchAllChannels: () => jest.fn().mockResolvedValue(Promise.resolve({ data: [{ id: 'channel_other_user1', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, team_id: 'currentTeamId', }, ], })), })); describe('components/SwitchChannelProvider', () => { const defaultState = { entities: { general: { config: {}, }, channels: { myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', }, direct_other_user: { channel_id: 'direct_other_user', user_id: 'current_user_id', roles: 'channel_role', last_viewed_at: 10, }, channel_other_user: { channel_id: 'channel_other_user', }, }, channels: { direct_other_user: { id: 'direct_other_user', name: 'current_user_id__other_user', }, }, messageCounts: { direct_other_user: { root: 2, total: 2, }, }, }, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, 'group_channel_show--other_gm_channel': { category: 'group_channel_show', value: 'true', name: 'other_gm_channel', user_id: 'current_user_id', }, }, }, users: { profiles: { current_user_id: {roles: 'system_role'}, other_user1: { id: 'other_user1', display_name: 'other_user1', username: 'other_user1', }, }, currentUserId: 'current_user_id', profilesInChannel: { current_user_id: ['user_1'], }, }, teams: { currentTeamId: 'currentTeamId', teams: { currentTeamId: { id: 'currentTeamId', display_name: 'test', type: 'O', delete_at: 0, }, }, }, posts: { posts: { [latestPost.id]: latestPost, }, postsInChannel: { other_gm_channel: [ {order: [latestPost.id], recent: true}, ], }, postsInThread: {}, }, }, }; it('should change name on wrapper to be unique with same name user channel and public channel', () => { const switchProvider = new SwitchChannelProvider(); const store = mockStore(defaultState); getState.mockImplementation(store.getState); const users = [ TestHelper.getUserMock({ id: 'other_user', username: 'other_user', }), ]; const channels = [{ id: 'channel_other_user', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, }, { id: 'direct_other_user', type: 'D', name: 'current_user_id__other_user', display_name: 'other_user', delete_at: 0, }]; const searchText = 'other'; switchProvider.startNewRequest(''); const result = switchProvider.formatList(searchText, channels, users); const set = new Set(result.terms); expect(set.size).toEqual(result.items.length); const set2 = new Set(result.items.map((o) => { if ('channel' in o) { return o.channel.name; } return null; })); expect(set2.size).toEqual(1); expect(result.items.length).toEqual(2); }); it('should change name on wrapper to be unique with same name user in channel and public channel', () => { const switchProvider = new SwitchChannelProvider(); const store = mockStore(defaultState); getState.mockImplementation(store.getState); const users = [ TestHelper.getUserMock({ id: 'other_user', username: 'other_user', })]; const channels = [{ id: 'channel_other_user', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, }]; const searchText = 'other'; switchProvider.startNewRequest(''); const result = switchProvider.formatList(searchText, channels, users); const set = new Set(result.terms); expect(set.size).toEqual(result.items.length); const set2 = new Set(result.items.map((o) => { if ('channel' in o) { return o.channel.name; } return null; })); expect(set2.size).toEqual(1); expect(result.items.length).toEqual(2); }); it('should not fail if nothing matches', () => { const switchProvider = new SwitchChannelProvider(); const store = mockStore(defaultState); getState.mockImplementation(store.getState); const users: UserProfile[] = []; const channels = [{ id: 'channel_other_user', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, }, { id: 'direct_other_user', type: 'D', name: 'current_user_id__other_user', display_name: 'other_user', delete_at: 0, }]; const searchText = 'something else'; switchProvider.startNewRequest(''); const results = switchProvider.formatList(searchText, channels, users); expect(results.terms.length).toEqual(0); expect(results.items.length).toEqual(0); }); it('should correctly format the display name depending on the preferences', () => { const switchProvider = new SwitchChannelProvider(); const user = TestHelper.getUserMock({ id: 'id', username: 'username', first_name: 'fn', last_name: 'ln', }); const channel = TestHelper.getChannelMock({ id: 'channel_id', }); let res = switchProvider.userWrappedChannel(user, channel); expect(res.channel.display_name).toEqual('fn ln'); getState.mockClear(); const store = mockStore({ entities: { general: { config: {}, }, channels: { myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, }, }, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'full_name', }, }, }, users: { profiles: { current_user_id: {roles: 'system_role'}, }, currentUserId: 'current_user_id', profilesInChannel: { current_user_id: ['user_1'], }, }, }, }); getState.mockImplementation(store.getState); res = switchProvider.userWrappedChannel(user, channel); expect(res.channel.display_name).toEqual('fn ln'); }); it('should sort results in aplhabetical order', () => { const channels = [{ id: 'channel_other_user', type: 'O', name: 'blah_other_user', display_name: 'blah_other_user', delete_at: 0, }, { id: 'direct_other_user1', type: 'D', name: 'current_user_id__other_user1', display_name: 'other_user1', delete_at: 0, }, { id: 'direct_other_user2', type: 'D', name: 'current_user_id__other_user2', display_name: 'other_user2', delete_at: 0, }]; const users = [ TestHelper.getUserMock({ id: 'other_user2', username: 'other_user2', }), TestHelper.getUserMock({ id: 'other_user1', username: 'other_user1', }), ]; const modifiedState = { ...defaultState, entities: { ...defaultState.entities, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, channel_other_user: {}, direct_other_user1: {}, direct_other_user2: {}, }, }, }, }; const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const searchText = 'other'; switchProvider.startNewRequest(''); const results = switchProvider.formatList(searchText, channels, users); const expectedOrder = [ 'other_user1', 'other_user2', 'channel_other_user', ]; expect(results.terms).toEqual(expectedOrder); }); it('should sort results based on last_viewed_at order followed by alphabetical andomit users not in members', () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, last_viewed_at: 1, }, direct_other_user1: { channel_id: 'direct_other_user1', msg_count: 1, last_viewed_at: 2, }, direct_other_user4: { channel_id: 'direct_other_user4', msg_count: 1, last_viewed_at: 3, }, channel_other_user: {}, }, }, }, }; const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const users = [ TestHelper.getUserMock({ id: 'other_user1', username: 'other_user1', }), TestHelper.getUserMock({ id: 'other_user2', username: 'other_user2', }), TestHelper.getUserMock({ id: 'other_user3', username: 'other_user3', }), TestHelper.getUserMock({ id: 'other_user4', username: 'other_user4', }), ]; const channels = [{ id: 'channel_other_user', type: 'O', name: 'blah_other_user', display_name: 'blah_other_user', delete_at: 0, }, { id: 'direct_other_user1', type: 'D', name: 'current_user_id__other_user1', display_name: 'other_user1', delete_at: 0, }, { id: 'direct_other_user2', type: 'D', name: 'current_user_id__other_user2', display_name: 'other_user2', delete_at: 0, }, { id: 'direct_other_user4', type: 'D', name: 'current_user_id__other_user4', display_name: 'other_user4', delete_at: 0, }]; const searchText = 'other'; switchProvider.startNewRequest(''); const results = switchProvider.formatList(searchText, channels, users); const expectedOrder = [ 'other_user4', 'other_user1', 'channel_other_user', ]; expect(results.terms).toEqual(expectedOrder); }); it('should start with GM before channels and DM"s with last_viewed_at', async () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, other_gm_channel: { channel_id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, }, other_user1: {}, }, channels: { channel_other_user: { id: 'channel_other_user', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, team_id: 'currentTeamId', }, other_gm_channel: { id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, type: 'G', name: 'other_gm_channel', delete_at: 0, display_name: 'other_gm_channel', }, other_user1: { id: 'other_user1', type: 'D', name: 'current_user_id__other_user1', display_name: 'current_user_id__other_user1', }, }, }, }, }; getState.mockClear(); const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const searchText = 'other'; const resultsCallback = jest.fn(); switchProvider.startNewRequest(''); await switchProvider.fetchUsersAndChannels(searchText, resultsCallback); const expectedOrder = [ 'other_gm_channel', 'other_user1', 'channel_other_user1', ]; expect(resultsCallback).toBeCalledWith(expect.objectContaining({ terms: expectedOrder, })); }); it('should start with DM (user name with dot) before GM"s if both DM & GM have last_viewed_at irrespective of value of last_viewed_at', async () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, other_gm_channel: { channel_id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, }, other_user1: { last_viewed_at: 4, }, }, channels: { channel_other_user: { id: 'channel_other_user', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, team_id: 'currentTeamId', }, other_gm_channel: { id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, type: 'G', name: 'other_gm_channel', delete_at: 0, display_name: 'other.user1, other.user2', }, other_user1: { id: 'other_user1', type: 'D', name: 'current_user_id__other_user1', display_name: 'other user1', }, }, }, users: { profiles: { current_user_id: {roles: 'system_role'}, other_user1: { id: 'other_user1', display_name: 'other user1', username: 'other.user1', }, }, currentUserId: 'current_user_id', profilesInChannel: { current_user_id: ['user_1'], }, }, }, }; getState.mockClear(); const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const searchText = 'other.'; const resultsCallback = jest.fn(); switchProvider.startNewRequest(''); await switchProvider.fetchUsersAndChannels(searchText, resultsCallback); const expectedOrder = [ 'other_user1', 'other_gm_channel', ]; expect(resultsCallback).toBeCalledWith(expect.objectContaining({ terms: expectedOrder, })); }); it('GM should not be first result as it is hidden in LHS', async () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, preferences: { ...defaultState.entities.preferences, myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, 'group_channel_show--other_gm_channel': { category: 'group_channel_show', value: 'false', name: 'other_gm_channel', user_id: 'current_user_id', }, }, }, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, other_gm_channel: { channel_id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, }, other_user1: {}, }, channels: { channel_other_user: { id: 'channel_other_user', type: 'O', name: 'other_user', display_name: 'other_user', delete_at: 0, team_id: 'currentTeamId', }, other_gm_channel: { id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, type: 'G', name: 'other_gm_channel', delete_at: 0, display_name: 'other_gm_channel', }, other_user1: { id: 'other_user1', type: 'D', name: 'current_user_id__other_user1', display_name: 'current_user_id__other_user1', }, }, channelsInTeam: { '': ['other_gm_channel'], }, }, }, }; getState.mockClear(); const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const searchText = 'other'; const resultsCallback = jest.fn(); switchProvider.startNewRequest(''); await switchProvider.fetchUsersAndChannels(searchText, resultsCallback); const expectedOrder = [ 'other_user1', 'other_gm_channel', 'channel_other_user1', ]; expect(resultsCallback).toBeCalledWith(expect.objectContaining({ terms: expectedOrder, })); }); it('Should match GM even with space in search term', () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, last_viewed_at: 1, }, direct_other_user1: { channel_id: 'direct_other_user1', msg_count: 1, last_viewed_at: 2, }, other_gm_channel: { channel_id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, }, }, channels: { other_gm_channel: { id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, type: 'G', name: 'other_gm_channel', delete_at: 0, display_name: 'other_gm_channel', }, other_user1: { id: 'other_user1', type: 'D', name: 'current_user_id__other_user1', display_name: 'current_user_id__other_user1', }, }, channelsInTeam: { '': ['other_gm_channel'], }, }, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, 'group_channel_show--other_gm_channel': { category: 'group_channel_show', value: 'true', name: 'other_gm_channel', user_id: 'current_user_id', }, }, }, }, }; const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const users = [ TestHelper.getUserMock({ id: 'other_user1', username: 'other_user1', }), ]; const channels = [{ id: 'other_gm_channel', msg_count: 1, last_viewed_at: 3, type: 'G', name: 'other_gm_channel', delete_at: 0, display_name: 'other_user1, current_user_id', }]; const searchText = 'other current'; switchProvider.startNewRequest(''); const results = switchProvider.formatList(searchText, channels, users); const expectedOrder = [ 'other_gm_channel', ]; expect(results.terms).toEqual(expectedOrder); }); it('should filter out channels belonging to archived teams', async () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, channels: { ...defaultState.entities.channels, myMembers: { channel_1: {}, channel_2: {}, }, channels: { channel_1: { id: 'channel_1', type: 'O', name: 'channel_1', display_name: 'channel 1', delete_at: 0, team_id: 'currentTeamId', }, channel_2: { id: 'channel_2', type: 'O', name: 'channel_2', display_name: 'channel 2', delete_at: 0, team_id: 'archivedTeam', }, }, }, }, }; getState.mockClear(); const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const searchText = 'chan'; const resultsCallback = jest.fn(); switchProvider.startNewRequest(''); await switchProvider.fetchUsersAndChannels(searchText, resultsCallback); const channelsFromActiveTeams = [ 'channel_1', ]; expect(resultsCallback).toBeCalledWith(expect.objectContaining({ terms: channelsFromActiveTeams, })); }); it('Should show threads as the first item in the list if search term matches', async () => { const modifiedState = { ...defaultState, entities: { ...defaultState.entities, general: { config: { CollapsedThreads: 'default_off', }, }, threads: { countsIncludingDirect: { currentTeamId: { total: 0, total_unread_threads: 0, total_unread_mentions: 0, }, }, counts: { currentTeamId: { total: 0, total_unread_threads: 0, total_unread_mentions: 0, }, }, }, preferences: { ...defaultState.entities.preferences, myPreferences: { ...defaultState.entities.preferences.myPreferences, [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.COLLAPSED_REPLY_THREADS}`]: { value: 'on', }, }, }, channels: { ...defaultState.entities.channels, myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, thread_gm_channel: { channel_id: 'thread_gm_channel', msg_count: 1, last_viewed_at: 3, }, thread_user1: {}, }, channels: { thread_gm_channel: { id: 'thread_gm_channel', msg_count: 1, last_viewed_at: 3, type: 'G', name: 'thread_gm_channel', delete_at: 0, display_name: 'thread_gm_channel', }, }, channelsInTeam: { '': ['thread_gm_channel'], }, }, }, }; getState.mockClear(); const switchProvider = new SwitchChannelProvider(); const store = mockStore(modifiedState); getState.mockImplementation(store.getState); const searchText = 'thread'; const resultsCallback = jest.fn(); switchProvider.startNewRequest(searchText); await switchProvider.fetchUsersAndChannels(searchText, resultsCallback); const expectedOrder = [ 'threads', 'thread_gm_channel', ]; expect(resultsCallback).toBeCalledWith(expect.objectContaining({ terms: expectedOrder, })); }); });
3,244
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/at_mention_provider/at_mention_suggestion.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import * as Utils from 'utils/utils'; import AtMentionSuggestion from './at_mention_suggestion'; import type {Item} from './at_mention_suggestion'; jest.mock('components/custom_status/custom_status_emoji', () => () => <div/>); jest.spyOn(Utils, 'getFullName').mockReturnValue('a b'); describe('at mention suggestion', () => { const userid1 = { id: 'userid1', username: 'user', first_name: 'a', last_name: 'b', nickname: 'c', isCurrentUser: true, } as Item; const userid2 = { id: 'userid2', username: 'user2', first_name: 'a', last_name: 'b', nickname: 'c', } as Item; const baseProps = { matchedPretext: '@', term: '@user', isSelection: false, onClick: jest.fn(), onMouseMove: jest.fn(), }; it('Should not display nick name of the signed in user', () => { const wrapper = mountWithIntl( <AtMentionSuggestion {...baseProps} item={userid1} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.suggestion-list__ellipsis').text()).toContain('a b'); expect(wrapper.find('.suggestion-list__ellipsis').text()).not.toContain('a b (c)'); }); it('Should display nick name of non signed in user', () => { const wrapper = mountWithIntl( <AtMentionSuggestion {...baseProps} item={userid2} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.suggestion-list__ellipsis').text()).toContain('a b (c)'); }); });
3,247
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/at_mention_provider
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/at_mention_provider/__snapshots__/at_mention_suggestion.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`at mention suggestion Should display nick name of non signed in user 1`] = ` <AtMentionSuggestion isSelection={false} item={ Object { "first_name": "a", "id": "userid2", "last_name": "b", "nickname": "c", "username": "user2", } } matchedPretext="@" onClick={[MockFunction]} onMouseMove={[MockFunction]} term="@user" > <SuggestionContainer data-testid="mentionSuggestion_user2" isSelection={false} item={ Object { "first_name": "a", "id": "userid2", "last_name": "b", "nickname": "c", "username": "user2", } } matchedPretext="@" onClick={[MockFunction]} onMouseMove={[MockFunction]} term="@user" > <div className="suggestion-list__item" data-testid="mentionSuggestion_user2" onClick={[Function]} onMouseMove={[Function]} role="button" tabIndex={-1} > <span className="status-wrapper style--none" > <span className="profile-icon" > <Memo(Avatar) size="sm" url="/api/v4/users/userid2/image?_=0" username="user2" > <img alt="user2 profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/userid2/image?_=0" tabIndex={0} /> </Memo(Avatar)> </span> <StatusIcon button={false} className="" /> </span> <span className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > @user2 </span> <span> a b (c) </span> <Component emojiSize={15} emojiStyle={ Object { "margin": "0 4px 4px", } } showTooltip={true} userID="userid2" > <div /> </Component> </span> </div> </SuggestionContainer> </AtMentionSuggestion> `; exports[`at mention suggestion Should not display nick name of the signed in user 1`] = ` <AtMentionSuggestion isSelection={false} item={ Object { "first_name": "a", "id": "userid1", "isCurrentUser": true, "last_name": "b", "nickname": "c", "username": "user", } } matchedPretext="@" onClick={[MockFunction]} onMouseMove={[MockFunction]} term="@user" > <SuggestionContainer data-testid="mentionSuggestion_user" isSelection={false} item={ Object { "first_name": "a", "id": "userid1", "isCurrentUser": true, "last_name": "b", "nickname": "c", "username": "user", } } matchedPretext="@" onClick={[MockFunction]} onMouseMove={[MockFunction]} term="@user" > <div className="suggestion-list__item" data-testid="mentionSuggestion_user" onClick={[Function]} onMouseMove={[Function]} role="button" tabIndex={-1} > <span className="status-wrapper style--none" > <span className="profile-icon" > <Memo(Avatar) size="sm" url="/api/v4/users/userid1/image?_=0" username="user" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/userid1/image?_=0" tabIndex={0} /> </Memo(Avatar)> </span> <StatusIcon button={false} className="" /> </span> <span className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > @user </span> <span> a b </span> <FormattedMessage defaultMessage="(you)" id="suggestion.user.isCurrent" > <span> (you) </span> </FormattedMessage> <Component emojiSize={15} emojiStyle={ Object { "margin": "0 4px 4px", } } showTooltip={true} userID="userid1" > <div /> </Component> </span> </div> </SuggestionContainer> </AtMentionSuggestion> `;
3,249
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/command_provider/command_provider.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 {AutocompleteSuggestion} from '@mattermost/types/integrations'; import {Client4} from 'mattermost-redux/client'; import CommandProvider, {CommandSuggestion} from './command_provider'; describe('CommandSuggestion', () => { const suggestion: AutocompleteSuggestion = { Suggestion: '/invite', Complete: '/invite', Hint: '@[username] ~[channel]', Description: 'Invite a user to a channel', IconData: '', }; const baseProps = { item: suggestion, isSelection: true, term: '/', matchedPretext: '', onClick: jest.fn(), onMouseMove: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <CommandSuggestion {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.slash-command__title').first().text()).toEqual('invite @[username] ~[channel]'); }); }); describe('CommandProvider', () => { describe('handlePretextChanged', () => { test('should fetch command autocomplete results from the server', async () => { const f = Client4.getCommandAutocompleteSuggestionsList; const mockFunc = jest.fn().mockResolvedValue([{ Suggestion: 'issue', Complete: 'jira issue', Hint: 'hint', IconData: 'icon_data', Description: 'description', type: 'commands', }]); Client4.getCommandAutocompleteSuggestionsList = mockFunc; const provider = new CommandProvider({ teamId: 'current_team', channelId: 'current_channel', rootId: 'current_root', }); const callback = jest.fn(); provider.handlePretextChanged('/jira issue', callback); await mockFunc(); const expected = { matchedPretext: '/jira issue', terms: ['/jira issue'], items: [{ Complete: '/jira issue', Suggestion: '/issue', Hint: 'hint', IconData: 'icon_data', Description: 'description', type: 'commands', }], component: CommandSuggestion, }; expect(callback).toHaveBeenCalledWith(expected); Client4.getCommandAutocompleteSuggestionsList = f; }); test('should use the app command parser', async () => { const f = Client4.getCommandAutocompleteSuggestionsList; const mockFunc = jest.fn().mockResolvedValue([{ Suggestion: 'issue', Complete: 'jira issue', Hint: 'hint', IconData: 'icon_data', Description: 'description', type: 'commands', }]); Client4.getCommandAutocompleteSuggestionsList = mockFunc; const provider = new CommandProvider({ teamId: 'current_team', channelId: 'current_channel', rootId: 'current_root', }); const callback = jest.fn(); provider.handlePretextChanged('/jira issue', callback); await mockFunc(); const expected = { matchedPretext: '/jira issue', terms: ['/jira issue'], items: [{ Complete: '/jira issue', Suggestion: '/issue', Hint: 'hint', IconData: 'icon_data', Description: 'description', type: 'commands', }], component: CommandSuggestion, }; expect(callback).toHaveBeenCalledWith(expected); Client4.getCommandAutocompleteSuggestionsList = f; }); }); });
3,251
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/command_provider
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/command_provider/__snapshots__/command_provider.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`CommandSuggestion should match snapshot 1`] = ` <SuggestionContainer isSelection={true} item={ Object { "Complete": "/invite", "Description": "Invite a user to a channel", "Hint": "@[username] ~[channel]", "IconData": "", "Suggestion": "/invite", } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} term="/" > <div className="slash-command__icon" > <span> / </span> </div> <div className="slash-command__info" > <div className="slash-command__title" > invite @[username] ~[channel] </div> <div className="slash-command__desc" > Invite a user to a channel </div> </div> </SuggestionContainer> `;
3,252
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/command_provider
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/command_provider/app_command_parser/app_command_parser.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import mockStore from 'tests/test_store'; import { AppCommandParser, ParseState, ParsedCommand, } from './app_command_parser'; import { AppCallResponseTypes, } from './app_command_parser_dependencies'; import type { AutocompleteSuggestion} from './app_command_parser_dependencies'; import { reduxTestState, testBindings, } from './tests/app_command_parser_test_data'; import { Client4, checkForExecuteSuggestion, } from './tests/app_command_parser_test_dependencies'; import type { AppBinding} from './tests/app_command_parser_test_dependencies'; const getOpenInModalOption = (command: string) => { return { Complete: command.substr(1) + '_open_command_in_modal', Description: 'Select this option to open the current command in a modal.', Hint: '', IconData: '_open_command_in_modal', Suggestion: 'Open in modal', }; }; describe('AppCommandParser', () => { const makeStore = async (bindings: AppBinding[]) => { const initialState = { ...reduxTestState, entities: { ...reduxTestState.entities, apps: { main: { bindings, forms: {}, }, rhs: { bindings, forms: {}, }, pluginEnabled: true, }, }, } as any; const testStore = await mockStore(initialState); return testStore; }; const intl = { formatMessage: (message: {id: string; defaultMessage: string}) => { return message.defaultMessage; }, }; let parser: AppCommandParser; beforeEach(async () => { const store = await makeStore(testBindings); parser = new AppCommandParser(store as any, intl, 'current_channel_id', 'team_id', 'root_id'); }); type Variant = { expectError?: string; verify?(parsed: ParsedCommand): void; } type TC = { title: string; command: string; submit: Variant; autocomplete?: Variant; // if undefined, use same checks as submnit } const checkResult = (parsed: ParsedCommand, v: Variant) => { if (v.expectError) { expect(parsed.state).toBe(ParseState.Error); expect(parsed.error).toBe(v.expectError); } else { // expect(parsed).toBe(1); expect(parsed.error).toBe(''); expect(v.verify).toBeTruthy(); if (v.verify) { v.verify(parsed); } } }; describe('getSuggestionsBase', () => { test('string matches 1', () => { const res = parser.getSuggestionsBase('/'); expect(res).toHaveLength(2); }); test('string matches 2', () => { const res = parser.getSuggestionsBase('/ji'); expect(res).toHaveLength(1); }); test('string matches 3', () => { const res = parser.getSuggestionsBase('/jira'); expect(res).toHaveLength(1); }); test('string matches case insensitive', () => { const res = parser.getSuggestionsBase('/JiRa'); expect(res).toHaveLength(1); }); test('string is past base command', () => { const res = parser.getSuggestionsBase('/jira '); expect(res).toHaveLength(0); }); test('other command matches', () => { const res = parser.getSuggestionsBase('/other'); expect(res).toHaveLength(1); }); test('string does not match', () => { const res = parser.getSuggestionsBase('/wrong'); expect(res).toHaveLength(0); }); }); describe('matchBinding', () => { const table: TC[] = [ { title: 'full command', command: '/jira issue create --project P --summary = "SUM MA RY" --verbose --epic=epic2', submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndCommand); expect(parsed.binding?.label).toBe('create'); expect(parsed.incomplete).toBe('--project'); expect(parsed.incompleteStart).toBe(19); }}, }, { title: 'full command case insensitive', command: '/JiRa IsSuE CrEaTe --PrOjEcT P --SuMmArY = "SUM MA RY" --VeRbOsE --EpIc=epic2', submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndCommand); expect(parsed.binding?.label).toBe('create'); expect(parsed.incomplete).toBe('--PrOjEcT'); expect(parsed.incompleteStart).toBe(19); }}, }, { title: 'incomplete top command', command: '/jir', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Command); expect(parsed.incomplete).toBe('jir'); }}, submit: {expectError: '`{command}`: No matching command found in this workspace.'}, }, { title: 'no space after the top command', command: '/jira', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Command); expect(parsed.incomplete).toBe('jira'); }}, submit: {expectError: 'You must select a subcommand.'}, }, { title: 'space after the top command', command: '/jira ', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Command); expect(parsed.incomplete).toBe(''); expect(parsed.binding?.label).toBe('jira'); }}, submit: {expectError: 'You must select a subcommand.'}, }, { title: 'middle of subcommand', command: '/jira iss', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Command); expect(parsed.binding?.label).toBe('jira'); expect(parsed.incomplete).toBe('iss'); expect(parsed.incompleteStart).toBe(9); }}, submit: {expectError: 'You must select a subcommand.'}, }, { title: 'second subcommand, no space', command: '/jira issue', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Command); expect(parsed.binding?.label).toBe('jira'); expect(parsed.incomplete).toBe('issue'); expect(parsed.incompleteStart).toBe(6); }}, submit: {expectError: 'You must select a subcommand.'}, }, { title: 'token after the end of bindings, no space', command: '/jira issue create something', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Command); expect(parsed.binding?.label).toBe('create'); expect(parsed.incomplete).toBe('something'); expect(parsed.incompleteStart).toBe(20); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndCommand); expect(parsed.binding?.label).toBe('create'); expect(parsed.incomplete).toBe('something'); expect(parsed.incompleteStart).toBe(20); }}, }, { title: 'token after the end of bindings, with space', command: '/jira issue create something ', submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndCommand); expect(parsed.binding?.label).toBe('create'); expect(parsed.incomplete).toBe('something'); expect(parsed.incompleteStart).toBe(20); }}, }, ]; table.forEach((tc) => { test(tc.title, async () => { const bindings = testBindings[0].bindings as AppBinding[]; let a = new ParsedCommand(tc.command, parser, intl); a = await a.matchBinding(bindings, true); checkResult(a, tc.autocomplete || tc.submit); let s = new ParsedCommand(tc.command, parser, intl); s = await s.matchBinding(bindings, false); checkResult(s, tc.submit); }); }); }); describe('parseForm', () => { const table: TC[] = [ { title: 'happy full create', command: '/jira issue create --project `P 1` --summary "SUM MA RY" --verbose --epic=epic2', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.incomplete).toBe('epic2'); expect(parsed.incompleteStart).toBe(75); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.epic).toBeUndefined(); expect(parsed.values?.summary).toBe('SUM MA RY'); expect(parsed.values?.verbose).toBe('true'); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.epic).toBe('epic2'); expect(parsed.values?.summary).toBe('SUM MA RY'); expect(parsed.values?.verbose).toBe('true'); }}, }, { title: 'happy full create case insensitive', command: '/JiRa IsSuE CrEaTe --PrOjEcT `P 1` --SuMmArY "SUM MA RY" --VeRbOsE --EpIc=epic2', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.incomplete).toBe('epic2'); expect(parsed.incompleteStart).toBe(75); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.epic).toBeUndefined(); expect(parsed.values?.summary).toBe('SUM MA RY'); expect(parsed.values?.verbose).toBe('true'); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.epic).toBe('epic2'); expect(parsed.values?.summary).toBe('SUM MA RY'); expect(parsed.values?.verbose).toBe('true'); }}, }, { title: 'partial epic', command: '/jira issue create --project KT --summary "great feature" --epic M', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.incomplete).toBe('M'); expect(parsed.incompleteStart).toBe(65); expect(parsed.values?.project).toBe('KT'); expect(parsed.values?.epic).toBeUndefined(); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.values?.epic).toBe('M'); }}, }, { title: 'happy full view', command: '/jira issue view --project=`P 1` MM-123', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.incomplete).toBe('MM-123'); expect(parsed.incompleteStart).toBe(33); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.issue).toBe(undefined); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.issue).toBe('MM-123'); }}, }, { title: 'happy view no parameters', command: '/jira issue view ', submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.StartParameter); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.incomplete).toBe(''); expect(parsed.incompleteStart).toBe(17); expect(parsed.values).toEqual({}); }}, }, { title: 'happy create flag no value', command: '/jira issue create --summary ', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.FlagValueSeparator); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.incomplete).toBe(''); expect(parsed.values).toEqual({}); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('create'); expect(parsed.resolvedForm?.submit?.path).toBe('/create-issue'); expect(parsed.incomplete).toBe(''); expect(parsed.values).toEqual({ summary: '', }); }}, }, { title: 'error: unmatched tick', command: '/jira issue view --project `P 1', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.TickValue); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.incomplete).toBe('P 1'); expect(parsed.incompleteStart).toBe(27); expect(parsed.values?.project).toBe(undefined); expect(parsed.values?.issue).toBe(undefined); }}, submit: {expectError: 'Matching tick quote expected before end of input.'}, }, { title: 'error: unmatched quote', command: '/jira issue view --project "P \\1', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.QuotedValue); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.incomplete).toBe('P 1'); expect(parsed.incompleteStart).toBe(27); expect(parsed.values?.project).toBe(undefined); expect(parsed.values?.issue).toBe(undefined); }}, submit: {expectError: 'Matching double quote expected before end of input.'}, }, { title: 'missing required fields not a problem for parseCommand', command: '/jira issue view --project "P 1"', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndQuotedValue); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.incomplete).toBe('P 1'); expect(parsed.incompleteStart).toBe(27); expect(parsed.values?.project).toBe(undefined); expect(parsed.values?.issue).toBe(undefined); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndQuotedValue); expect(parsed.binding?.label).toBe('view'); expect(parsed.resolvedForm?.submit?.path).toBe('/view-issue'); expect(parsed.values?.project).toBe('P 1'); expect(parsed.values?.issue).toBe(undefined); }}, }, { title: 'error: invalid flag', command: '/jira issue view --wrong test', submit: {expectError: 'Command does not accept flag `{flagName}`.'}, }, { title: 'error: unexpected positional', command: '/jira issue create wrong', submit: {expectError: 'Unable to identify argument.'}, }, { title: 'error: multiple equal signs', command: '/jira issue create --project == test', submit: {expectError: 'Multiple `=` signs are not allowed.'}, }, { title: 'rest field', command: '/jira issue rest hello world', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Rest); expect(parsed.binding?.label).toBe('rest'); expect(parsed.incomplete).toBe('hello world'); expect(parsed.values?.summary).toBe(undefined); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Rest); expect(parsed.binding?.label).toBe('rest'); expect(parsed.values?.summary).toBe('hello world'); }}, }, { title: 'rest field with other field', command: '/jira issue rest --verbose true hello world', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Rest); expect(parsed.binding?.label).toBe('rest'); expect(parsed.incomplete).toBe('hello world'); expect(parsed.values?.summary).toBe(undefined); expect(parsed.values?.verbose).toBe('true'); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.Rest); expect(parsed.binding?.label).toBe('rest'); expect(parsed.values?.summary).toBe('hello world'); expect(parsed.values?.verbose).toBe('true'); }}, }, { title: 'rest field as flag with other field', command: '/jira issue rest --summary "hello world" --verbose true', autocomplete: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('rest'); expect(parsed.incomplete).toBe('true'); expect(parsed.values?.summary).toBe('hello world'); expect(parsed.values?.verbose).toBe(undefined); }}, submit: {verify: (parsed: ParsedCommand): void => { expect(parsed.state).toBe(ParseState.EndValue); expect(parsed.binding?.label).toBe('rest'); expect(parsed.values?.summary).toBe('hello world'); expect(parsed.values?.verbose).toBe('true'); }}, }, { title: 'error: rest after rest field flag', command: '/jira issue rest --summary "hello world" --verbose true hello world', submit: {expectError: 'Unable to identify argument.'}, }, ]; table.forEach((tc) => { test(tc.title, async () => { const bindings = testBindings[0].bindings as AppBinding[]; let a = new ParsedCommand(tc.command, parser, intl); a = await a.matchBinding(bindings, true); a = a.parseForm(true); checkResult(a, tc.autocomplete || tc.submit); let s = new ParsedCommand(tc.command, parser, intl); s = await s.matchBinding(bindings, false); s = s.parseForm(false); checkResult(s, tc.submit); }); }); }); describe('getSuggestions', () => { test('subcommand 1', async () => { const suggestions = await parser.getSuggestions('/jira '); expect(suggestions).toEqual([ { Suggestion: 'issue', Complete: 'jira issue', Hint: 'Issue hint', IconData: 'Issue icon', Description: 'Interact with Jira issues', type: 'commands', }, ]); }); test('subcommand 1 case insensitive', async () => { const suggestions = await parser.getSuggestions('/JiRa '); expect(suggestions).toEqual([ { Suggestion: 'issue', Complete: 'JiRa issue', Hint: 'Issue hint', IconData: 'Issue icon', Description: 'Interact with Jira issues', type: 'commands', }, ]); }); test('subcommand 2', async () => { const suggestions = await parser.getSuggestions('/jira issue'); expect(suggestions).toEqual([ { Suggestion: 'issue', Complete: 'jira issue', Hint: 'Issue hint', IconData: 'Issue icon', Description: 'Interact with Jira issues', type: 'commands', }, ]); }); test('subcommand 2 case insensitive', async () => { const suggestions = await parser.getSuggestions('/JiRa IsSuE'); expect(suggestions).toEqual([ { Suggestion: 'issue', Complete: 'JiRa issue', Hint: 'Issue hint', IconData: 'Issue icon', Description: 'Interact with Jira issues', type: 'commands', }, ]); }); test('subcommand 2 with a space', async () => { const suggestions = await parser.getSuggestions('/jira issue '); expect(suggestions).toEqual([ { Suggestion: 'view', Complete: 'jira issue view', Hint: '', IconData: '', Description: 'View details of a Jira issue', type: 'commands', }, { Suggestion: 'create', Complete: 'jira issue create', Hint: 'Create hint', IconData: 'Create icon', Description: 'Create a new Jira issue', type: 'commands', }, { Suggestion: 'rest', Complete: 'jira issue rest', Hint: 'rest hint', IconData: 'rest icon', Description: 'rest description', type: 'commands', }, ]); }); test('subcommand 2 with a space case insensitive', async () => { const suggestions = await parser.getSuggestions('/JiRa IsSuE '); expect(suggestions).toEqual([ { Suggestion: 'view', Complete: 'JiRa IsSuE view', Hint: '', IconData: '', Description: 'View details of a Jira issue', type: 'commands', }, { Suggestion: 'create', Complete: 'JiRa IsSuE create', Hint: 'Create hint', IconData: 'Create icon', Description: 'Create a new Jira issue', type: 'commands', }, { Suggestion: 'rest', Complete: 'JiRa IsSuE rest', Hint: 'rest hint', IconData: 'rest icon', Description: 'rest description', type: 'commands', }, ]); }); test('subcommand 3 partial', async () => { const suggestions = await parser.getSuggestions('/jira issue c'); expect(suggestions).toEqual([ { Suggestion: 'create', Complete: 'jira issue create', Hint: 'Create hint', IconData: 'Create icon', Description: 'Create a new Jira issue', type: 'commands', }, ]); }); test('subcommand 3 partial case insensitive', async () => { const suggestions = await parser.getSuggestions('/JiRa IsSuE C'); expect(suggestions).toEqual([ { Suggestion: 'create', Complete: 'JiRa IsSuE create', Hint: 'Create hint', IconData: 'Create icon', Description: 'Create a new Jira issue', type: 'commands', }, ]); }); test('view just after subcommand (positional)', async () => { const suggestions = await parser.getSuggestions('/jira issue view '); expect(suggestions).toEqual([ { Complete: 'jira issue view', Description: 'The Jira issue key', Hint: '', IconData: '', Suggestion: 'issue: ""', }, getOpenInModalOption('/jira issue view '), ]); }); test('view flags just after subcommand', async () => { let suggestions = await parser.getSuggestions('/jira issue view -'); expect(suggestions).toEqual([ { Complete: 'jira issue view --project', Description: 'The Jira project description', Hint: 'The Jira project hint', IconData: '', Suggestion: '--project', }, getOpenInModalOption('/jira issue view -'), ]); suggestions = await parser.getSuggestions('/jira issue view --'); expect(suggestions).toEqual([ { Complete: 'jira issue view --project', Description: 'The Jira project description', Hint: 'The Jira project hint', IconData: '', Suggestion: '--project', }, getOpenInModalOption('/jira issue view --'), ]); }); test('create flags just after subcommand', async () => { const suggestions = await parser.getSuggestions('/jira issue create '); let executeCommand: AutocompleteSuggestion[] = []; if (checkForExecuteSuggestion) { executeCommand = [ { Complete: 'jira issue create _execute_current_command', Description: 'Select this option or use Ctrl+Enter to execute the current command.', Hint: '', IconData: '_execute_current_command', Suggestion: 'Execute Current Command', }, ]; } expect(suggestions).toEqual([ ...executeCommand, { Complete: 'jira issue create --project', Description: 'The Jira project description', Hint: 'The Jira project hint', IconData: 'Create icon', Suggestion: '--project', }, { Complete: 'jira issue create --summary', Description: 'The Jira issue summary', Hint: 'The thing is working great!', IconData: 'Create icon', Suggestion: '--summary', }, { Complete: 'jira issue create --verbose', Description: 'display details', Hint: 'yes or no!', IconData: 'Create icon', Suggestion: '--verbose', }, { Complete: 'jira issue create --epic', Description: 'The Jira epic', Hint: 'The thing is working great!', IconData: 'Create icon', Suggestion: '--epic', }, getOpenInModalOption('/jira issue create '), ]); }); test('used flags do not appear', async () => { const suggestions = await parser.getSuggestions('/jira issue create --project KT '); let executeCommand: AutocompleteSuggestion[] = []; if (checkForExecuteSuggestion) { executeCommand = [ { Complete: 'jira issue create --project KT _execute_current_command', Description: 'Select this option or use Ctrl+Enter to execute the current command.', Hint: '', IconData: '_execute_current_command', Suggestion: 'Execute Current Command', }, ]; } expect(suggestions).toEqual([ ...executeCommand, { Complete: 'jira issue create --project KT --summary', Description: 'The Jira issue summary', Hint: 'The thing is working great!', IconData: 'Create icon', Suggestion: '--summary', }, { Complete: 'jira issue create --project KT --verbose', Description: 'display details', Hint: 'yes or no!', IconData: 'Create icon', Suggestion: '--verbose', }, { Complete: 'jira issue create --project KT --epic', Description: 'The Jira epic', Hint: 'The thing is working great!', IconData: 'Create icon', Suggestion: '--epic', }, getOpenInModalOption('/jira issue create --project KT '), ]); }); test('create flags mid-flag', async () => { const mid = await parser.getSuggestions('/jira issue create --project KT --summ'); expect(mid).toEqual([ { Complete: 'jira issue create --project KT --summary', Description: 'The Jira issue summary', Hint: 'The thing is working great!', IconData: 'Create icon', Suggestion: '--summary', }, getOpenInModalOption('/jira issue create --project KT --summ'), ]); const full = await parser.getSuggestions('/jira issue create --project KT --summary'); expect(full).toEqual([ { Complete: 'jira issue create --project KT --summary', Description: 'The Jira issue summary', Hint: 'The thing is working great!', IconData: 'Create icon', Suggestion: '--summary', }, getOpenInModalOption('/jira issue create --project KT --summary'), ]); }); test('empty text value suggestion', async () => { const suggestions = await parser.getSuggestions('/jira issue create --project KT --summary '); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary', Description: 'The Jira issue summary', Hint: '', IconData: 'Create icon', Suggestion: 'summary: ""', }, getOpenInModalOption('/jira issue create --project KT --summary '), ]); }); test('partial text value suggestion', async () => { const suggestions = await parser.getSuggestions('/jira issue create --project KT --summary Sum'); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary Sum', Description: 'The Jira issue summary', Hint: '', IconData: 'Create icon', Suggestion: 'summary: "Sum"', }, getOpenInModalOption('/jira issue create --project KT --summary Sum'), ]); }); test('quote text value suggestion close quotes', async () => { const suggestions = await parser.getSuggestions('/jira issue create --project KT --summary "Sum'); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary "Sum"', Description: 'The Jira issue summary', Hint: '', IconData: 'Create icon', Suggestion: 'summary: "Sum"', }, getOpenInModalOption('/jira issue create --project KT --summary "Sum'), ]); }); test('tick text value suggestion close quotes', async () => { const suggestions = await parser.getSuggestions('/jira issue create --project KT --summary `Sum'); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary `Sum`', Description: 'The Jira issue summary', Hint: '', IconData: 'Create icon', Suggestion: 'summary: `Sum`', }, getOpenInModalOption('/jira issue create --project KT --summary `Sum'), ]); }); test('create flag summary value', async () => { const suggestions = await parser.getSuggestions('/jira issue create --summary '); expect(suggestions).toEqual([ { Complete: 'jira issue create --summary', Description: 'The Jira issue summary', Hint: '', IconData: 'Create icon', Suggestion: 'summary: ""', }, getOpenInModalOption('/jira issue create --summary '), ]); }); test('create flag project dynamic select value', async () => { const f = Client4.executeAppCall; Client4.executeAppCall = jest.fn().mockResolvedValue(Promise.resolve({type: AppCallResponseTypes.OK, data: {items: [{label: 'special-label', value: 'special-value'}]}})); const suggestions = await parser.getSuggestions('/jira issue create --project '); Client4.executeAppCall = f; expect(suggestions).toEqual([ { Complete: 'jira issue create --project special-value', Suggestion: 'special-value', Description: 'special-label', Hint: '', IconData: 'Create icon', }, getOpenInModalOption('/jira issue create --project '), ]); }); test('create flag epic static select value', async () => { let suggestions = await parser.getSuggestions('/jira issue create --project KT --summary "great feature" --epic '); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary "great feature" --epic epic1', Suggestion: 'Dylan Epic', Description: 'The Jira epic', Hint: 'The thing is working great!', IconData: 'Create icon', }, { Complete: 'jira issue create --project KT --summary "great feature" --epic epic2', Suggestion: 'Michael Epic', Description: 'The Jira epic', Hint: 'The thing is working great!', IconData: 'Create icon', }, getOpenInModalOption('/jira issue create --project KT --summary "great feature" --epic '), ]); suggestions = await parser.getSuggestions('/jira issue create --project KT --summary "great feature" --epic M'); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary "great feature" --epic epic2', Suggestion: 'Michael Epic', Description: 'The Jira epic', Hint: 'The thing is working great!', IconData: 'Create icon', }, getOpenInModalOption('/jira issue create --project KT --summary "great feature" --epic M'), ]); suggestions = await parser.getSuggestions('/jira issue create --project KT --summary "great feature" --epic Nope'); expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary "great feature" --epic', Suggestion: '', Description: '', Hint: 'No matching options.', IconData: 'error', }, getOpenInModalOption('/jira issue create --project KT --summary "great feature" --epic Nope'), ]); }); test('filled out form shows execute', async () => { const suggestions = await parser.getSuggestions('/jira issue create --project KT --summary "great feature" --epic epicvalue --verbose true '); if (!checkForExecuteSuggestion) { expect(suggestions).toEqual([]); return; } expect(suggestions).toEqual([ { Complete: 'jira issue create --project KT --summary "great feature" --epic epicvalue --verbose true _execute_current_command', Suggestion: 'Execute Current Command', Description: 'Select this option or use Ctrl+Enter to execute the current command.', IconData: '_execute_current_command', Hint: '', }, getOpenInModalOption('/jira issue create --project KT --summary "great feature" --epic epicvalue --verbose true '), ]); }); }); describe('composeCommandSubmitCall', () => { const base = { context: { app_id: 'jira', channel_id: 'current_channel_id', location: '/command/jira/issue/create', root_id: 'root_id', team_id: 'team_id', }, path: '/create-issue', }; test('empty form', async () => { const cmd = '/jira issue create'; const values = {}; const {creq} = await parser.composeCommandSubmitCall(cmd); expect(creq).toEqual({ ...base, raw_command: cmd, expand: {}, query: undefined, selected_field: undefined, values, }); }); test('full form', async () => { const cmd = '/jira issue create --summary "Here it is" --epic epic1 --verbose true --project'; const values = { summary: 'Here it is', epic: { label: 'Dylan Epic', value: 'epic1', }, verbose: true, project: '', }; const {creq} = await parser.composeCommandSubmitCall(cmd); expect(creq).toEqual({ ...base, expand: {}, selected_field: undefined, query: undefined, raw_command: cmd, values, }); }); test('dynamic lookup test', async () => { const f = Client4.executeAppCall; const mockedExecute = jest.fn().mockResolvedValue(Promise.resolve({type: AppCallResponseTypes.OK, data: {items: [{label: 'special-label', value: 'special-value'}]}})); Client4.executeAppCall = mockedExecute; const suggestions = await parser.getSuggestions('/jira issue create --summary "The summary" --epic epic1 --project special'); Client4.executeAppCall = f; expect(suggestions).toEqual([ { Complete: 'jira issue create --summary "The summary" --epic epic1 --project special-value', Suggestion: 'special-value', Description: 'special-label', Hint: '', IconData: 'Create icon', }, getOpenInModalOption('/jira issue create --summary "The summary" --epic epic1 --project special'), ]); expect(mockedExecute).toHaveBeenCalledWith({ context: { app_id: 'jira', channel_id: 'current_channel_id', location: '/command/jira/issue/create', root_id: 'root_id', team_id: 'team_id', }, expand: {}, path: '/create-issue-lookup', query: 'special', raw_command: '/jira issue create --summary "The summary" --epic epic1 --project special', selected_field: 'project', values: { summary: 'The summary', epic: { label: 'Dylan Epic', value: 'epic1', }, }, }, false); }); }); });
3,259
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/search_channel_suggestion/search_channel_suggestion.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 {TestHelper} from 'utils/test_helper'; import SearchChannelSuggestion from './search_channel_suggestion'; describe('components/suggestion/search_channel_suggestion', () => { const mockChannel = TestHelper.getChannelMock(); const baseProps = { item: mockChannel, isSelection: false, currentUserId: 'userid1', teammateIsBot: false, term: '', matchedPretext: '', onClick: jest.fn(), onMouseMove: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <SearchChannelSuggestion {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, isSelection is false', () => { const props = {...baseProps, isSelection: false}; const wrapper = shallow( <SearchChannelSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, isSelection is true', () => { const props = {...baseProps, isSelection: true}; const wrapper = shallow( <SearchChannelSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, channel type DM_CHANNEL', () => { mockChannel.type = 'D'; const props = {...baseProps, item: mockChannel, isSelection: true}; const wrapper = shallow( <SearchChannelSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, channel type GM_CHANNEL', () => { mockChannel.type = 'G'; const props = {...baseProps, item: mockChannel, isSelection: true}; const wrapper = shallow( <SearchChannelSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, channel type OPEN_CHANNEL', () => { mockChannel.type = 'O'; const props = {...baseProps, item: mockChannel, isSelection: true}; const wrapper = shallow( <SearchChannelSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, channel type PRIVATE_CHANNEL', () => { mockChannel.type = 'P'; const props = {...baseProps, item: mockChannel, isSelection: true}; const wrapper = shallow( <SearchChannelSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,261
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/search_channel_suggestion
petrpan-code/mattermost/mattermost/webapp/channels/src/components/suggestion/search_channel_suggestion/__snapshots__/search_channel_suggestion.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/suggestion/search_channel_suggestion should match snapshot 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={false} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <span className="suggestion-list__icon suggestion-list__icon--large" > <i className="icon icon--standard icon--no-spacing icon-globe" /> </span> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > name </span> ~DN </div> </SuggestionContainer> `; exports[`components/suggestion/search_channel_suggestion should match snapshot, channel type DM_CHANNEL 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={true} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "D", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <Memo(Avatar) size="sm" url="/api/v4/users/DN/image?_=0" /> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > @name </span> </div> </SuggestionContainer> `; exports[`components/suggestion/search_channel_suggestion should match snapshot, channel type GM_CHANNEL 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={true} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "G", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <span className="suggestion-list__icon suggestion-list__icon--large" > <div className="status status--group" > G </div> </span> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > @name </span> </div> </SuggestionContainer> `; exports[`components/suggestion/search_channel_suggestion should match snapshot, channel type OPEN_CHANNEL 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={true} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <span className="suggestion-list__icon suggestion-list__icon--large" > <i className="icon icon--standard icon--no-spacing icon-globe" /> </span> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > name </span> ~DN </div> </SuggestionContainer> `; exports[`components/suggestion/search_channel_suggestion should match snapshot, channel type PRIVATE_CHANNEL 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={true} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "P", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <span className="suggestion-list__icon suggestion-list__icon--large" > <i className="icon icon--standard icon--no-spacing icon-lock-outline" /> </span> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > name </span> ~DN </div> </SuggestionContainer> `; exports[`components/suggestion/search_channel_suggestion should match snapshot, isSelection is false 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={false} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <span className="suggestion-list__icon suggestion-list__icon--large" > <i className="icon icon--standard icon--no-spacing icon-globe" /> </span> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > name </span> ~DN </div> </SuggestionContainer> `; exports[`components/suggestion/search_channel_suggestion should match snapshot, isSelection is true 1`] = ` <SuggestionContainer currentUserId="userid1" isSelection={true} item={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } matchedPretext="" onClick={[MockFunction]} onMouseMove={[MockFunction]} teammateIsBot={false} term="" > <span className="suggestion-list__icon suggestion-list__icon--large" > <i className="icon icon--standard icon--no-spacing icon-globe" /> </span> <div className="suggestion-list__ellipsis" > <span className="suggestion-list__main" > name </span> ~DN </div> </SuggestionContainer> `;
3,271
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/system_notice/system_notice.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import SystemNotice from 'components/system_notice/system_notice'; import {mountWithIntl, type MockIntl} from 'tests/helpers/intl-test-helper'; describe('components/SystemNotice', () => { const baseProps = { currentUserId: 'someid', preferences: {}, dismissedNotices: {}, isSystemAdmin: false, notices: [{name: 'notice1', adminOnly: false, title: 'some title', body: 'some body', allowForget: true, show: () => true}], serverVersion: '5.1', license: {IsLicensed: 'true'}, config: {}, analytics: {TOTAL_USERS: 300}, intl: { formatMessage: jest.fn(), } as MockIntl, actions: { savePreferences: jest.fn(), dismissNotice: jest.fn(), getStandardAnalytics: jest.fn(), }, }; test('should match snapshot for regular user, regular notice', () => { const wrapper = mountWithIntl(<SystemNotice {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for regular user, no notice', () => { const props = {...baseProps, notices: []}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for regular user, admin notice', () => { const props = {...baseProps, notices: [{...baseProps.notices[0], adminOnly: true}]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for regular user, admin and regular notice', () => { const props = {...baseProps, notices: [ {...baseProps.notices[0], adminOnly: true}, {...baseProps.notices[0], name: 'notice2', title: 'some title2', body: 'some body2'}, ]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for admin, regular notice', () => { const props = {...baseProps, isSystemAdmin: true}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for admin, admin notice', () => { const props = {...baseProps, isSystemAdmin: true, notices: [{...baseProps.notices[0], adminOnly: true}]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for regular user, dismissed notice', () => { const props = {...baseProps, dismissedNotices: {notice1: true}}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for regular user, dont show again notice', () => { const props = {...baseProps, preferences: {notice1: {}}}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for show function returning false', () => { const props = {...baseProps, notices: [{...baseProps.notices[0], show: () => false}]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for show function returning true', () => { const props = {...baseProps, notices: [{...baseProps.notices[0], show: () => true}]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for with allowForget equal false', () => { const props = {...baseProps, notices: [{...baseProps.notices[0], allowForget: false}]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when a custom icon is passed', () => { const props = {...baseProps, notices: [{...baseProps.notices[0], icon: <span>{'icon'}</span>}]}; const wrapper = mountWithIntl(<SystemNotice {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
3,274
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/system_notice
petrpan-code/mattermost/mattermost/webapp/channels/src/components/system_notice/__snapshots__/system_notice.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SystemNotice should match snapshot for admin, admin notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction] { "calls": Array [ Array [], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction] { "calls": Array [ Array [ Object { "defaultMessage": "Only visible to System Admins Icon", "id": "system_notice.adminVisible.icon", }, ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, } } isSystemAdmin={true} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": true, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <MattermostLogo> <span> <svg aria-label="Mattermost Logo" enableBackground="new 0 0 500 500" role="img" version="1.1" viewBox="0 0 500 500" x="0px" y="0px" > <g> <g> <path d="M396.9,47.7l2.6,53.1c43,47.5,60,114.8,38.6,178.1c-32,94.4-137.4,144.1-235.4,110.9 S51.1,253.1,83,158.7C104.5,95.2,159.2,52,222.5,40.5l34.2-40.4C150-2.8,49.3,63.4,13.3,169.9C-31,300.6,39.1,442.5,169.9,486.7 s272.6-25.8,316.9-156.6C522.7,223.9,483.1,110.3,396.9,47.7z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> <path d="M335.6,204.3l-1.8-74.2l-1.5-42.7l-1-37c0,0,0.2-17.8-0.4-22c-0.1-0.9-0.4-1.6-0.7-2.2 c0-0.1-0.1-0.2-0.1-0.3c0-0.1-0.1-0.2-0.1-0.2c-0.7-1.2-1.8-2.1-3.1-2.6c-1.4-0.5-2.9-0.4-4.2,0.2c0,0-0.1,0-0.1,0 c-0.2,0.1-0.3,0.1-0.4,0.2c-0.6,0.3-1.2,0.7-1.8,1.3c-3,3-13.7,17.2-13.7,17.2l-23.2,28.8l-27.1,33l-46.5,57.8 c0,0-21.3,26.6-16.6,59.4s29.1,48.7,48,55.1c18.9,6.4,48,8.5,71.6-14.7C336.4,238.4,335.6,204.3,335.6,204.3z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> </svg> </span> </MattermostLogo> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title </div> some body <div className="system-notice__info" > <i className="fa fa-eye" /> <FormattedMessage defaultMessage="Only visible to System Admins" id="system_notice.adminVisible" > <span> Only visible to System Admins </span> </FormattedMessage> </div> <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> <button className="btn btn-sm btn-tertiary" id="systemnotice_dontshow" onClick={[Function]} > <FormattedMessage defaultMessage="Don't Show Again" id="system_notice.dont_show" > <span> Don't Show Again </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `; exports[`components/SystemNotice should match snapshot for admin, regular notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction] { "calls": Array [ Array [], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={true} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <MattermostLogo> <span> <svg aria-label="Mattermost Logo" enableBackground="new 0 0 500 500" role="img" version="1.1" viewBox="0 0 500 500" x="0px" y="0px" > <g> <g> <path d="M396.9,47.7l2.6,53.1c43,47.5,60,114.8,38.6,178.1c-32,94.4-137.4,144.1-235.4,110.9 S51.1,253.1,83,158.7C104.5,95.2,159.2,52,222.5,40.5l34.2-40.4C150-2.8,49.3,63.4,13.3,169.9C-31,300.6,39.1,442.5,169.9,486.7 s272.6-25.8,316.9-156.6C522.7,223.9,483.1,110.3,396.9,47.7z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> <path d="M335.6,204.3l-1.8-74.2l-1.5-42.7l-1-37c0,0,0.2-17.8-0.4-22c-0.1-0.9-0.4-1.6-0.7-2.2 c0-0.1-0.1-0.2-0.1-0.3c0-0.1-0.1-0.2-0.1-0.2c-0.7-1.2-1.8-2.1-3.1-2.6c-1.4-0.5-2.9-0.4-4.2,0.2c0,0-0.1,0-0.1,0 c-0.2,0.1-0.3,0.1-0.4,0.2c-0.6,0.3-1.2,0.7-1.8,1.3c-3,3-13.7,17.2-13.7,17.2l-23.2,28.8l-27.1,33l-46.5,57.8 c0,0-21.3,26.6-16.6,59.4s29.1,48.7,48,55.1c18.9,6.4,48,8.5,71.6-14.7C336.4,238.4,335.6,204.3,335.6,204.3z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> </svg> </span> </MattermostLogo> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title </div> some body <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> <button className="btn btn-sm btn-tertiary" id="systemnotice_dontshow" onClick={[Function]} > <FormattedMessage defaultMessage="Don't Show Again" id="system_notice.dont_show" > <span> Don't Show Again </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `; exports[`components/SystemNotice should match snapshot for regular user, admin and regular notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": true, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, Object { "adminOnly": false, "allowForget": true, "body": "some body2", "name": "notice2", "show": [Function], "title": "some title2", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <MattermostLogo> <span> <svg aria-label="Mattermost Logo" enableBackground="new 0 0 500 500" role="img" version="1.1" viewBox="0 0 500 500" x="0px" y="0px" > <g> <g> <path d="M396.9,47.7l2.6,53.1c43,47.5,60,114.8,38.6,178.1c-32,94.4-137.4,144.1-235.4,110.9 S51.1,253.1,83,158.7C104.5,95.2,159.2,52,222.5,40.5l34.2-40.4C150-2.8,49.3,63.4,13.3,169.9C-31,300.6,39.1,442.5,169.9,486.7 s272.6-25.8,316.9-156.6C522.7,223.9,483.1,110.3,396.9,47.7z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> <path d="M335.6,204.3l-1.8-74.2l-1.5-42.7l-1-37c0,0,0.2-17.8-0.4-22c-0.1-0.9-0.4-1.6-0.7-2.2 c0-0.1-0.1-0.2-0.1-0.3c0-0.1-0.1-0.2-0.1-0.2c-0.7-1.2-1.8-2.1-3.1-2.6c-1.4-0.5-2.9-0.4-4.2,0.2c0,0-0.1,0-0.1,0 c-0.2,0.1-0.3,0.1-0.4,0.2c-0.6,0.3-1.2,0.7-1.8,1.3c-3,3-13.7,17.2-13.7,17.2l-23.2,28.8l-27.1,33l-46.5,57.8 c0,0-21.3,26.6-16.6,59.4s29.1,48.7,48,55.1c18.9,6.4,48,8.5,71.6-14.7C336.4,238.4,335.6,204.3,335.6,204.3z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> </svg> </span> </MattermostLogo> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title2 </div> some body2 <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> <button className="btn btn-sm btn-tertiary" id="systemnotice_dontshow" onClick={[Function]} > <FormattedMessage defaultMessage="Don't Show Again" id="system_notice.dont_show" > <span> Don't Show Again </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `; exports[`components/SystemNotice should match snapshot for regular user, admin notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": true, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" /> `; exports[`components/SystemNotice should match snapshot for regular user, dismissed notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={ Object { "notice1": true, } } intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" /> `; exports[`components/SystemNotice should match snapshot for regular user, dont show again notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={ Object { "notice1": Object {}, } } serverVersion="5.1" /> `; exports[`components/SystemNotice should match snapshot for regular user, no notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={Array []} preferences={Object {}} serverVersion="5.1" /> `; exports[`components/SystemNotice should match snapshot for regular user, regular notice 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <MattermostLogo> <span> <svg aria-label="Mattermost Logo" enableBackground="new 0 0 500 500" role="img" version="1.1" viewBox="0 0 500 500" x="0px" y="0px" > <g> <g> <path d="M396.9,47.7l2.6,53.1c43,47.5,60,114.8,38.6,178.1c-32,94.4-137.4,144.1-235.4,110.9 S51.1,253.1,83,158.7C104.5,95.2,159.2,52,222.5,40.5l34.2-40.4C150-2.8,49.3,63.4,13.3,169.9C-31,300.6,39.1,442.5,169.9,486.7 s272.6-25.8,316.9-156.6C522.7,223.9,483.1,110.3,396.9,47.7z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> <path d="M335.6,204.3l-1.8-74.2l-1.5-42.7l-1-37c0,0,0.2-17.8-0.4-22c-0.1-0.9-0.4-1.6-0.7-2.2 c0-0.1-0.1-0.2-0.1-0.3c0-0.1-0.1-0.2-0.1-0.2c-0.7-1.2-1.8-2.1-3.1-2.6c-1.4-0.5-2.9-0.4-4.2,0.2c0,0-0.1,0-0.1,0 c-0.2,0.1-0.3,0.1-0.4,0.2c-0.6,0.3-1.2,0.7-1.8,1.3c-3,3-13.7,17.2-13.7,17.2l-23.2,28.8l-27.1,33l-46.5,57.8 c0,0-21.3,26.6-16.6,59.4s29.1,48.7,48,55.1c18.9,6.4,48,8.5,71.6-14.7C336.4,238.4,335.6,204.3,335.6,204.3z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> </svg> </span> </MattermostLogo> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title </div> some body <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> <button className="btn btn-sm btn-tertiary" id="systemnotice_dontshow" onClick={[Function]} > <FormattedMessage defaultMessage="Don't Show Again" id="system_notice.dont_show" > <span> Don't Show Again </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `; exports[`components/SystemNotice should match snapshot for show function returning false 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" /> `; exports[`components/SystemNotice should match snapshot for show function returning true 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <MattermostLogo> <span> <svg aria-label="Mattermost Logo" enableBackground="new 0 0 500 500" role="img" version="1.1" viewBox="0 0 500 500" x="0px" y="0px" > <g> <g> <path d="M396.9,47.7l2.6,53.1c43,47.5,60,114.8,38.6,178.1c-32,94.4-137.4,144.1-235.4,110.9 S51.1,253.1,83,158.7C104.5,95.2,159.2,52,222.5,40.5l34.2-40.4C150-2.8,49.3,63.4,13.3,169.9C-31,300.6,39.1,442.5,169.9,486.7 s272.6-25.8,316.9-156.6C522.7,223.9,483.1,110.3,396.9,47.7z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> <path d="M335.6,204.3l-1.8-74.2l-1.5-42.7l-1-37c0,0,0.2-17.8-0.4-22c-0.1-0.9-0.4-1.6-0.7-2.2 c0-0.1-0.1-0.2-0.1-0.3c0-0.1-0.1-0.2-0.1-0.2c-0.7-1.2-1.8-2.1-3.1-2.6c-1.4-0.5-2.9-0.4-4.2,0.2c0,0-0.1,0-0.1,0 c-0.2,0.1-0.3,0.1-0.4,0.2c-0.6,0.3-1.2,0.7-1.8,1.3c-3,3-13.7,17.2-13.7,17.2l-23.2,28.8l-27.1,33l-46.5,57.8 c0,0-21.3,26.6-16.6,59.4s29.1,48.7,48,55.1c18.9,6.4,48,8.5,71.6-14.7C336.4,238.4,335.6,204.3,335.6,204.3z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> </svg> </span> </MattermostLogo> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title </div> some body <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> <button className="btn btn-sm btn-tertiary" id="systemnotice_dontshow" onClick={[Function]} > <FormattedMessage defaultMessage="Don't Show Again" id="system_notice.dont_show" > <span> Don't Show Again </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `; exports[`components/SystemNotice should match snapshot for with allowForget equal false 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": false, "body": "some body", "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <MattermostLogo> <span> <svg aria-label="Mattermost Logo" enableBackground="new 0 0 500 500" role="img" version="1.1" viewBox="0 0 500 500" x="0px" y="0px" > <g> <g> <path d="M396.9,47.7l2.6,53.1c43,47.5,60,114.8,38.6,178.1c-32,94.4-137.4,144.1-235.4,110.9 S51.1,253.1,83,158.7C104.5,95.2,159.2,52,222.5,40.5l34.2-40.4C150-2.8,49.3,63.4,13.3,169.9C-31,300.6,39.1,442.5,169.9,486.7 s272.6-25.8,316.9-156.6C522.7,223.9,483.1,110.3,396.9,47.7z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> <path d="M335.6,204.3l-1.8-74.2l-1.5-42.7l-1-37c0,0,0.2-17.8-0.4-22c-0.1-0.9-0.4-1.6-0.7-2.2 c0-0.1-0.1-0.2-0.1-0.3c0-0.1-0.1-0.2-0.1-0.2c-0.7-1.2-1.8-2.1-3.1-2.6c-1.4-0.5-2.9-0.4-4.2,0.2c0,0-0.1,0-0.1,0 c-0.2,0.1-0.3,0.1-0.4,0.2c-0.6,0.3-1.2,0.7-1.8,1.3c-3,3-13.7,17.2-13.7,17.2l-23.2,28.8l-27.1,33l-46.5,57.8 c0,0-21.3,26.6-16.6,59.4s29.1,48.7,48,55.1c18.9,6.4,48,8.5,71.6-14.7C336.4,238.4,335.6,204.3,335.6,204.3z" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", } } /> </g> </svg> </span> </MattermostLogo> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title </div> some body <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `; exports[`components/SystemNotice should match snapshot when a custom icon is passed 1`] = ` <SystemNotice actions={ Object { "dismissNotice": [MockFunction], "getStandardAnalytics": [MockFunction], "savePreferences": [MockFunction], } } analytics={ Object { "TOTAL_USERS": 300, } } config={Object {}} currentUserId="someid" dismissedNotices={Object {}} intl={ Object { "formatMessage": [MockFunction], } } isSystemAdmin={false} license={ Object { "IsLicensed": "true", } } notices={ Array [ Object { "adminOnly": false, "allowForget": true, "body": "some body", "icon": <span> icon </span>, "name": "notice1", "show": [Function], "title": "some title", }, ] } preferences={Object {}} serverVersion="5.1" > <div className="system-notice bg--white" > <div className="system-notice__logo" > <span> icon </span> </div> <div className="system-notice__body" > <div className="system-notice__title" > some title </div> some body <div className="system-notice__footer" > <button className="btn btn-sm btn-primary" id="systemnotice_remindme" onClick={[Function]} > <FormattedMessage defaultMessage="Remind Me Later" id="system_notice.remind_me" > <span> Remind Me Later </span> </FormattedMessage> </button> <button className="btn btn-sm btn-tertiary" id="systemnotice_dontshow" onClick={[Function]} > <FormattedMessage defaultMessage="Don't Show Again" id="system_notice.dont_show" > <span> Don't Show Again </span> </FormattedMessage> </button> </div> </div> </div> </SystemNotice> `;
3,277
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_controller
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_controller/actions/index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as teamsActions from 'mattermost-redux/actions/teams'; import * as teamActions from 'actions/team_actions'; import {joinTeam} from 'components/team_controller/actions'; import mockStore from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; describe('components/team_controller/actions', () => { const testUserId = 'test_user_id'; const testUser = TestHelper.getUserMock({id: testUserId}); const testTeamId = 'test_team_id'; const testTeam = TestHelper.getTeamMock({id: testTeamId}); const initialState = { entities: { users: { profiles: { [testUserId]: testUser, }, currentUserId: testUserId, }, general: { license: {}, config: {}, }, preferences: { myPreferences: {}, }, }, requests: { channels: { getChannelsMembersCategories: { status: 'not_started', error: null, }, }, }, }; describe('joinTeam', () => { test('should not allow joining a deleted team', async () => { const getTeamByNameFn = () => () => Promise.resolve({data: {...testTeam, delete_at: 154545}}); jest.spyOn(teamsActions, 'getTeamByName').mockImplementation(getTeamByNameFn); const testStore = mockStore(initialState); const result = await testStore.dispatch(joinTeam(testTeam.name, false)); expect(result).toEqual({error: Error('Team not found or deleted')}); }); test('should not allow joining a team when user cannot be added to it', async () => { const getTeamByNameFn = () => () => Promise.resolve({data: testTeam}); jest.spyOn(teamsActions, 'getTeamByName').mockImplementation(getTeamByNameFn); const addUserToTeamFn = () => () => Promise.resolve({error: {message: 'cannot add user to team'}}); jest.spyOn(teamActions, 'addUserToTeam').mockImplementation(addUserToTeamFn); const testStore = mockStore(initialState); const result = await testStore.dispatch(joinTeam(testTeam.name, false)); expect(result).toEqual({error: {message: 'cannot add user to team'}}); }); }); });
3,280
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_general_tab/open_invite.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 OpenInvite from './open_invite'; describe('components/TeamSettings/OpenInvite', () => { const patchTeam = jest.fn().mockReturnValue({data: true}); const onToggle = jest.fn().mockReturnValue({data: true}); const defaultProps = { teamId: 'team_id', isActive: false, isGroupConstrained: false, allowOpenInvite: false, patchTeam, onToggle, }; test('should match snapshot on non active without groupConstrained', () => { const props = {...defaultProps}; const wrapper = shallow(<OpenInvite {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on non active allowing open invite', () => { const props = {...defaultProps, allowOpenInvite: true}; const wrapper = shallow(<OpenInvite {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on non active with groupConstrained', () => { const props = {...defaultProps, isGroupConstrained: true}; const wrapper = shallow(<OpenInvite {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on active without groupConstrained', () => { const props = {...defaultProps, isActive: true}; const wrapper = shallow(<OpenInvite {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on active with groupConstrained', () => { const props = {...defaultProps, isActive: true, isGroupConstrained: true}; const wrapper = shallow(<OpenInvite {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
3,283
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_general_tab/team_general_tab.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 {ChangeEvent, ComponentProps} from 'react'; import {GeneralTab} from 'components/team_general_tab/team_general_tab'; import {type MockIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; describe('components/TeamSettings', () => { const getTeam = jest.fn().mockResolvedValue({data: true}); const patchTeam = jest.fn().mockReturnValue({data: true}); const regenerateTeamInviteId = jest.fn().mockReturnValue({data: true}); const removeTeamIcon = jest.fn().mockReturnValue({data: true}); const setTeamIcon = jest.fn().mockReturnValue({data: true}); const baseActions = { getTeam, patchTeam, regenerateTeamInviteId, removeTeamIcon, setTeamIcon, }; const defaultProps: ComponentProps<typeof GeneralTab> = { team: TestHelper.getTeamMock({id: 'team_id'}), maxFileSize: 50, activeSection: 'team_icon', intl: { formatMessage: jest.fn(), } as MockIntl, updateSection: jest.fn(), closeModal: jest.fn(), collapseModal: jest.fn(), actions: baseActions, canInviteTeamMembers: true, isMobileView: false, }; test('should handle bad updateTeamIcon function call', () => { const wrapper = shallow<GeneralTab>(<GeneralTab {...defaultProps}/>); wrapper.instance().updateTeamIcon(null as unknown as ChangeEvent<HTMLInputElement>); expect(wrapper.state('clientError')).toEqual('An error occurred while selecting the image.'); }); test('should handle invalid file selection', () => { const wrapper = shallow<GeneralTab>(<GeneralTab {...defaultProps}/>); wrapper.instance().updateTeamIcon({ target: { files: [{ type: 'text/plain', }], }, } as unknown as ChangeEvent<HTMLInputElement>); expect(wrapper.state('clientError')).toEqual('Only BMP, JPG or PNG images may be used for team icons'); }); test('should handle too large files', () => { const wrapper = shallow<GeneralTab>(<GeneralTab {...defaultProps}/>); wrapper.instance().updateTeamIcon({ target: { files: [{ type: 'image/jpeg', size: defaultProps.maxFileSize + 1, }], }, } as unknown as ChangeEvent<HTMLInputElement>); expect(wrapper.state('clientError')).toEqual('Unable to upload team icon. File is too large.'); }); test('should call actions.setTeamIcon on handleTeamIconSubmit', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); let teamIconFile = null; wrapper.setState({teamIconFile, submitActive: true}); wrapper.instance().handleTeamIconSubmit(); expect(actions.setTeamIcon).not.toHaveBeenCalled(); teamIconFile = {file: 'team_icon_file'} as unknown as File; wrapper.setState({teamIconFile, submitActive: false}); wrapper.instance().handleTeamIconSubmit(); expect(actions.setTeamIcon).not.toHaveBeenCalled(); wrapper.setState({teamIconFile, submitActive: true}); wrapper.instance().handleTeamIconSubmit(); expect(actions.setTeamIcon).toHaveBeenCalledTimes(1); expect(actions.setTeamIcon).toHaveBeenCalledWith(props.team?.id, teamIconFile); }); test('should call actions.removeTeamIcon on handleTeamIconRemove', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); wrapper.instance().handleTeamIconRemove(); expect(actions.removeTeamIcon).toHaveBeenCalledTimes(1); expect(actions.removeTeamIcon).toHaveBeenCalledWith(props.team?.id); }); test('hide invite code if no permissions for team inviting', () => { const props = {...defaultProps, canInviteTeamMembers: false}; const wrapper1 = shallow(<GeneralTab {...defaultProps}/>); const wrapper2 = shallow(<GeneralTab {...props}/>); expect(wrapper1).toMatchSnapshot(); expect(wrapper2).toMatchSnapshot(); }); test('should call actions.patchTeam on handleAllowedDomainsSubmit', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); wrapper.instance().handleAllowedDomainsSubmit(); expect(actions.patchTeam).toHaveBeenCalledTimes(1); expect(actions.patchTeam).toHaveBeenCalledWith({ allowed_domains: '', id: props.team?.id, }); }); test('should call actions.patchTeam on handleNameSubmit', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; if (props.team) { props.team.display_name = 'TestTeam'; } const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); wrapper.instance().handleNameSubmit(); expect(actions.patchTeam).toHaveBeenCalledTimes(1); expect(actions.patchTeam).toHaveBeenCalledWith({ display_name: props.team?.display_name, id: props.team?.id, }); }); test('should call actions.patchTeam on handleInviteIdSubmit', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; if (props.team) { props.team.invite_id = '12345'; } const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); wrapper.instance().handleInviteIdSubmit(); expect(actions.regenerateTeamInviteId).toHaveBeenCalledTimes(1); expect(actions.regenerateTeamInviteId).toHaveBeenCalledWith(props.team?.id); }); test('should call actions.patchTeam on handleDescriptionSubmit', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); const newDescription = 'The Test Team'; wrapper.setState({description: newDescription}); wrapper.instance().handleDescriptionSubmit(); if (props.team) { props.team.description = newDescription; } expect(actions.patchTeam).toHaveBeenCalledTimes(1); expect(actions.patchTeam).toHaveBeenCalledWith({ description: newDescription, id: props.team?.id, }); }); test('should match snapshot when team is group constrained', () => { const props = {...defaultProps}; if (props.team) { props.team.group_constrained = true; } const wrapper = shallow(<GeneralTab {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should call actions.getTeam on handleUpdateSection if invite_id is empty', () => { const actions = {...baseActions}; const props = {...defaultProps, actions}; if (props.team) { props.team.invite_id = ''; } const wrapper = shallow<GeneralTab>(<GeneralTab {...props}/>); wrapper.instance().handleUpdateSection('invite_id'); expect(actions.getTeam).toHaveBeenCalledTimes(1); expect(actions.getTeam).toHaveBeenCalledWith(props.team?.id); }); });
3,285
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_general_tab
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_general_tab/__snapshots__/open_invite.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/TeamSettings/OpenInvite should match snapshot on active with groupConstrained 1`] = ` <SettingItemMax containerStyle="" infoPosition="bottom" inputs={ Array [ <div> <div> <Memo(MemoizedFormattedMessage) defaultMessage="No, members of this team are added and removed by linked groups. <link>Learn More</link>" id="team_settings.openInviteDescription.groupConstrained" values={ Object { "link": [Function], } } /> </div> </div>, ] } saving={false} section="" serverError="" submit={[Function]} title="Allow any user with an account on this server to join this team" updateSection={[Function]} /> `; exports[`components/TeamSettings/OpenInvite should match snapshot on active without groupConstrained 1`] = ` <SettingItemMax containerStyle="" infoPosition="bottom" inputs={ Array [ <fieldset> <legend className="form-legend hidden-label" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Code" id="team_settings.openInviteDescription.ariaLabel" /> </legend> <div className="radio" > <label> <input defaultChecked={false} id="teamOpenInvite" name="userOpenInviteOptions" onChange={[Function]} type="radio" /> <Memo(MemoizedFormattedMessage) defaultMessage="Yes" id="general_tab.yes" /> </label> <br /> </div> <div className="radio" > <label> <input defaultChecked={true} id="teamOpenInviteNo" name="userOpenInviteOptions" onChange={[Function]} type="radio" /> <Memo(MemoizedFormattedMessage) defaultMessage="No" id="general_tab.no" /> </label> <br /> </div> <div className="mt-5" > <Memo(MemoizedFormattedMessage) defaultMessage="When allowed, a link to this team will be included on the landing page allowing anyone with an account to join this team. Changing from \\"Yes\\" to \\"No\\" will regenerate the invitation code, create a new invitation link and invalidate the previous link." id="general_tab.openInviteDesc" /> </div> </fieldset>, ] } saving={false} section="" serverError="" submit={[Function]} title="Allow any user with an account on this server to join this team" updateSection={[Function]} /> `; exports[`components/TeamSettings/OpenInvite should match snapshot on non active allowing open invite 1`] = ` <SettingItemMin describe="Yes" section="open_invite" title="Allow any user with an account on this server to join this team" updateSection={[Function]} /> `; exports[`components/TeamSettings/OpenInvite should match snapshot on non active with groupConstrained 1`] = ` <SettingItemMin describe="No, members of this team are added and removed by linked groups." section="open_invite" title="Allow any user with an account on this server to join this team" updateSection={[Function]} /> `; exports[`components/TeamSettings/OpenInvite should match snapshot on non active without groupConstrained 1`] = ` <SettingItemMin describe="No" section="open_invite" title="Allow any user with an account on this server to join this team" updateSection={[Function]} /> `;
3,286
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_general_tab
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_general_tab/__snapshots__/team_general_tab.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/TeamSettings hide invite code if no permissions for team inviting 1`] = ` <div> <div className="modal-header" > <button aria-label="Close" className="close" data-dismiss="modal" id="closeButton" onClick={[MockFunction]} type="button" > <span aria-hidden="true" > × </span> </button> <h4 className="modal-title" > <div className="modal-back" > <span onClick={[MockFunction]} > <BackIcon /> </span> </div> <MemoizedFormattedMessage defaultMessage="General Settings" id="general_tab.title" /> </h4> </div> <div className="user-settings" > <div className="GeneralTab__header" > <h3> <MemoizedFormattedMessage defaultMessage="General Settings" id="general_tab.title" /> </h3> <LearnAboutTeamsLink /> </div> <div className="divider-dark first" /> <SettingItemMin describe="name" section="name" title="Team Name" updateSection={[Function]} /> <div className="divider-light" /> <SettingItemMin describe="" section="description" title="Team Description" updateSection={[Function]} /> <div className="divider-light" /> <SettingPicture clientError="" file={null} helpText={ <Memo(MemoizedFormattedMessage) defaultMessage="Upload a team icon in BMP, JPG or PNG format.\\\\nSquare images with a solid background color are recommended." id="setting_picture.help.team" /> } imageContext="team" loadingPicture={false} onFileChange={[Function]} onRemove={[Function]} onSubmit={[Function]} serverError="" src={null} submitActive={false} title="Team Icon" updateSection={[Function]} /> <div className="divider-light" /> <SettingItemMin describe="" section="allowed_domains" title="allowedDomains" updateSection={[Function]} /> <div className="divider-light" /> <OpenInvite allowOpenInvite={false} isActive={false} isGroupConstrained={false} onToggle={[Function]} patchTeam={[MockFunction]} teamId="team_id" /> <div className="divider-light" /> <SettingItemMin describe="Click 'Edit' to regenerate Invite Code." section="invite_id" title="Invite Code" updateSection={[Function]} /> <div className="divider-dark" /> </div> </div> `; exports[`components/TeamSettings hide invite code if no permissions for team inviting 2`] = ` <div> <div className="modal-header" > <button aria-label="Close" className="close" data-dismiss="modal" id="closeButton" onClick={[MockFunction]} type="button" > <span aria-hidden="true" > × </span> </button> <h4 className="modal-title" > <div className="modal-back" > <span onClick={[MockFunction]} > <BackIcon /> </span> </div> <MemoizedFormattedMessage defaultMessage="General Settings" id="general_tab.title" /> </h4> </div> <div className="user-settings" > <div className="GeneralTab__header" > <h3> <MemoizedFormattedMessage defaultMessage="General Settings" id="general_tab.title" /> </h3> <LearnAboutTeamsLink /> </div> <div className="divider-dark first" /> <SettingItemMin describe="name" section="name" title="Team Name" updateSection={[Function]} /> <div className="divider-light" /> <SettingItemMin describe="" section="description" title="Team Description" updateSection={[Function]} /> <div className="divider-light" /> <SettingPicture clientError="" file={null} helpText={ <Memo(MemoizedFormattedMessage) defaultMessage="Upload a team icon in BMP, JPG or PNG format.\\\\nSquare images with a solid background color are recommended." id="setting_picture.help.team" /> } imageContext="team" loadingPicture={false} onFileChange={[Function]} onRemove={[Function]} onSubmit={[Function]} serverError="" src={null} submitActive={false} title="Team Icon" updateSection={[Function]} /> <div className="divider-light" /> <SettingItemMin describe="" section="allowed_domains" title="allowedDomains" updateSection={[Function]} /> <div className="divider-light" /> <OpenInvite allowOpenInvite={false} isActive={false} isGroupConstrained={false} onToggle={[Function]} patchTeam={[MockFunction]} teamId="team_id" /> <div className="divider-light" /> <div className="divider-dark" /> </div> </div> `; exports[`components/TeamSettings should match snapshot when team is group constrained 1`] = ` <div> <div className="modal-header" > <button aria-label="Close" className="close" data-dismiss="modal" id="closeButton" onClick={[MockFunction]} type="button" > <span aria-hidden="true" > × </span> </button> <h4 className="modal-title" > <div className="modal-back" > <span onClick={[MockFunction]} > <BackIcon /> </span> </div> <MemoizedFormattedMessage defaultMessage="General Settings" id="general_tab.title" /> </h4> </div> <div className="user-settings" > <div className="GeneralTab__header" > <h3> <MemoizedFormattedMessage defaultMessage="General Settings" id="general_tab.title" /> </h3> <LearnAboutTeamsLink /> </div> <div className="divider-dark first" /> <SettingItemMin describe="TestTeam" section="name" title="Team Name" updateSection={[Function]} /> <div className="divider-light" /> <SettingItemMin describe="The Test Team" section="description" title="Team Description" updateSection={[Function]} /> <div className="divider-light" /> <SettingPicture clientError="" file={null} helpText={ <Memo(MemoizedFormattedMessage) defaultMessage="Upload a team icon in BMP, JPG or PNG format.\\\\nSquare images with a solid background color are recommended." id="setting_picture.help.team" /> } imageContext="team" loadingPicture={false} onFileChange={[Function]} onRemove={[Function]} onSubmit={[Function]} serverError="" src={null} submitActive={false} title="Team Icon" updateSection={[Function]} /> <div className="divider-light" /> <OpenInvite allowOpenInvite={false} isActive={false} isGroupConstrained={true} onToggle={[Function]} patchTeam={[MockFunction]} teamId="team_id" /> <div className="divider-dark" /> </div> </div> `;
3,290
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_members_dropdown/team_members_dropdown.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 TeamMembersDropdown from 'components/team_members_dropdown/team_members_dropdown'; import {TestHelper} from 'utils/test_helper'; describe('components/team_members_dropdown', () => { const user = TestHelper.getUserMock({id: 'user-1', username: 'username1', roles: 'team_admin', is_bot: false}); const user2 = TestHelper.getUserMock({id: 'user-2', username: 'username2', roles: 'team_admin', is_bot: false}); const bot = TestHelper.getUserMock({id: 'bot-user', username: 'bot', roles: 'system_user', is_bot: true}); const team = TestHelper.getTeamMock({type: 'O', allowed_domains: '', allow_open_invite: false, scheme_id: undefined}); const baseProps = { user: user2, currentUser: user, teamMember: TestHelper.getTeamMembershipMock({roles: 'channel_admin', scheme_admin: true}), teamUrl: '', currentTeam: team, index: 0, totalUsers: 10, collapsedThreads: true, actions: { getMyTeamMembers: jest.fn(), getMyTeamUnreads: jest.fn(), getUser: jest.fn(), getTeamMember: jest.fn(), getTeamStats: jest.fn(), getChannelStats: jest.fn(), updateTeamMemberSchemeRoles: jest.fn(), removeUserFromTeamAndGetStats: jest.fn(), updateUserActive: jest.fn(), }, }; test('should match snapshot for team_members_dropdown', () => { const wrapper = shallow( <TeamMembersDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot opening dropdown upwards', () => { const wrapper = shallow( <TeamMembersDropdown {...baseProps} index={4} totalUsers={5} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with group-constrained team', () => { baseProps.currentTeam.group_constrained = true; const wrapper = shallow( <TeamMembersDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for a bot with group-constrained team', () => { baseProps.currentTeam.group_constrained = true; baseProps.user = bot; const wrapper = shallow( <TeamMembersDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,292
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_members_dropdown
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_members_dropdown/__snapshots__/team_members_dropdown.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/team_members_dropdown should match snapshot for a bot with group-constrained team 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button aria-expanded="true" className="dropdown-toggle theme color--link style--none" id="teamMembersDropdown_bot" type="button" > <span> <MemoizedFormattedMessage defaultMessage="Team Admin" id="team_members_dropdown.teamAdmin" /> </span> <DropdownIcon /> </button> <div> <Menu ariaLabel="Change the role of a team member" openLeft={true} openUp={false} > <MenuItemAction id="removeFromTeam" onClick={[Function]} show={true} text="Remove From Team" /> <MenuItemAction onClick={[Function]} show={true} text="Make Member" /> </Menu> </div> </MenuWrapper> `; exports[`components/team_members_dropdown should match snapshot for team_members_dropdown 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button aria-expanded="true" className="dropdown-toggle theme color--link style--none" id="teamMembersDropdown_username2" type="button" > <span> <MemoizedFormattedMessage defaultMessage="Team Admin" id="team_members_dropdown.teamAdmin" /> </span> <DropdownIcon /> </button> <div> <Menu ariaLabel="Change the role of a team member" openLeft={true} openUp={false} > <MenuItemAction id="removeFromTeam" onClick={[Function]} show={true} text="Remove From Team" /> <MenuItemAction onClick={[Function]} show={true} text="Make Member" /> </Menu> </div> </MenuWrapper> `; exports[`components/team_members_dropdown should match snapshot opening dropdown upwards 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button aria-expanded="true" className="dropdown-toggle theme color--link style--none" id="teamMembersDropdown_username2" type="button" > <span> <MemoizedFormattedMessage defaultMessage="Team Admin" id="team_members_dropdown.teamAdmin" /> </span> <DropdownIcon /> </button> <div> <Menu ariaLabel="Change the role of a team member" openLeft={true} openUp={true} > <MenuItemAction id="removeFromTeam" onClick={[Function]} show={true} text="Remove From Team" /> <MenuItemAction onClick={[Function]} show={true} text="Make Member" /> </Menu> </div> </MenuWrapper> `; exports[`components/team_members_dropdown should match snapshot with group-constrained team 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button aria-expanded="true" className="dropdown-toggle theme color--link style--none" id="teamMembersDropdown_username2" type="button" > <span> <MemoizedFormattedMessage defaultMessage="Team Admin" id="team_members_dropdown.teamAdmin" /> </span> <DropdownIcon /> </button> <div> <Menu ariaLabel="Change the role of a team member" openLeft={true} openUp={false} > <MenuItemAction onClick={[Function]} show={true} text="Make Member" /> </Menu> </div> </MenuWrapper> `;
3,294
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_members_modal/team_members_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 {Modal} from 'react-bootstrap'; import {TestHelper} from 'utils/test_helper'; import TeamMembersModal from './team_members_modal'; describe('components/TeamMembersModal', () => { const baseProps = { currentTeam: TestHelper.getTeamMock({ id: 'id', display_name: 'display name', }), onExited: jest.fn(), onLoad: jest.fn(), actions: { openModal: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <TeamMembersModal {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should call onHide on Modal\'s onExited', () => { const wrapper = shallow( <TeamMembersModal {...baseProps} />, ); const modalProps = wrapper.find(Modal).first().props(); if (modalProps.onExited) { modalProps.onExited(document.createElement('div')); } expect(baseProps.onExited).toHaveBeenCalledTimes(1); }); });
3,296
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_members_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_members_modal/__snapshots__/team_members_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/TeamMembersModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="teamMemberModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal" dialogComponentClass={[Function]} enforceFocus={true} id="teamMembersModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} 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="teamMemberModalLabel" > <MemoizedFormattedMessage defaultMessage="{team} Members" id="team_member_modal.members" values={ Object { "team": "display name", } } /> </ModalTitle> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="id" > <button className="btn btn-primary btn-sm invite-people-btn" id="invitePeople" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Invite People" id="team_member_modal.invitePeople" /> </button> </Connect(TeamPermissionGate)> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <Connect(MemberListTeam) teamId="id" /> </ModalBody> </Modal> `;
3,298
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_selector_modal/team_selector_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 {TestHelper} from 'utils/test_helper'; import TeamSelectorModal from './team_selector_modal'; import type {Props} from './team_selector_modal'; describe('components/TeamSelectorModal', () => { const defaultProps: Props = { currentSchemeId: 'xxx', alreadySelected: ['id1'], searchTerm: '', teams: [ TestHelper.getTeamMock({ id: 'id1', delete_at: 0, scheme_id: '', display_name: 'Team 1', }), TestHelper.getTeamMock({ id: 'id2', delete_at: 123, scheme_id: '', display_name: 'Team 2', }), TestHelper.getTeamMock({ id: 'id3', delete_at: 0, scheme_id: 'test', display_name: 'Team 3', }), TestHelper.getTeamMock({ id: 'id4', delete_at: 0, scheme_id: '', display_name: 'Team 4', group_constrained: false, }), TestHelper.getTeamMock({ id: 'id5', delete_at: 0, scheme_id: '', display_name: 'Team 5', group_constrained: true, }), ], onModalDismissed: jest.fn(), onTeamsSelected: jest.fn(), actions: { loadTeams: jest.fn().mockResolvedValue({data: []}), setModalSearchTerm: jest.fn(() => Promise.resolve()), searchTeams: jest.fn(() => Promise.resolve()), }, }; test('should match snapshot', () => { const wrapper = shallow(<TeamSelectorModal {...defaultProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should hide group constrained teams when excludeGroupConstrained is true', () => { const wrapper = shallow( <TeamSelectorModal {...defaultProps}/>, ); wrapper.setProps({excludeGroupConstrained: true}); expect(wrapper).toMatchSnapshot(); }); });
3,300
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_selector_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_selector_modal/__snapshots__/team_selector_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/TeamSelectorModal should hide group constrained teams when excludeGroupConstrained is true 1`] = ` <Modal animation={true} aria-labelledby="teamSelectorModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels team-selector-modal" dialogComponentClass={[Function]} enforceFocus={true} 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} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="teamSelectorModalLabel" > <FormattedMarkdownMessage defaultMessage="Add Teams to **Team Selection** List" id="add_teams_to_scheme.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Yes, Move Team" id="add_teams_to_scheme.confirmation.accept" /> } message={ <Memo(MemoizedFormattedMessage) defaultMessage="This team is already selected in another team scheme, are you sure you want to move it to this team scheme?" id="add_teams_to_scheme.confirmation.message" /> } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={false} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Team Override Scheme Change?" id="add_teams_to_scheme.confirmation.title" /> } /> <MultiSelect ariaLabelRenderer={[Function]} buttonSubmitText="Add" focusOnLoad={true} handleAdd={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addTeamsToSchemeKey" loading={true} numRemainingText={ <Memo(MemoizedFormattedMessage) defaultMessage="Use ↑↓ to browse, ↵ to select." id="multiselect.selectTeams" /> } optionRenderer={[Function]} options={ Array [ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "Team 3", "email": "", "group_constrained": false, "id": "id3", "invite_id": "", "label": "DN", "name": "DN", "scheme_id": "test", "type": "O", "update_at": 0, "value": "id3", }, Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "Team 4", "email": "", "group_constrained": false, "id": "id4", "invite_id": "", "label": "DN", "name": "DN", "scheme_id": "", "type": "O", "update_at": 0, "value": "id4", }, ] } perPage={50} placeholderText="Search and add teams" saveButtonPosition="top" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueRenderer={[Function]} valueWithImage={false} values={Array []} /> </ModalBody> </Modal> `; exports[`components/TeamSelectorModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="teamSelectorModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels team-selector-modal" dialogComponentClass={[Function]} enforceFocus={true} 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} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="teamSelectorModalLabel" > <FormattedMarkdownMessage defaultMessage="Add Teams to **Team Selection** List" id="add_teams_to_scheme.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Yes, Move Team" id="add_teams_to_scheme.confirmation.accept" /> } message={ <Memo(MemoizedFormattedMessage) defaultMessage="This team is already selected in another team scheme, are you sure you want to move it to this team scheme?" id="add_teams_to_scheme.confirmation.message" /> } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={false} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Team Override Scheme Change?" id="add_teams_to_scheme.confirmation.title" /> } /> <MultiSelect ariaLabelRenderer={[Function]} buttonSubmitText="Add" focusOnLoad={true} handleAdd={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addTeamsToSchemeKey" loading={true} numRemainingText={ <Memo(MemoizedFormattedMessage) defaultMessage="Use ↑↓ to browse, ↵ to select." id="multiselect.selectTeams" /> } optionRenderer={[Function]} options={ Array [ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "Team 3", "email": "", "group_constrained": false, "id": "id3", "invite_id": "", "label": "DN", "name": "DN", "scheme_id": "test", "type": "O", "update_at": 0, "value": "id3", }, Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "Team 4", "email": "", "group_constrained": false, "id": "id4", "invite_id": "", "label": "DN", "name": "DN", "scheme_id": "", "type": "O", "update_at": 0, "value": "id4", }, Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "Team 5", "email": "", "group_constrained": true, "id": "id5", "invite_id": "", "label": "DN", "name": "DN", "scheme_id": "", "type": "O", "update_at": 0, "value": "id5", }, ] } perPage={50} placeholderText="Search and add teams" saveButtonPosition="top" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueRenderer={[Function]} valueWithImage={false} values={Array []} /> </ModalBody> </Modal> `;
3,304
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_settings_modal/team_settings_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 TeamSettingsModal from 'components/team_settings_modal/team_settings_modal'; describe('components/team_settings_modal', () => { const baseProps = { isCloud: false, onExited: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <TeamSettingsModal {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should call onExited callback when the modal is hidden', () => { const wrapper = shallow( <TeamSettingsModal {...baseProps} />, ); (wrapper.instance() as TeamSettingsModal).handleHidden(); expect(baseProps.onExited).toHaveBeenCalledTimes(1); }); });
3,306
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_settings_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_settings_modal/__snapshots__/team_settings_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/team_settings_modal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="teamSettingsModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal settings-modal settings-modal--action" dialogComponentClass={[Function]} enforceFocus={true} id="teamSettingsModal" 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} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" id="teamSettingsModalLabel" > <ModalTitle bsClass="modal-title" componentClass="h1" > <MemoizedFormattedMessage defaultMessage="Team Settings" id="team_settings_modal.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="settings-table" > <div className="settings-links" > <Suspense fallback={null} > <lazy activeTab="general" tabs={ Array [ Object { "icon": "icon icon-settings-outline", "iconTitle": "Settings Icon", "name": "general", "uiName": "General", }, ] } updateTab={[Function]} /> </Suspense> </div> <div className="settings-content minimize-settings" > <Connect(TeamSettings) activeSection="" activeTab="general" closeModal={[Function]} collapseModal={[Function]} updateSection={[Function]} /> </div> </div> </ModalBody> </Modal> `;
3,309
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/team_sidebar/components/team_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {BrowserRouter as Router} from 'react-router-dom'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import TeamButton from './team_button'; describe('components/TeamSidebar/TeamButton', () => { const baseProps = { btnClass: '', url: '', displayName: '', tip: '', order: 0, showOrder: false, active: false, disabled: false, unread: false, mentions: 0, teamIconUrl: null, switchTeam: () => {}, isDraggable: false, teamIndex: 0, teamId: '', isInProduct: false, }; it('should show unread badge and set class when unread in channels', () => { const props = { ...baseProps, active: false, unread: true, }; const wrapper = mountWithIntl( <Router> <TeamButton {...props}/> </Router>, ); expect(wrapper.find('.unread-badge').exists()).toBe(true); expect(wrapper.find('.team-container.unread').exists()).toBe(true); }); it('should hide unread badge and set no class when unread in a product', () => { const props = { ...baseProps, active: false, unread: true, isInProduct: true, }; const wrapper = mountWithIntl( <Router> <TeamButton {...props}/> </Router>, ); expect(wrapper.find('.unread-badge').exists()).toBe(false); expect(wrapper.find('.team-container.unread').exists()).toBe(false); }); it('should show mentions badge and set class when mentions in channels', () => { const props = { ...baseProps, active: false, unread: true, mentions: 1, }; const wrapper = mountWithIntl( <Router> <TeamButton {...props}/> </Router>, ); expect(wrapper.find('.badge.badge-max-number').exists()).toBe(true); expect(wrapper.find('.team-container.unread').exists()).toBe(true); }); it('should hide mentions badge and set no class when mentions in product', () => { const props = { ...baseProps, active: false, unread: true, mentions: 1, isInProduct: true, }; const wrapper = mountWithIntl( <Router> <TeamButton {...props}/> </Router>, ); expect(wrapper.find('.badge.badge-max-number').exists()).toBe(false); expect(wrapper.find('.team-container.unread').exists()).toBe(false); }); });
3,312
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/terms_of_service/terms_of_service.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 {emitUserLoggedOutEvent} from 'actions/global_actions'; import type EmojiMap from 'utils/emoji_map'; import TermsOfService from './terms_of_service'; import type {TermsOfServiceProps} from './terms_of_service'; jest.mock('actions/global_actions', () => ({ emitUserLoggedOutEvent: jest.fn(), redirectUserToDefaultTeam: jest.fn(), })); describe('components/terms_of_service/TermsOfService', () => { const getTermsOfService = jest.fn().mockResolvedValue({data: {id: 'tos_id', text: 'tos_text'}}); const updateMyTermsOfServiceStatus = jest.fn().mockResolvedValue({data: true}); const baseProps: TermsOfServiceProps = { actions: { getTermsOfService, updateMyTermsOfServiceStatus, }, location: {search: ''}, termsEnabled: true, emojiMap: {} as EmojiMap, onboardingFlowEnabled: false, }; test('should match snapshot', () => { const props = {...baseProps}; const wrapper = shallow<TermsOfService>(<TermsOfService {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should call getTermsOfService on mount', () => { const props = {...baseProps}; shallow<TermsOfService>(<TermsOfService {...props}/>); expect(props.actions.getTermsOfService).toHaveBeenCalledTimes(1); }); test('should match snapshot on loading', () => { const props = {...baseProps}; const wrapper = shallow<TermsOfService>(<TermsOfService {...props}/>); wrapper.setState({loading: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on accept terms', () => { const props = {...baseProps}; const wrapper = shallow<TermsOfService>(<TermsOfService {...props}/>); wrapper.setState({loadingAgree: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on reject terms', () => { const props = {...baseProps}; const wrapper = shallow<TermsOfService>(<TermsOfService {...props}/>); wrapper.setState({loadingDisagree: true}); expect(wrapper).toMatchSnapshot(); }); test('should call updateTermsOfServiceStatus on registerUserAction', async () => { const wrapper = shallow<TermsOfService>(<TermsOfService {...baseProps}/>); await wrapper.instance().registerUserAction(true, jest.fn()); expect(baseProps.actions.updateMyTermsOfServiceStatus).toHaveBeenCalledTimes(1); }); test('should match state and call updateTermsOfServiceStatus on handleAcceptTerms', () => { const wrapper = shallow<TermsOfService>(<TermsOfService {...baseProps}/>); wrapper.instance().handleAcceptTerms(); expect(wrapper.state('loadingAgree')).toEqual(true); expect(wrapper.state('serverError')).toEqual(null); expect(baseProps.actions.updateMyTermsOfServiceStatus).toHaveBeenCalledTimes(1); }); test('should match state and call updateTermsOfServiceStatus on handleRejectTerms', () => { const wrapper = shallow<TermsOfService>(<TermsOfService {...baseProps}/>); wrapper.instance().handleRejectTerms(); expect(wrapper.state('loadingDisagree')).toEqual(true); expect(wrapper.state('serverError')).toEqual(null); expect(baseProps.actions.updateMyTermsOfServiceStatus).toHaveBeenCalledTimes(1); }); test('should call emitUserLoggedOutEvent on handleLogoutClick', () => { const wrapper = shallow<TermsOfService>(<TermsOfService {...baseProps}/>); wrapper.instance().handleLogoutClick({preventDefault: jest.fn()} as unknown as React.MouseEvent<HTMLAnchorElement, MouseEvent>); expect(emitUserLoggedOutEvent).toHaveBeenCalledTimes(1); expect(emitUserLoggedOutEvent).toHaveBeenCalledWith('/login'); }); });
3,314
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/terms_of_service
petrpan-code/mattermost/mattermost/webapp/channels/src/components/terms_of_service/__snapshots__/terms_of_service.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/terms_of_service/TermsOfService should match snapshot 1`] = `<LoadingScreen />`; exports[`components/terms_of_service/TermsOfService should match snapshot on loading 1`] = `<LoadingScreen />`; exports[`components/terms_of_service/TermsOfService should match snapshot, on accept terms 1`] = `<LoadingScreen />`; exports[`components/terms_of_service/TermsOfService should match snapshot, on reject terms 1`] = `<LoadingScreen />`;
3,323
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/channel_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/channel_threads/thread_footer/thread_footer.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 type {ComponentProps} from 'react'; import type {UserThread} from '@mattermost/types/threads'; import Timestamp from 'components/timestamp'; import SimpleTooltip from 'components/widgets/simple_tooltip'; import Avatars from 'components/widgets/users/avatars'; import {fakeDate} from 'tests/helpers/date'; import {mockStore} from 'tests/test_store'; import ThreadFooter from './thread_footer'; import FollowButton from '../../common/follow_button'; describe('components/threading/channel_threads/thread_footer', () => { const baseState = { entities: { general: { config: {}, }, users: { currentUserId: 'uid', profiles: { 1: { id: '1', username: 'first.last1', nickname: 'nickname1', first_name: 'First1', last_name: 'Last1', }, 2: { id: '2', username: 'first.last2', nickname: 'nickname2', first_name: 'First2', last_name: 'Last2', }, 3: { id: '3', username: 'first.last3', nickname: 'nickname3', first_name: 'First3', last_name: 'Last3', }, 4: { id: '4', username: 'first.last4', nickname: 'nickname4', first_name: 'First4', last_name: 'Last4', }, 5: { id: '5', username: 'first.last5', nickname: 'nickname5', first_name: 'First5', last_name: 'Last5', }, }, }, teams: { currentTeamId: 'tid', }, preferences: { myPreferences: {}, }, posts: { posts: { postthreadid: { id: 'postthreadid', reply_count: 9, last_reply_at: 1554161504000, is_following: true, channel_id: 'cid', user_id: '1', }, singlemessageid: { id: 'singlemessageid', reply_count: 0, last_reply_at: 0, is_following: true, channel_id: 'cid', user_id: '1', }, }, }, threads: { threads: { postthreadid: { id: 'postthreadid', participants: [ {id: '1'}, {id: '2'}, {id: '3'}, {id: '4'}, {id: '5'}, ], reply_count: 9, unread_replies: 0, unread_mentions: 0, last_reply_at: 1554161504000, last_viewed_at: 1554161505000, is_following: true, post: { channel_id: 'cid', user_id: '1', }, }, }, }, }, }; let resetFakeDate: () => void; let state: any; let thread: UserThread; let props: ComponentProps<typeof ThreadFooter>; beforeEach(() => { resetFakeDate = fakeDate(new Date('2020-05-03T13:20:00Z')); state = {...baseState}; thread = state.entities.threads.threads.postthreadid; props = {threadId: thread.id}; }); afterEach(() => { resetFakeDate(); }); test('should report total number of replies', () => { const {mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.exists('.dot-unreads')).toBe(false); expect(wrapper.exists('FormattedMessage[id="threading.numReplies"]')).toBe(true); }); test('should show unread indicator', () => { thread.unread_replies = 2; const {mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(SimpleTooltip).find('.dot-unreads').exists()).toBe(true); }); test('should not show unread indicator if not following', () => { thread.unread_replies = 2; thread.is_following = false; const {mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper.find(SimpleTooltip).find('.dot-unreads').exists()).toBe(false); }); test('should have avatars', () => { const {mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper.find(Avatars).props()).toHaveProperty('userIds', ['5', '4', '3', '2', '1']); }); test('should have a timestamp', () => { const {mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper.find(Timestamp).props()).toHaveProperty('value', thread.last_reply_at); }); test('should have a reply button', () => { const {store, mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); wrapper.find('button.separated').first().simulate('click'); expect(store.getActions()).toEqual([ { type: 'SELECT_POST', channelId: 'cid', postId: 'postthreadid', timestamp: 1588512000000, }, ]); }); test('should have a follow button', () => { thread.is_following = false; const {store, mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper.exists(FollowButton)).toBe(true); expect(wrapper.find(FollowButton).props()).toHaveProperty('isFollowing', thread.is_following); wrapper.find('button.separated').last().simulate('click'); expect(store.getActions()).toEqual([ { type: 'FOLLOW_CHANGED_THREAD', data: { following: true, id: 'postthreadid', team_id: 'tid', }, }, ]); }); test('should have an unfollow button', () => { thread.is_following = true; const {store, mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter {...props} />, mountOptions, ); expect(wrapper.exists(FollowButton)).toBe(true); expect(wrapper.find(FollowButton).props()).toHaveProperty('isFollowing', thread.is_following); wrapper.find('button.separated').last().simulate('click'); expect(store.getActions()).toEqual([ { type: 'FOLLOW_CHANGED_THREAD', data: { following: false, id: 'postthreadid', team_id: 'tid', }, }, ]); }); test('should match snapshot when a single message is followed', () => { const {mountOptions} = mockStore(state); const wrapper = mount( <ThreadFooter threadId='singlemessageid' />, mountOptions, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.exists(FollowButton)).toBe(true); expect(wrapper.find(FollowButton).props()).toHaveProperty('isFollowing', true); }); });
3,325
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/channel_threads/thread_footer
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/channel_threads/thread_footer/__snapshots__/thread_footer.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/channel_threads/thread_footer should match snapshot when a single message is followed 1`] = ` <Memo(ThreadFooter) threadId="singlemessageid" > <div className="ThreadFooter" > <div className="indicator" /> <Memo(FollowButton) className="separated" isFollowing={true} onClick={[Function]} > <Memo(Button) className="separated FollowButton" disabled={false} isActive={true} onClick={[Function]} > <button className="Button Button___transparent is-active separated FollowButton" disabled={false} onClick={[Function]} > <span className="Button_label" > Following </span> </button> </Memo(Button)> </Memo(FollowButton)> </div> </Memo(ThreadFooter)> `; exports[`components/threading/channel_threads/thread_footer should report total number of replies 1`] = ` <Memo(ThreadFooter) threadId="postthreadid" > <div className="ThreadFooter" > <div className="indicator" /> <Memo(Avatars) size="sm" userIds={ Array [ "5", "4", "3", "2", "1", ] } > <div className="Avatars Avatars___sm" onMouseLeave={[Function]} > <UserAvatar disableProfileOverlay={false} key="5" overlayProps={ Object { "animation": true, "delayShow": undefined, "onEntered": [Function], } } size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } userId="5" > <OverlayTrigger defaultOverlayShown={false} disabled={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hide={[Function]} src="/api/v4/users/5/image?_=0" userId="5" /> } placement="right" rootClose={true} trigger="click" > <OverlayTrigger defaultOverlayShown={false} overlay={ <OverlayWrapper className="user-profile-popover" hide={[Function]} intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } src="/api/v4/users/5/image?_=0" userId="5" /> } placement="right" rootClose={true} trigger="click" > <SimpleTooltip animation={true} content="first.last5" id="name-5" onClick={[Function]} onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="name-5" placement="top" > first.last5 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="name-5" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last5 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <RoundButton className="style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="RoundButton-dvlhqG gHOQXq style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Memo(Avatar) size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} url="/api/v4/users/5/image?_=0" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/5/image?_=0" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} /> </Memo(Avatar)> </button> </RoundButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </OverlayTrigger> </OverlayTrigger> </UserAvatar> <UserAvatar disableProfileOverlay={false} key="4" overlayProps={ Object { "animation": true, "delayShow": undefined, "onEntered": [Function], } } size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } userId="4" > <OverlayTrigger defaultOverlayShown={false} disabled={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hide={[Function]} src="/api/v4/users/4/image?_=0" userId="4" /> } placement="right" rootClose={true} trigger="click" > <OverlayTrigger defaultOverlayShown={false} overlay={ <OverlayWrapper className="user-profile-popover" hide={[Function]} intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } src="/api/v4/users/4/image?_=0" userId="4" /> } placement="right" rootClose={true} trigger="click" > <SimpleTooltip animation={true} content="first.last4" id="name-4" onClick={[Function]} onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="name-4" placement="top" > first.last4 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="name-4" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last4 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <RoundButton className="style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="RoundButton-dvlhqG gHOQXq style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Memo(Avatar) size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} url="/api/v4/users/4/image?_=0" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/4/image?_=0" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} /> </Memo(Avatar)> </button> </RoundButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </OverlayTrigger> </OverlayTrigger> </UserAvatar> <UserAvatar disableProfileOverlay={false} key="3" overlayProps={ Object { "animation": true, "delayShow": undefined, "onEntered": [Function], } } size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } userId="3" > <OverlayTrigger defaultOverlayShown={false} disabled={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hide={[Function]} src="/api/v4/users/3/image?_=0" userId="3" /> } placement="right" rootClose={true} trigger="click" > <OverlayTrigger defaultOverlayShown={false} overlay={ <OverlayWrapper className="user-profile-popover" hide={[Function]} intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } src="/api/v4/users/3/image?_=0" userId="3" /> } placement="right" rootClose={true} trigger="click" > <SimpleTooltip animation={true} content="first.last3" id="name-3" onClick={[Function]} onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="name-3" placement="top" > first.last3 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="name-3" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last3 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <RoundButton className="style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="RoundButton-dvlhqG gHOQXq style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Memo(Avatar) size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} url="/api/v4/users/3/image?_=0" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/3/image?_=0" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} /> </Memo(Avatar)> </button> </RoundButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </OverlayTrigger> </OverlayTrigger> </UserAvatar> <SimpleTooltip animation={true} content="first.last2, first.last1" id="names-overflow" onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="names-overflow" placement="top" > first.last2, first.last1 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="names-overflow" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last2, first.last1 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <Memo(Avatar) onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={0} text="+2" > <div className="Avatar Avatar-sm Avatar-plain" data-content="+2" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={0} /> </Memo(Avatar)> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </Memo(Avatars)> <Memo(Button) className="ReplyButton separated" onClick={[Function]} prepend={ <span className="icon" > <i className="icon-reply-outline" /> </span> } > <button className="Button Button___transparent ReplyButton separated" onClick={[Function]} > <span className="Button_prepended" > <span className="icon" > <i className="icon-reply-outline" /> </span> </span> <span className="Button_label" > <FormattedMessage defaultMessage="{totalReplies, plural, =0 {Reply} =1 {# reply} other {# replies}}" id="threading.numReplies" values={ Object { "totalReplies": 9, } } > <span> 9 replies </span> </FormattedMessage> </span> </button> </Memo(Button)> <Memo(FollowButton) className="separated" isFollowing={true} onClick={[Function]} > <Memo(Button) className="separated FollowButton" disabled={false} isActive={true} onClick={[Function]} > <button className="Button Button___transparent is-active separated FollowButton" disabled={false} onClick={[Function]} > <span className="Button_label" > Following </span> </button> </Memo(Button)> </Memo(FollowButton)> <Connect(injectIntl(Timestamp)) day="numeric" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} value={1554161504000} > <injectIntl(Timestamp) day="numeric" dispatch={[Function]} hourCycle="h12" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} value={1554161504000} > <Timestamp day="numeric" dispatch={[Function]} hour="numeric" hourCycle="h12" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } minute="numeric" month="long" numeric="auto" relNearest={1} second="numeric" style="long" timeZoneName="short" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} value={1554161504000} weekday="long" year="numeric" > <span className="Timestamp separated alt-visible" > <FormattedMessage defaultMessage="Last reply {formatted}" id="threading.footer.lastReplyAt" values={ Object { "formatted": <Memo(SemanticTime) value={2019-04-01T23:31:44.000Z} > April 1, 2019 </Memo(SemanticTime)>, } } > <span> Last reply <Memo(SemanticTime) key=".$.1" value={2019-04-01T23:31:44.000Z} > <time dateTime="2019-04-01T23:31:44.000" > April 1, 2019 </time> </Memo(SemanticTime)> </span> </FormattedMessage> </span> </Timestamp> </injectIntl(Timestamp)> </Connect(injectIntl(Timestamp))> </div> </Memo(ThreadFooter)> `; exports[`components/threading/channel_threads/thread_footer should show unread indicator 1`] = ` <Memo(ThreadFooter) threadId="postthreadid" > <div className="ThreadFooter" > <SimpleTooltip content={ <Memo(MemoizedFormattedMessage) defaultMessage="{newReplies, plural, =0 {no unread messages} =1 {one unread message} other {# unread messages}}" id="threading.numNewMessages" values={ Object { "newReplies": 2, } } /> } id="threadFooterIndicator" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="threadFooterIndicator" placement="top" > <Memo(MemoizedFormattedMessage) defaultMessage="{newReplies, plural, =0 {no unread messages} =1 {one unread message} other {# unread messages}}" id="threading.numNewMessages" values={ Object { "newReplies": 2, } } /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="threadFooterIndicator" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > <Memo(MemoizedFormattedMessage) defaultMessage="{newReplies, plural, =0 {no unread messages} =1 {one unread message} other {# unread messages}}" id="threading.numNewMessages" values={ Object { "newReplies": 2, } } /> </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div className="indicator" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} tabIndex={0} > <div className="dot-unreads" /> </div> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> <Memo(Avatars) size="sm" userIds={ Array [ "5", "4", "3", "2", "1", ] } > <div className="Avatars Avatars___sm" onMouseLeave={[Function]} > <UserAvatar disableProfileOverlay={false} key="5" overlayProps={ Object { "animation": true, "delayShow": undefined, "onEntered": [Function], } } size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } userId="5" > <OverlayTrigger defaultOverlayShown={false} disabled={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hide={[Function]} src="/api/v4/users/5/image?_=0" userId="5" /> } placement="right" rootClose={true} trigger="click" > <OverlayTrigger defaultOverlayShown={false} overlay={ <OverlayWrapper className="user-profile-popover" hide={[Function]} intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } src="/api/v4/users/5/image?_=0" userId="5" /> } placement="right" rootClose={true} trigger="click" > <SimpleTooltip animation={true} content="first.last5" id="name-5" onClick={[Function]} onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="name-5" placement="top" > first.last5 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="name-5" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last5 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <RoundButton className="style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="RoundButton-dvlhqG gHOQXq style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Memo(Avatar) size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} url="/api/v4/users/5/image?_=0" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/5/image?_=0" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} /> </Memo(Avatar)> </button> </RoundButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </OverlayTrigger> </OverlayTrigger> </UserAvatar> <UserAvatar disableProfileOverlay={false} key="4" overlayProps={ Object { "animation": true, "delayShow": undefined, "onEntered": [Function], } } size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } userId="4" > <OverlayTrigger defaultOverlayShown={false} disabled={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hide={[Function]} src="/api/v4/users/4/image?_=0" userId="4" /> } placement="right" rootClose={true} trigger="click" > <OverlayTrigger defaultOverlayShown={false} overlay={ <OverlayWrapper className="user-profile-popover" hide={[Function]} intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } src="/api/v4/users/4/image?_=0" userId="4" /> } placement="right" rootClose={true} trigger="click" > <SimpleTooltip animation={true} content="first.last4" id="name-4" onClick={[Function]} onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="name-4" placement="top" > first.last4 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="name-4" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last4 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <RoundButton className="style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="RoundButton-dvlhqG gHOQXq style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Memo(Avatar) size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} url="/api/v4/users/4/image?_=0" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/4/image?_=0" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} /> </Memo(Avatar)> </button> </RoundButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </OverlayTrigger> </OverlayTrigger> </UserAvatar> <UserAvatar disableProfileOverlay={false} key="3" overlayProps={ Object { "animation": true, "delayShow": undefined, "onEntered": [Function], } } size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } userId="3" > <OverlayTrigger defaultOverlayShown={false} disabled={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hide={[Function]} src="/api/v4/users/3/image?_=0" userId="3" /> } placement="right" rootClose={true} trigger="click" > <OverlayTrigger defaultOverlayShown={false} overlay={ <OverlayWrapper className="user-profile-popover" hide={[Function]} intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } src="/api/v4/users/3/image?_=0" userId="3" /> } placement="right" rootClose={true} trigger="click" > <SimpleTooltip animation={true} content="first.last3" id="name-3" onClick={[Function]} onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="name-3" placement="top" > first.last3 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onClick={[Function]} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="name-3" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last3 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <RoundButton className="style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="RoundButton-dvlhqG gHOQXq style--none" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Memo(Avatar) size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} url="/api/v4/users/3/image?_=0" > <img alt="user profile image" className="Avatar Avatar-sm" loading="lazy" onError={[Function]} src="/api/v4/users/3/image?_=0" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={-1} /> </Memo(Avatar)> </button> </RoundButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </OverlayTrigger> </OverlayTrigger> </UserAvatar> <SimpleTooltip animation={true} content="first.last2, first.last1" id="names-overflow" onEntered={[Function]} > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onEntered={[Function]} overlay={ <Tooltip className="hidden-xs" id="names-overflow" placement="top" > first.last2, first.last1 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger animation={true} defaultOverlayShown={false} delayShow={500} onEntered={[Function]} overlay={ <OverlayWrapper className="hidden-xs" id="names-overflow" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > first.last2, first.last1 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <Memo(Avatar) onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} size="sm" style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={0} text="+2" > <div className="Avatar Avatar-sm Avatar-plain" data-content="+2" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} style={ Object { "background": "rgb(240, 240, 241)", } } tabIndex={0} /> </Memo(Avatar)> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </Memo(Avatars)> <Memo(Button) className="ReplyButton separated" onClick={[Function]} prepend={ <span className="icon" > <i className="icon-reply-outline" /> </span> } > <button className="Button Button___transparent ReplyButton separated" onClick={[Function]} > <span className="Button_prepended" > <span className="icon" > <i className="icon-reply-outline" /> </span> </span> <span className="Button_label" > <FormattedMessage defaultMessage="{totalReplies, plural, =0 {Reply} =1 {# reply} other {# replies}}" id="threading.numReplies" values={ Object { "totalReplies": 9, } } > <span> 9 replies </span> </FormattedMessage> </span> </button> </Memo(Button)> <Memo(FollowButton) className="separated" isFollowing={true} onClick={[Function]} > <Memo(Button) className="separated FollowButton" disabled={false} isActive={true} onClick={[Function]} > <button className="Button Button___transparent is-active separated FollowButton" disabled={false} onClick={[Function]} > <span className="Button_label" > Following </span> </button> </Memo(Button)> </Memo(FollowButton)> <Connect(injectIntl(Timestamp)) day="numeric" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} value={1554161504000} > <injectIntl(Timestamp) day="numeric" dispatch={[Function]} hourCycle="h12" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} value={1554161504000} > <Timestamp day="numeric" dispatch={[Function]} hour="numeric" hourCycle="h12" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } minute="numeric" month="long" numeric="auto" relNearest={1} second="numeric" style="long" timeZoneName="short" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} value={1554161504000} weekday="long" year="numeric" > <span className="Timestamp separated alt-visible" > <FormattedMessage defaultMessage="Last reply {formatted}" id="threading.footer.lastReplyAt" values={ Object { "formatted": <Memo(SemanticTime) value={2019-04-01T23:31:44.000Z} > April 1, 2019 </Memo(SemanticTime)>, } } > <span> Last reply <Memo(SemanticTime) key=".$.1" value={2019-04-01T23:31:44.000Z} > <time dateTime="2019-04-01T23:31:44.000" > April 1, 2019 </time> </Memo(SemanticTime)> </span> </FormattedMessage> </span> </Timestamp> </injectIntl(Timestamp)> </Connect(injectIntl(Timestamp))> </div> </Memo(ThreadFooter)> `;
3,330
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common/button/button.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 ReplyIcon from 'components/widgets/icons/reply_icon'; import Button from './button'; describe('components/threading/common/button', () => { test('should support onClick', () => { const action = jest.fn(); const wrapper = shallow<typeof Button>( <Button onClick={action} />, ); expect(wrapper).toMatchSnapshot(); wrapper.simulate('click'); expect(action).toHaveBeenCalled(); }); test('should support className', () => { const className = 'test-class other-test-class'; const wrapper = shallow<typeof Button>( <Button className={className} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.hasClass('test-class')).toBe(true); expect(wrapper.hasClass('other-test-class')).toBe(true); }); test('should support prepended content', () => { const wrapper = shallow<typeof Button>( <Button prepend={<ReplyIcon className='Icon'/>} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.exists('.Button_prepended ReplyIcon')).toBe(true); }); test('should support appended content', () => { const wrapper = shallow<typeof Button>( <Button append={<ReplyIcon className='Icon'/>} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.exists('.Button_appended ReplyIcon')).toBe(true); }); test('should support children', () => { const wrapper = shallow<typeof Button>( <Button> {'text-goes-here'} </Button>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.text()).toBe('text-goes-here'); }); });
3,333
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common/button
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common/button/__snapshots__/button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/common/button should support appended content 1`] = ` <button className="Button Button___transparent" > <span className="Button_label" /> <span className="Button_appended" > <ReplyIcon className="Icon" /> </span> </button> `; exports[`components/threading/common/button should support children 1`] = ` <button className="Button Button___transparent" > <span className="Button_label" > text-goes-here </span> </button> `; exports[`components/threading/common/button should support className 1`] = ` <button className="Button Button___transparent test-class other-test-class" > <span className="Button_label" /> </button> `; exports[`components/threading/common/button should support onClick 1`] = ` <button className="Button Button___transparent" onClick={[MockFunction]} > <span className="Button_label" /> </button> `; exports[`components/threading/common/button should support prepended content 1`] = ` <button className="Button Button___transparent" > <span className="Button_prepended" > <ReplyIcon className="Icon" /> </span> <span className="Button_label" /> </button> `;
3,334
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common/follow_button/follow_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import FollowButton from './follow_button'; import Button from '../button'; describe('components/threading/common/follow_button', () => { test('should say follow', () => { const clickHandler = jest.fn(); const wrapper = mountWithIntl( <FollowButton isFollowing={false} onClick={clickHandler} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(Button).text()).toBe('Follow'); wrapper.find(Button).simulate('click'); expect(clickHandler).toHaveBeenCalled(); }); test('should say following', () => { const wrapper = mountWithIntl( <FollowButton isFollowing={true} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(Button).text()).toBe('Following'); }); test('should fire click handler', () => { const clickHandler = jest.fn(); const wrapper = mountWithIntl( <FollowButton isFollowing={false} onClick={clickHandler} />, ); wrapper.find(Button).simulate('click'); expect(clickHandler).toHaveBeenCalled(); }); });
3,337
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common/follow_button
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/common/follow_button/__snapshots__/follow_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/common/follow_button should say follow 1`] = ` <Memo(FollowButton) isFollowing={false} onClick={[MockFunction]} > <Memo(Button) className="FollowButton" disabled={false} isActive={false} onClick={[MockFunction]} > <button className="Button Button___transparent FollowButton" disabled={false} onClick={[MockFunction]} > <span className="Button_label" > Follow </span> </button> </Memo(Button)> </Memo(FollowButton)> `; exports[`components/threading/common/follow_button should say following 1`] = ` <Memo(FollowButton) isFollowing={true} > <Memo(Button) className="FollowButton" disabled={false} isActive={true} > <button className="Button Button___transparent is-active FollowButton" disabled={false} > <span className="Button_label" > Following </span> </button> </Memo(Button)> </Memo(FollowButton)> `;
3,346
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_item/thread_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 {Channel} from '@mattermost/types/channels'; import type {Post} from '@mattermost/types/posts'; import type {UserThread} from '@mattermost/types/threads'; import {markLastPostInThreadAsUnread, updateThreadRead} from 'mattermost-redux/actions/threads'; import {manuallyMarkThreadAsUnread} from 'actions/views/threads'; import Tag from 'components/widgets/tag/tag'; import {WindowSizes} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import * as Utils from 'utils/utils'; import ThreadItem from './thread_item'; import ThreadMenu from '../thread_menu'; jest.mock('mattermost-redux/actions/threads'); jest.mock('actions/views/threads'); const mockRouting = { currentUserId: '7n4ach3i53bbmj84dfmu5b7c1c', currentTeamId: 'tid', goToInChannel: jest.fn(), select: jest.fn(), }; jest.mock('../../hooks', () => { return { useThreadRouting: () => mockRouting, }; }); const mockDispatch = jest.fn(); let mockThread: UserThread; let mockPost: Post; let mockChannel: Channel; let mockState: any; 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/threading/global_threads/thread_item', () => { let props: ComponentProps<typeof ThreadItem>; beforeEach(() => { mockThread = { id: '1y8hpek81byspd4enyk9mp1ncw', reply_count: 0, unread_replies: 0, unread_mentions: 0, is_following: true, participants: [ { id: '7n4ach3i53bbmj84dfmu5b7c1c', username: 'frodo.baggins', first_name: 'Frodo', last_name: 'Baggins', }, { id: 'ij61jet1bbdk8fhhxitywdj4ih', username: 'samwise.gamgee', first_name: 'Samwise', last_name: 'Gamgee', }, ], post: { user_id: 'mt5td9mdriyapmwuh5pc84dmhr', channel_id: 'pnzsh7kwt7rmzgj8yb479sc9yw', }, } as UserThread; mockPost = { id: '1y8hpek81byspd4enyk9mp1ncw', user_id: 'mt5td9mdriyapmwuh5pc84dmhr', channel_id: 'pnzsh7kwt7rmzgj8yb479sc9yw', message: 'test msg', create_at: 1610486901110, edit_at: 1611786714912, } as Post; const user = TestHelper.getUserMock(); mockChannel = { id: 'pnzsh7kwt7rmzgj8yb479sc9yw', name: 'test-team', display_name: 'Team name', } as Channel; mockState = { entities: { users: { currentUserId: user.id, }, preferences: { myPreferences: {}, }, }, views: { browser: { windowSize: WindowSizes.DESKTOP_VIEW, }, }, }; props = { isFirstThreadInList: false, channel: mockChannel, currentRelativeTeamUrl: '/tname', displayName: 'Someone', isSelected: false, post: mockPost, postsInThread: [], thread: mockThread, threadId: mockThread.id, isPostPriorityEnabled: false, }; }); test('should report total number of replies', () => { mockThread.reply_count = 9; const wrapper = shallow(<ThreadItem {...props}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.activity MemoizedFormattedMessage').props()).toHaveProperty('id', 'threading.numReplies'); expect(wrapper.find('.activity MemoizedFormattedMessage').props()).toHaveProperty('values.totalReplies', 9); }); test('should report unread messages', () => { mockThread.reply_count = 11; mockThread.unread_replies = 2; const wrapper = shallow(<ThreadItem {...props}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.exists('.dot-unreads')).toBe(true); expect(wrapper.find('.activity MemoizedFormattedMessage').props()).toHaveProperty('id', 'threading.numNewReplies'); expect(wrapper.find('.activity MemoizedFormattedMessage').props()).toHaveProperty('values.newReplies', 2); }); test('should report unread mentions', () => { mockThread.reply_count = 16; mockThread.unread_replies = 5; mockThread.unread_mentions = 2; const wrapper = shallow(<ThreadItem {...props}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.dot-mentions').text()).toBe('2'); expect(wrapper.find('.activity MemoizedFormattedMessage').props()).toHaveProperty('id', 'threading.numNewReplies'); expect(wrapper.find('.activity MemoizedFormattedMessage').props()).toHaveProperty('values.newReplies', 5); }); test('should show channel name', () => { const wrapper = shallow(<ThreadItem {...props}/>); expect(wrapper.find(Tag).props().text).toContain('Team name'); }); test('should pass required props to ThreadMenu', () => { const wrapper = shallow(<ThreadItem {...props}/>); // verify ThreadMenu received transient/required props new Map<string, any>([ ['hasUnreads', Boolean(mockThread.unread_replies)], ['threadId', mockThread.id], ['isFollowing', mockThread.is_following], ['unreadTimestamp', 1611786714912], ]).forEach((val, prop) => { expect(wrapper.find(ThreadMenu).props()).toHaveProperty(prop, val); }); }); test('should call Utils.handleFormattedTextClick on click', () => { const wrapper = shallow(<ThreadItem {...props}/>); const spy = jest.spyOn(Utils, 'handleFormattedTextClick').mockImplementationOnce(jest.fn()); wrapper.find('.preview').simulate('click', {}); expect(spy).toHaveBeenCalledWith({}, '/tname'); }); test('should allow marking as unread on alt + click', () => { const wrapper = shallow(<ThreadItem {...props}/>); wrapper.simulate('click', {altKey: true}); expect(updateThreadRead).not.toHaveBeenCalled(); expect(markLastPostInThreadAsUnread).toHaveBeenCalledWith('user_id', 'tid', '1y8hpek81byspd4enyk9mp1ncw'); expect(manuallyMarkThreadAsUnread).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw', 1611786714912); expect(mockDispatch).toHaveBeenCalledTimes(2); }); });
3,348
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_item
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_item/__snapshots__/thread_item.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/global_threads/thread_item should report total number of replies 1`] = ` <article className="ThreadItem" id="" onClick={[Function]} tabIndex={0} > <h1> <div className="ThreadItem__author" > Someone </div> <div className="ThreadItem__tags" > <Memo(Tag) onClick={[Function]} text="Team name" /> </div> <Connect(injectIntl(Timestamp)) className="alt-hidden" day="numeric" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} /> </h1> <div className="menu-anchor alt-visible" > <Memo(ThreadMenu) hasUnreads={false} isFollowing={true} threadId="1y8hpek81byspd4enyk9mp1ncw" unreadTimestamp={1611786714912} > <SimpleTooltip content={ <Memo(MemoizedFormattedMessage) defaultMessage="Actions" id="threading.threadItem.menu" /> } id="threadActionMenu" > <Memo(Button) className="Button___icon" marginTop={true} > <DotsVerticalIcon size={18} /> </Memo(Button)> </SimpleTooltip> </Memo(ThreadMenu)> </div> <div aria-readonly="true" className="preview" dir="auto" onClick={[Function]} tabIndex={0} > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="test msg" options={ Object { "atMentions": false, "mentionHighlight": false, "singleline": true, } } /> </div> <div className="activity" > <Memo(Avatars) size="xs" userIds={ Array [ "mt5td9mdriyapmwuh5pc84dmhr", "ij61jet1bbdk8fhhxitywdj4ih", "7n4ach3i53bbmj84dfmu5b7c1c", ] } /> <MemoizedFormattedMessage defaultMessage="{totalReplies, plural, =0 {Reply} =1 {# reply} other {# replies}}" id="threading.numReplies" values={ Object { "totalReplies": 9, } } /> </div> </article> `; exports[`components/threading/global_threads/thread_item should report unread mentions 1`] = ` <article className="ThreadItem has-unreads" id="" onClick={[Function]} tabIndex={0} > <h1> <div className="indicator" > <div className="dot-mentions" > 2 </div> </div> <div className="ThreadItem__author" > Someone </div> <div className="ThreadItem__tags" > <Memo(Tag) onClick={[Function]} text="Team name" /> </div> <Connect(injectIntl(Timestamp)) className="alt-hidden" day="numeric" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} /> </h1> <div className="menu-anchor alt-visible" > <Memo(ThreadMenu) hasUnreads={true} isFollowing={true} threadId="1y8hpek81byspd4enyk9mp1ncw" unreadTimestamp={1611786714912} > <SimpleTooltip content={ <Memo(MemoizedFormattedMessage) defaultMessage="Actions" id="threading.threadItem.menu" /> } id="threadActionMenu" > <Memo(Button) className="Button___icon" marginTop={true} > <DotsVerticalIcon size={18} /> </Memo(Button)> </SimpleTooltip> </Memo(ThreadMenu)> </div> <div aria-readonly="true" className="preview" dir="auto" onClick={[Function]} tabIndex={0} > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="test msg" options={ Object { "atMentions": false, "mentionHighlight": false, "singleline": true, } } /> </div> <div className="activity" > <Memo(Avatars) size="xs" userIds={ Array [ "mt5td9mdriyapmwuh5pc84dmhr", "ij61jet1bbdk8fhhxitywdj4ih", "7n4ach3i53bbmj84dfmu5b7c1c", ] } /> <MemoizedFormattedMessage defaultMessage="{newReplies, plural, =1 {# new reply} other {# new replies}}" id="threading.numNewReplies" values={ Object { "newReplies": 5, } } /> </div> </article> `; exports[`components/threading/global_threads/thread_item should report unread messages 1`] = ` <article className="ThreadItem has-unreads" id="" onClick={[Function]} tabIndex={0} > <h1> <div className="indicator" > <div className="dot-unreads" /> </div> <div className="ThreadItem__author" > Someone </div> <div className="ThreadItem__tags" > <Memo(Tag) onClick={[Function]} text="Team name" /> </div> <Connect(injectIntl(Timestamp)) className="alt-hidden" day="numeric" units={ Array [ "now", "minute", "hour", "day", "week", ] } useTime={false} /> </h1> <div className="menu-anchor alt-visible" > <Memo(ThreadMenu) hasUnreads={true} isFollowing={true} threadId="1y8hpek81byspd4enyk9mp1ncw" unreadTimestamp={1611786714912} > <SimpleTooltip content={ <Memo(MemoizedFormattedMessage) defaultMessage="Actions" id="threading.threadItem.menu" /> } id="threadActionMenu" > <Memo(Button) className="Button___icon" marginTop={true} > <DotsVerticalIcon size={18} /> </Memo(Button)> </SimpleTooltip> </Memo(ThreadMenu)> </div> <div aria-readonly="true" className="preview" dir="auto" onClick={[Function]} tabIndex={0} > <Connect(Markdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="test msg" options={ Object { "atMentions": false, "mentionHighlight": false, "singleline": true, } } /> </div> <div className="activity" > <Memo(Avatars) size="xs" userIds={ Array [ "mt5td9mdriyapmwuh5pc84dmhr", "ij61jet1bbdk8fhhxitywdj4ih", "7n4ach3i53bbmj84dfmu5b7c1c", ] } /> <MemoizedFormattedMessage defaultMessage="{newReplies, plural, =1 {# new reply} other {# new replies}}" id="threading.numNewReplies" values={ Object { "newReplies": 2, } } /> </div> </article> `;
3,357
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list/thread_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 {ComponentProps} from 'react'; import {getThreads} from 'mattermost-redux/actions/threads'; import {openModal} from 'actions/views/modals'; import Header from 'components/widgets/header'; import {Constants, WindowSizes} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import ThreadList, {ThreadFilter} from './thread_list'; import VirtualizedThreadList from './virtualized_thread_list'; import Button from '../../common/button'; jest.mock('mattermost-redux/actions/threads'); jest.mock('actions/views/modals'); const mockRouting = { currentUserId: 'uid', currentTeamId: 'tid', goToInChannel: jest.fn(), select: jest.fn(), }; jest.mock('../../hooks', () => { return { useThreadRouting: () => mockRouting, }; }); const mockDispatch = jest.fn(); let mockState: any; 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/threading/global_threads/thread_list', () => { let props: ComponentProps<typeof ThreadList>; beforeEach(() => { props = { currentFilter: ThreadFilter.none, someUnread: true, ids: ['1', '2', '3'], unreadIds: ['2'], setFilter: jest.fn(), }; const user = TestHelper.getUserMock(); const profiles = { [user.id]: user, }; mockState = { entities: { users: { currentUserId: user.id, profiles, }, preferences: { myPreferences: {}, }, threads: { countsIncludingDirect: { tid: { total: 0, total_unread_threads: 0, total_unread_mentions: 0, }, }, }, teams: { currentTeamId: 'tid', }, }, views: { browser: { windowSize: WindowSizes.DESKTOP_VIEW, }, }, }; }); test('should match snapshot', () => { const wrapper = shallow( <ThreadList {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should support filter:all', () => { const wrapper = shallow( <ThreadList {...props}/>, ); wrapper.find(Header).shallow().find(Button).first().shallow().simulate('click'); expect(props.setFilter).toHaveBeenCalledWith(''); }); test('should support filter:unread', () => { const wrapper = shallow( <ThreadList {...props}/>, ); wrapper.find(Header).shallow().find(Button).find({hasDot: true}).simulate('click'); expect(props.setFilter).toHaveBeenCalledWith('unread'); }); test('should support openModal', () => { const wrapper = shallow( <ThreadList {...props}/>, ); wrapper.find(Header).shallow().find({content: 'Mark all as read'}).find(Button).simulate('click'); expect(openModal).toHaveBeenCalledTimes(1); }); test('should support getThreads', async () => { const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); useStateSpy.mockImplementation((init = false) => [init, setState]); const wrapper = shallow( <ThreadList {...props}/>, ); const handleLoadMoreItems = wrapper.find(VirtualizedThreadList).prop('loadMoreItems'); const loadMoreItems = await handleLoadMoreItems(2, 3); expect(loadMoreItems).toEqual({data: true}); expect(getThreads).toHaveBeenCalledWith('uid', 'tid', {unread: false, perPage: Constants.THREADS_PAGE_SIZE, before: '2'}); expect(setState.mock.calls).toEqual([[true], [false], [true]]); }); });
3,359
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list/virtualized_thread_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 {ComponentProps} from 'react'; import VirtualizedThreadList from './virtualized_thread_list'; describe('components/threading/global_threads/thread_list/virtualized_thread_list', () => { let props: ComponentProps<typeof VirtualizedThreadList>; let loadMoreItems: (startIndex: number, stopIndex: number) => Promise<any>; beforeEach(() => { loadMoreItems = () => Promise.resolve(); props = { ids: ['1', '2', '3'], loadMoreItems, selectedThreadId: '1', total: 3, isLoading: false, addNoMoreResultsItem: false, }; }); test('should match snapshot', () => { const wrapper = shallow(<VirtualizedThreadList {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
3,361
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list/virtualized_thread_list_row.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 {Constants} from 'utils/constants'; import Row from './virtualized_thread_list_row'; describe('components/threading/global_threads/thread_list/virtualized_thread_list_row', () => { let props: ComponentProps<typeof Row>; beforeEach(() => { props = { data: { ids: ['1', '2', '3'], selectedThreadId: undefined, }, index: 1, style: {}, }; }); test('should match snapshot', () => { const wrapper = shallow(<Row {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should support item loading indicator', () => { const wrapper = shallow( <Row {...props} data={{ids: [...props.data.ids, Constants.THREADS_LOADING_INDICATOR_ITEM_ID], selectedThreadId: undefined}} index={3} />); expect(wrapper).toMatchSnapshot(); }); test('should support item search guidance ', () => { const wrapper = shallow( <Row {...props} data={{ids: [...props.data.ids, Constants.THREADS_NO_RESULTS_ITEM_ID], selectedThreadId: undefined}} index={3} />); expect(wrapper).toMatchSnapshot(); }); });
3,363
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list/__snapshots__/thread_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/global_threads/thread_list should match snapshot 1`] = ` <div className="ThreadList" id="threads-list-container" tabIndex={0} > <Header heading={ <React.Fragment> <div className="tab-button-wrapper" > <Memo(Button) className="Button___large Margined" isActive={true} onClick={[Function]} > <Memo(MemoizedFormattedMessage) defaultMessage="All your threads" id="threading.filters.allThreads" /> </Memo(Button)> </div> <div className="tab-button-wrapper" id="threads-list-unread-button" > <Memo(Button) className="Button___large Margined" hasDot={true} isActive={false} onClick={[Function]} > <Memo(MemoizedFormattedMessage) defaultMessage="Unreads" id="threading.filters.unreads" /> </Memo(Button)> </div> </React.Fragment> } id="tutorial-threads-mobile-header" right={ <div className="right-anchor" > <SimpleTooltip content="Mark all as read" id="threadListMarkRead" > <Memo(Button) className="Button___large Button___icon" id="threads-list__mark-all-as-read" marginTop={true} onClick={[Function]} > <span className="icon" > <PlaylistCheckIcon size={18} /> </span> </Memo(Button)> </SimpleTooltip> </div> } /> <div className="threads" data-testid="threads_list" > <Memo(VirtualizedThreadList) addNoMoreResultsItem={false} ids={ Array [ "1", "2", "3", ] } isLoading={false} key="threads_list_" loadMoreItems={[Function]} total={0} /> </div> </div> `;
3,364
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list/__snapshots__/virtualized_thread_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/global_threads/thread_list/virtualized_thread_list should match snapshot 1`] = ` <AutoSizer disableHeight={false} disableWidth={false} onResize={[Function]} style={Object {}} > <Component /> </AutoSizer> `;
3,365
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_list/__snapshots__/virtualized_thread_list_row.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/global_threads/thread_list/virtualized_thread_list_row should match snapshot 1`] = ` <Connect(Component) isFirstThreadInList={false} isSelected={false} key="2" style={Object {}} threadId="2" /> `; exports[`components/threading/global_threads/thread_list/virtualized_thread_list_row should support item loading indicator 1`] = ` <LoadingScreen message={<React.Fragment />} style={Object {}} /> `; exports[`components/threading/global_threads/thread_list/virtualized_thread_list_row should support item search guidance 1`] = ` <NoResultsIndicator iconGraphic={<SearchHintSVG />} layout={1} style={ Object { "background": "rgba(var(--center-channel-color-rgb), 0.04)", "padding": "16px 16px 16px 24px", } } subtitle={ <Memo(MemoizedFormattedMessage) defaultMessage="If you’re looking for older conversations, try searching with {searchShortcut}" id="globalThreads.searchGuidance.subtitle" values={ Object { "searchShortcut": <SearchShortcut className="thread-no-results-subtitle-shortcut" variant="tutorialTip" />, } } /> } subtitleClassName="thread-no-results-subtitle" title={ <Memo(MemoizedFormattedMessage) defaultMessage="That’s the end of the list" id="globalThreads.searchGuidance.title" /> } titleClassName="thread-no-results-title" /> `;
3,368
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_menu/thread_menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import {set} from 'lodash'; import React from 'react'; import type {ComponentProps} from 'react'; import {setThreadFollow, updateThreadRead, markLastPostInThreadAsUnread} from 'mattermost-redux/actions/threads'; import { flagPost as savePost, unflagPost as unsavePost, } from 'actions/post_actions'; import {manuallyMarkThreadAsUnread} from 'actions/views/threads'; import Menu from 'components/widgets/menu/menu'; import {fakeDate} from 'tests/helpers/date'; import {copyToClipboard} from 'utils/utils'; import type {GlobalState} from 'types/store'; import ThreadMenu from '../thread_menu'; jest.mock('mattermost-redux/actions/threads'); jest.mock('actions/views/threads'); jest.mock('actions/post_actions'); jest.mock('utils/utils'); const mockRouting = { params: { team: 'team-name-1', }, currentUserId: 'uid', currentTeamId: 'tid', goToInChannel: jest.fn(), }; jest.mock('../../hooks', () => { return { useThreadRouting: () => mockRouting, }; }); 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/threading/common/thread_menu', () => { let props: ComponentProps<typeof ThreadMenu>; beforeEach(() => { props = { threadId: '1y8hpek81byspd4enyk9mp1ncw', unreadTimestamp: 1610486901110, hasUnreads: false, isFollowing: false, children: ( <button>{'test'}</button> ), }; mockState = {entities: {preferences: {myPreferences: {}}}} as GlobalState; }); test('should match snapshot', () => { const wrapper = shallow( <ThreadMenu {...props} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot after opening', () => { const wrapper = shallow( <ThreadMenu {...props} />, ); wrapper.find('button').simulate('click'); expect(wrapper).toMatchSnapshot(); }); test('should allow following', () => { const wrapper = shallow( <ThreadMenu {...props} isFollowing={false} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Follow thread'}).simulate('click'); expect(setThreadFollow).toHaveBeenCalledWith('uid', 'tid', '1y8hpek81byspd4enyk9mp1ncw', true); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should allow unfollowing', () => { const wrapper = shallow( <ThreadMenu {...props} isFollowing={true} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Unfollow thread'}).simulate('click'); expect(setThreadFollow).toHaveBeenCalledWith('uid', 'tid', '1y8hpek81byspd4enyk9mp1ncw', false); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should allow opening in channel', () => { const wrapper = shallow( <ThreadMenu {...props} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Open in channel'}).simulate('click'); expect(mockRouting.goToInChannel).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw'); expect(mockDispatch).not.toHaveBeenCalled(); }); test('should allow marking as read', () => { const resetFakeDate = fakeDate(new Date(1612582579566)); const wrapper = shallow( <ThreadMenu {...props} hasUnreads={true} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Mark as read'}).simulate('click'); expect(markLastPostInThreadAsUnread).not.toHaveBeenCalled(); expect(updateThreadRead).toHaveBeenCalledWith('uid', 'tid', '1y8hpek81byspd4enyk9mp1ncw', 1612582579566); expect(manuallyMarkThreadAsUnread).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw', 1612582579566); expect(mockDispatch).toHaveBeenCalledTimes(2); resetFakeDate(); }); test('should allow marking as unread', () => { const wrapper = shallow( <ThreadMenu {...props} hasUnreads={false} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Mark as unread'}).simulate('click'); expect(updateThreadRead).not.toHaveBeenCalled(); expect(markLastPostInThreadAsUnread).toHaveBeenCalledWith('uid', 'tid', '1y8hpek81byspd4enyk9mp1ncw'); expect(manuallyMarkThreadAsUnread).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw', 1610486901110); expect(mockDispatch).toHaveBeenCalledTimes(2); }); test('should allow saving', () => { const wrapper = shallow( <ThreadMenu {...props} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Save'}).simulate('click'); expect(savePost).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw'); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should allow unsaving', () => { set(mockState, 'entities.preferences.myPreferences', { 'flagged_post--1y8hpek81byspd4enyk9mp1ncw': { user_id: 'uid', category: 'flagged_post', name: '1y8hpek81byspd4enyk9mp1ncw', value: 'true', }, }); const wrapper = shallow( <ThreadMenu {...props} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Unsave'}).simulate('click'); expect(unsavePost).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw'); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should allow link copying', () => { const wrapper = shallow( <ThreadMenu {...props} />, ); wrapper.find('button').simulate('click'); wrapper.find(Menu.ItemAction).find({text: 'Copy link'}).simulate('click'); expect(copyToClipboard).toHaveBeenCalledWith('http://localhost:8065/team-name-1/pl/1y8hpek81byspd4enyk9mp1ncw'); expect(mockDispatch).not.toHaveBeenCalled(); }); });
3,370
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_menu/__snapshots__/thread_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/common/thread_menu should match snapshot 1`] = ` <MenuWrapper animationComponent={[Function]} className="" stopPropagationOnToggle={true} > <button> test </button> <Menu ariaLabel="" openLeft={true} > <MenuItemAction extraText="You will be notified about replies" onClick={[Function]} show={true} text="Follow thread" /> <MenuItemAction onClick={[Function]} show={true} text="Open in channel" /> <MenuItemAction onClick={[Function]} show={true} text="Mark as unread" /> <MenuItemAction onClick={[Function]} show={true} text="Save" /> <MenuItemAction onClick={[Function]} show={true} text="Copy link" /> </Menu> </MenuWrapper> `; exports[`components/threading/common/thread_menu should match snapshot after opening 1`] = ` <MenuWrapper animationComponent={[Function]} className="" stopPropagationOnToggle={true} > <button> test </button> <Menu ariaLabel="" openLeft={true} > <MenuItemAction extraText="You will be notified about replies" onClick={[Function]} show={true} text="Follow thread" /> <MenuItemAction onClick={[Function]} show={true} text="Open in channel" /> <MenuItemAction onClick={[Function]} show={true} text="Mark as unread" /> <MenuItemAction onClick={[Function]} show={true} text="Save" /> <MenuItemAction onClick={[Function]} show={true} text="Copy link" /> </Menu> </MenuWrapper> `;
3,373
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_pane/thread_pane.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 {setThreadFollow} from 'mattermost-redux/actions/threads'; import Button from 'components/threading/common/button'; import FollowButton from 'components/threading/common/follow_button'; import Header from 'components/widgets/header'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import ThreadPane from './thread_pane'; jest.mock('mattermost-redux/actions/threads'); const mockRouting = { currentUserId: 'uid', currentTeamId: 'tid', goToInChannel: jest.fn(), select: jest.fn(), }; jest.mock('../../hooks', () => { return { useThreadRouting: () => mockRouting, }; }); const mockDispatch = jest.fn(); let mockState: any; 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/threading/global_threads/thread_pane', () => { let props: ComponentProps<typeof ThreadPane>; let mockThread: typeof props['thread']; beforeEach(() => { mockThread = { id: '1y8hpek81byspd4enyk9mp1ncw', unread_replies: 0, unread_mentions: 0, is_following: true, post: { user_id: 'mt5td9mdriyapmwuh5pc84dmhr', channel_id: 'pnzsh7kwt7rmzgj8yb479sc9yw', }, } as typeof props['thread']; props = { thread: mockThread, }; const user1 = TestHelper.fakeUserWithId('uid'); const profiles: Record<string, UserProfile> = {}; profiles[user1.id] = user1; mockState = { entities: { general: { config: {}, }, preferences: { myPreferences: {}, }, posts: { postsInThread: {'1y8hpek81byspd4enyk9mp1ncw': []}, posts: { '1y8hpek81byspd4enyk9mp1ncw': { id: '1y8hpek81byspd4enyk9mp1ncw', user_id: 'mt5td9mdriyapmwuh5pc84dmhr', channel_id: 'pnzsh7kwt7rmzgj8yb479sc9yw', create_at: 1610486901110, edit_at: 1611786714912, }, }, }, channels: { channels: { pnzsh7kwt7rmzgj8yb479sc9yw: { id: 'pnzsh7kwt7rmzgj8yb479sc9yw', display_name: 'Team name', }, }, }, users: { profiles, currentUserId: 'uid', }, }, }; }); test('should match snapshot', () => { const wrapper = shallow( <ThreadPane {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should support follow', () => { props.thread.is_following = false; const wrapper = shallow( <ThreadPane {...props}/>, ); wrapper.find(Header).shallow().find(FollowButton).shallow().simulate('click'); expect(setThreadFollow).toHaveBeenCalledWith(mockRouting.currentUserId, mockRouting.currentTeamId, mockThread.id, true); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should support unfollow', () => { props.thread.is_following = true; const wrapper = shallow( <ThreadPane {...props}/>, ); wrapper.find(Header).shallow().find(FollowButton).shallow().simulate('click'); expect(setThreadFollow).toHaveBeenCalledWith(mockRouting.currentUserId, mockRouting.currentTeamId, mockThread.id, false); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should support openInChannel', () => { const wrapper = shallow( <ThreadPane {...props}/>, ); wrapper.find(Header).shallow().find('h3').find(Button).simulate('click'); expect(mockRouting.goToInChannel).toHaveBeenCalledWith('1y8hpek81byspd4enyk9mp1ncw'); }); test('should support go back to list', () => { const wrapper = shallow( <ThreadPane {...props}/>, ); wrapper.find(Header).shallow().find(Button).find('.back').simulate('click'); expect(mockRouting.select).toHaveBeenCalledWith(); }); });
3,375
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_pane
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/global_threads/thread_pane/__snapshots__/thread_pane.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/global_threads/thread_pane should match snapshot 1`] = ` <div className="ThreadPane" id="thread-pane-container" > <Header className="ThreadPane___header" heading={ <React.Fragment> <Memo(Button) className="Button___icon Button___large back" onClick={[Function]} > <i className="icon icon-arrow-back-ios" /> </Memo(Button)> <h3> <span className="separated" > Thread </span> <Memo(Button) allowTextOverflow={true} className="separated" onClick={[Function]} > Team name </Memo(Button)> </h3> </React.Fragment> } right={ <React.Fragment> <Memo(FollowButton) disabled={false} isFollowing={true} onClick={[Function]} /> <Memo(ThreadMenu) hasUnreads={false} isFollowing={true} threadId="1y8hpek81byspd4enyk9mp1ncw" unreadTimestamp={1611786714912} > <SimpleTooltip content="More Actions" id="threadActionMenu" > <Memo(Button) className="Button___icon Button___large" > <DotsVerticalIcon size={18} /> </Memo(Button)> </SimpleTooltip> </Memo(ThreadMenu)> </React.Fragment> } /> </div> `;
3,382
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/thread_viewer/thread_viewer.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 {Channel} from '@mattermost/types/channels'; import type {Post} from '@mattermost/types/posts'; import type {UserThread} from '@mattermost/types/threads'; import {fakeDate} from 'tests/helpers/date'; import {TestHelper} from 'utils/test_helper'; import type {FakePost} from 'types/store/rhs'; import ThreadViewer from './thread_viewer'; import type {Props} from './thread_viewer'; describe('components/threading/ThreadViewer', () => { const post: Post = TestHelper.getPostMock({ channel_id: 'channel_id', create_at: 1502715365009, update_at: 1502715372443, is_following: true, reply_count: 3, }); const fakePost: FakePost = { id: post.id, exists: true, type: post.type, user_id: post.user_id, channel_id: post.channel_id, message: post.message, }; const channel: Channel = TestHelper.getChannelMock({ display_name: '', name: '', header: '', purpose: '', creator_id: '', scheme_id: '', teammate_id: '', status: '', }); const actions = { removePost: jest.fn(), selectPostCard: jest.fn(), getNewestPostThread: jest.fn(), getPostThread: jest.fn(), getThread: jest.fn(), updateThreadRead: jest.fn(), updateThreadLastOpened: jest.fn(), fetchRHSAppsBindings: jest.fn(), }; const baseProps: Props = { selected: post, channel, currentUserId: 'user_id', currentTeamId: 'team_id', socketConnectionStatus: true, actions, isCollapsedThreadsEnabled: false, postIds: [post.id], appsEnabled: true, rootPostId: post.id, }; test('should match snapshot', async () => { const reset = fakeDate(new Date(1502715365000)); const wrapper = shallow( <ThreadViewer {...baseProps}/>, ); await new Promise((resolve) => setTimeout(resolve)); expect(wrapper).toMatchSnapshot(); reset(); }); test('should make api call to get thread posts on socket reconnect', () => { const wrapper = shallow( <ThreadViewer {...baseProps}/>, ); wrapper.setProps({socketConnectionStatus: false}); wrapper.setProps({socketConnectionStatus: true}); return expect(actions.getPostThread).toHaveBeenCalledWith(post.id, true); }); test('should not break if root post is a fake post', () => { const props = { ...baseProps, selected: fakePost, }; expect(() => { shallow(<ThreadViewer {...props}/>); }).not.toThrowError("Cannot read property 'reply_count' of undefined"); }); test('should not break if root post is ID only', () => { const props = { ...baseProps, rootPostId: post.id, selected: undefined, }; expect(() => { shallow(<ThreadViewer {...props}/>); }).not.toThrowError("Cannot read property 'reply_count' of undefined"); }); test('should call fetchThread when no thread on mount', (done) => { const {actions} = baseProps; shallow( <ThreadViewer {...baseProps} isCollapsedThreadsEnabled={true} />, ); expect.assertions(3); process.nextTick(() => { expect(actions.updateThreadLastOpened).not.toHaveBeenCalled(); expect(actions.updateThreadRead).not.toHaveBeenCalled(); expect(actions.getThread).toHaveBeenCalledWith('user_id', 'team_id', 'id', true); done(); }); }); test('should call updateThreadLastOpened on mount', () => { jest.useFakeTimers().setSystemTime(400); const {actions} = baseProps; const userThread = { id: 'id', last_viewed_at: 42, last_reply_at: 32, } as UserThread; shallow( <ThreadViewer {...baseProps} userThread={userThread} isCollapsedThreadsEnabled={true} />, ); expect.assertions(3); expect(actions.updateThreadLastOpened).toHaveBeenCalledWith('id', 42); expect(actions.updateThreadRead).not.toHaveBeenCalled(); expect(actions.getThread).not.toHaveBeenCalled(); }); test('should call updateThreadLastOpened and updateThreadRead on mount when unread replies', () => { jest.useFakeTimers().setSystemTime(400); const {actions} = baseProps; const userThread = { id: 'id', last_viewed_at: 42, last_reply_at: 142, } as UserThread; shallow( <ThreadViewer {...baseProps} userThread={userThread} isCollapsedThreadsEnabled={true} />, ); expect.assertions(3); expect(actions.updateThreadLastOpened).toHaveBeenCalledWith('id', 42); expect(actions.updateThreadRead).toHaveBeenCalledWith('user_id', 'team_id', 'id', 400); expect(actions.getThread).not.toHaveBeenCalled(); }); test('should call updateThreadLastOpened and updateThreadRead upon thread id change', (done) => { jest.useRealTimers(); const dateNowOrig = Date.now; Date.now = () => new Date(400).getMilliseconds(); const {actions} = baseProps; const userThread = { id: 'id', last_viewed_at: 42, last_reply_at: 142, } as UserThread; const wrapper = shallow( <ThreadViewer {...baseProps} isCollapsedThreadsEnabled={true} />, ); expect.assertions(6); process.nextTick(() => { expect(actions.updateThreadLastOpened).not.toHaveBeenCalled(); expect(actions.updateThreadRead).not.toHaveBeenCalled(); expect(actions.getThread).toHaveBeenCalled(); jest.resetAllMocks(); wrapper.setProps({userThread}); expect(actions.updateThreadLastOpened).toHaveBeenCalledWith('id', 42); expect(actions.updateThreadRead).toHaveBeenCalledWith('user_id', 'team_id', 'id', 400); expect(actions.getThread).not.toHaveBeenCalled(); Date.now = dateNowOrig; done(); }); }); test('should call fetchRHSAppsBindings on mount if appsEnabled', () => { const {actions} = baseProps; shallow( <ThreadViewer {...baseProps} />, ); expect(actions.fetchRHSAppsBindings).toHaveBeenCalledWith('channel_id', 'id'); }); test('should not call fetchRHSAppsBindings on mount if not appsEnabled', () => { const {actions} = baseProps; shallow( <ThreadViewer {...baseProps} appsEnabled={false} />, ); expect(actions.fetchRHSAppsBindings).not.toHaveBeenCalledWith('channel_id', 'id'); }); });
3,384
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/thread_viewer
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/thread_viewer/__snapshots__/thread_viewer.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/threading/ThreadViewer should match snapshot 1`] = ` <Fragment> <div className="ThreadViewer" > <div className="post-right-comments-container" > <FileUploadOverlay overlayType="right" /> <DeferredRenderWrapper channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 0, "display_name": "", "group_constrained": false, "header": "", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "", "purpose": "", "scheme_id": "", "status": "", "team_id": "team_id", "teammate_id": "", "type": "O", "update_at": 0, } } isThreadView={false} key="id" onCardClick={[Function]} postIds={ Array [ "id", ] } selected={ Object { "channel_id": "channel_id", "create_at": 1502715365009, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "id", "is_following": true, "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": 3, "root_id": "", "type": "system_add_remove", "update_at": 1502715372443, "user_id": "user_id", } } useRelativeTimestamp={false} /> </div> </div> </Fragment> `;
3,388
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading
petrpan-code/mattermost/mattermost/webapp/channels/src/components/threading/virtualized_thread_viewer/virtualized_thread_viewer.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 {Channel} from '@mattermost/types/channels'; import type {Post} from '@mattermost/types/posts'; import type {UserProfile} from '@mattermost/types/users'; import {TestHelper} from 'utils/test_helper'; import VirtualizedThreadViewer from './virtualized_thread_viewer'; describe('components/threading/VirtualizedThreadViewer', () => { const post: Post = TestHelper.getPostMock({ channel_id: 'channel_id', create_at: 1502715365009, update_at: 1502715372443, is_following: true, reply_count: 3, }); const channel: Channel = TestHelper.getChannelMock({ display_name: '', name: '', header: '', purpose: '', creator_id: '', scheme_id: '', teammate_id: '', status: '', }); const actions = { removePost: jest.fn(), selectPostCard: jest.fn(), getPostThread: jest.fn(), getThread: jest.fn(), updateThreadRead: jest.fn(), updateThreadLastOpened: jest.fn(), fetchRHSAppsBindings: jest.fn(), }; const directTeammate: UserProfile = TestHelper.getUserMock(); const baseProps = { selected: post, channel, currentUserId: 'user_id', currentTeamId: 'team_id', previewCollapsed: 'false', previewEnabled: true, socketConnectionStatus: true, actions, directTeammate, posts: [post], lastPost: post, onCardClick: () => {}, onCardClickPost: () => {}, replyListIds: [], teamId: '', useRelativeTimestamp: true, isMobileView: false, isThreadView: true, lastViewedAt: 0, newMessagesSeparatorActions: [], }; test('should scroll to the bottom when the current user makes a new post in the thread', () => { const scrollToBottom = jest.fn(); const wrapper = shallow( <VirtualizedThreadViewer {...baseProps}/>, ); const instance = wrapper.instance() as VirtualizedThreadViewer; instance.scrollToBottom = scrollToBottom; expect(scrollToBottom).not.toHaveBeenCalled(); wrapper.setProps({ lastPost: { id: 'newpost', root_id: post.id, user_id: 'user_id', }, }); expect(scrollToBottom).toHaveBeenCalled(); }); test('should not scroll to the bottom when another user makes a new post in the thread', () => { const scrollToBottom = jest.fn(); const wrapper = shallow( <VirtualizedThreadViewer {...baseProps}/>, ); const instance = wrapper.instance() as VirtualizedThreadViewer; instance.scrollToBottom = scrollToBottom; expect(scrollToBottom).not.toHaveBeenCalled(); wrapper.setProps({ lastPost: { id: 'newpost', root_id: post.id, user_id: 'other_user_id', }, }); expect(scrollToBottom).not.toHaveBeenCalled(); }); test('should not scroll to the bottom when there is a highlighted reply', () => { const scrollToBottom = jest.fn(); const wrapper = shallow( <VirtualizedThreadViewer {...baseProps} />, ); const instance = wrapper.instance() as VirtualizedThreadViewer; instance.scrollToBottom = scrollToBottom; wrapper.setProps({ lastPost: { id: 'newpost', root_id: post.id, user_id: 'user_id', }, highlightedPostId: '42', }); expect(scrollToBottom).not.toHaveBeenCalled(); }); });
3,394
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/three_days_left_trial_modal/three_days_left_trial_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 {Provider} from 'react-redux'; import {GenericModal} from '@mattermost/components'; import ThreeDaysLeftTrialModal from 'components/three_days_left_trial_modal/three_days_left_trial_modal'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; describe('components/three_days_left_trial_modal/three_days_left_trial_modal', () => { // required state to mount using the provider const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, cloud: { limits: { limitsLoaded: true, }, }, users: { currentUserId: user.id, profiles, }, usage: { files: { totalStorage: 0, totalStorageLoaded: true, }, messages: { history: 0, historyLoaded: true, }, boards: { cards: 0, cardsLoaded: true, }, integrations: { enabled: 3, enabledLoaded: true, }, teams: { active: 0, cloudArchived: 0, teamsLoaded: true, }, }, }, views: { modals: { modalState: { three_days_left_trial_modal: { open: 'true', }, }, }, }, }; const props = { onExited: jest.fn(), limitsOverpassed: false, }; const store = mockStore(state); test('should match snapshot', () => { const wrapper = shallow( <Provider store={store}> <ThreeDaysLeftTrialModal {...props}/> </Provider>, ); expect(wrapper.debug()).toMatchSnapshot(); }); test('should match snapshot when limits are overpassed and show the limits panel', () => { const wrapper = shallow( <Provider store={store}> <ThreeDaysLeftTrialModal {...props} limitsOverpassed={true} /> </Provider>, ); expect(wrapper.debug()).toMatchSnapshot(); }); test('should show the three days left modal with the three cards', () => { const wrapper = mountWithIntl( <Provider store={store}> <ThreeDaysLeftTrialModal {...props}/> </Provider>, ); expect(wrapper.find('ThreeDaysLeftTrialModal ThreeDaysLeftTrialCard')).toHaveLength(3); }); test('should show the workspace limits panel when limits are overpassed', () => { const wrapper = mountWithIntl( <Provider store={store}> <ThreeDaysLeftTrialModal {...props} limitsOverpassed={true} /> </Provider>, ); expect(wrapper.find('ThreeDaysLeftTrialModal WorkspaceLimitsPanel')).toHaveLength(1); }); test('should call on exited', () => { const mockOnExited = jest.fn(); const wrapper = mountWithIntl( <Provider store={store}> <ThreeDaysLeftTrialModal {...props} onExited={mockOnExited} /> </Provider>, ); wrapper.find(GenericModal).props().onExited(); expect(mockOnExited).toHaveBeenCalled(); }); });
3,397
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/three_days_left_trial_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/three_days_left_trial_modal/__snapshots__/three_days_left_trial_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/three_days_left_trial_modal/three_days_left_trial_modal should match snapshot 1`] = ` "<ContextProvider value={{...}}> <ThreeDaysLeftTrialModal onExited={[Function: mockConstructor] { _isMockFunction: true, getMockImplementation: [Function (anonymous)], mock: Object [Object: null prototype] { calls: [], contexts: [], instances: [], invocationCallOrder: [], results: [] }, mockClear: [Function (anonymous)], mockReset: [Function (anonymous)], mockRestore: [Function (anonymous)], mockReturnValueOnce: [Function (anonymous)], mockResolvedValueOnce: [Function (anonymous)], mockRejectedValueOnce: [Function (anonymous)], mockReturnValue: [Function (anonymous)], mockResolvedValue: [Function (anonymous)], mockRejectedValue: [Function (anonymous)], mockImplementationOnce: [Function (anonymous)], withImplementation: [Function: bound withImplementation], mockImplementation: [Function (anonymous)], mockReturnThis: [Function (anonymous)], mockName: [Function (anonymous)], getMockName: [Function (anonymous)] }} limitsOverpassed={false} /> </ContextProvider>" `; exports[`components/three_days_left_trial_modal/three_days_left_trial_modal should match snapshot when limits are overpassed and show the limits panel 1`] = ` "<ContextProvider value={{...}}> <ThreeDaysLeftTrialModal onExited={[Function: mockConstructor] { _isMockFunction: true, getMockImplementation: [Function (anonymous)], mock: Object [Object: null prototype] { calls: [], contexts: [], instances: [], invocationCallOrder: [], results: [] }, mockClear: [Function (anonymous)], mockReset: [Function (anonymous)], mockRestore: [Function (anonymous)], mockReturnValueOnce: [Function (anonymous)], mockResolvedValueOnce: [Function (anonymous)], mockRejectedValueOnce: [Function (anonymous)], mockReturnValue: [Function (anonymous)], mockResolvedValue: [Function (anonymous)], mockRejectedValue: [Function (anonymous)], mockImplementationOnce: [Function (anonymous)], withImplementation: [Function: bound withImplementation], mockImplementation: [Function (anonymous)], mockReturnThis: [Function (anonymous)], mockName: [Function (anonymous)], getMockName: [Function (anonymous)] }} limitsOverpassed={true} /> </ContextProvider>" `;
3,398
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import type {GlobalState} from 'types/store'; import * as Timestamp from './timestamp'; import {mapStateToProps} from './index'; const supportsHourCycleOg = Timestamp.supportsHourCycle; Object.defineProperty(Timestamp, 'supportsHourCycle', {get: () => supportsHourCycleOg}); const supportsHourCycleSpy = jest.spyOn(Timestamp, 'supportsHourCycle', 'get'); describe('mapStateToProps', () => { const currentUserId = 'user-id'; const initialState = { entities: { preferences: { myPreferences: {}, }, users: { currentUserId, profiles: { [currentUserId]: { id: currentUserId, }, }, }, }, } as unknown as GlobalState; describe('hourCycle', () => { test('hourCycle should be h12 when military time is false and the prop was not set', () => { const props = mapStateToProps(initialState, {}); expect(props.hourCycle).toBe('h12'); }); test('hourCycle should be h23 when military time is true and the prop was not set', () => { const testState = mergeObjects(initialState, { entities: { preferences: { myPreferences: { 'display_settings--use_military_time': { category: 'display_settings', name: 'use_military_time', user_id: currentUserId, value: 'true', }, }, }, }, }); const props = mapStateToProps(testState, {}); expect(props.hourCycle).toBe('h23'); }); test('hourCycle should have the value of prop.hourCycle when given', () => { const testState = mergeObjects(initialState, { entities: { preferences: { myPreferences: { 'display_settings--use_military_time': { category: 'display_settings', name: 'use_military_time', user_id: currentUserId, value: 'true', }, }, }, }, }); const props = mapStateToProps(testState, {hourCycle: 'h24'}); expect(props.hourCycle).toBe('h24'); }); }); describe('timeZone', () => { test('timeZone should be the user TZ when the prop was not set', () => { const testState = mergeObjects(initialState, { entities: { users: { profiles: { [currentUserId]: { timezone: { useAutomaticTimezone: false, manualTimezone: 'Europe/Paris', }, }, }, }, }, }); const props = mapStateToProps(testState, {}); expect(props.timeZone).toBe('Europe/Paris'); }); test('timeZone should be the value of prop.timeZone when given', () => { const testState = mergeObjects(initialState, { entities: { users: { profiles: { [currentUserId]: { timezone: { useAutomaticTimezone: false, manualTimezone: 'Europe/Paris', }, }, }, }, }, }); const props = mapStateToProps(testState, {timeZone: 'America/Phoenix'}); expect(props.timeZone).toBe('America/Phoenix'); }); }); describe('hour12, hourCycle unsupported', () => { test('hour12 should be false when using military time', () => { const testState = mergeObjects(initialState, { entities: { preferences: { myPreferences: { 'display_settings--use_military_time': { category: 'display_settings', name: 'use_military_time', user_id: currentUserId, value: 'true', }, }, }, }, }); supportsHourCycleSpy.mockReturnValueOnce(false); const props = mapStateToProps(testState, {}); expect(props.hour12).toBe(false); }); test('hour12 should be true when not using military time', () => { const testState = mergeObjects(initialState, { entities: { preferences: { myPreferences: { 'display_settings--use_military_time': { category: 'display_settings', name: 'use_military_time', user_id: currentUserId, value: 'false', }, }, }, }, }); supportsHourCycleSpy.mockReturnValueOnce(false); const props = mapStateToProps(testState, {}); expect(props.hour12).toBe(true); }); test('hour12 should equal props.hour12 when defined', () => { const testState = mergeObjects(initialState, { entities: { preferences: { myPreferences: { 'display_settings--use_military_time': { category: 'display_settings', name: 'use_military_time', user_id: currentUserId, value: 'false8', }, }, }, }, }); supportsHourCycleSpy.mockReturnValueOnce(false); const props = mapStateToProps(testState, {hour12: false}); expect(props.hour12).toBe(false); }); }); });
3,401
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp/semantic_time.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 SemanticTime from './semantic_time'; describe('components/timestamp/SemanticTime', () => { test('should render time semantically', () => { const date = new Date('2020-06-05T10:20:30Z'); const wrapper = mount( <SemanticTime value={date} />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2020-06-05T10:20:30.000'); }); test('should support passthrough children', () => { const date = new Date('2020-06-05T10:20:30Z'); const wrapper = mount( <SemanticTime value={date} > {'10:20'} </SemanticTime>, ); expect(wrapper.find('time').text()).toBe('10:20'); }); test('should support custom label', () => { const date = new Date('2020-06-05T10:20:30Z'); const wrapper = mount( <SemanticTime value={date} aria-label='A custom label' />, ); expect(wrapper).toMatchSnapshot(); }); });
3,403
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp/timestamp.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import moment from 'moment'; import React from 'react'; import {createIntl} from 'react-intl'; import defaultMessages from 'i18n/en.json'; import {fakeDate} from 'tests/helpers/date'; import {shallowWithIntl, mountWithIntl} from 'tests/helpers/intl-test-helper'; import SemanticTime from './semantic_time'; import Timestamp from './timestamp'; import {RelativeRanges} from './index'; describe('components/timestamp/Timestamp', () => { let resetFakeDate: () => void; beforeEach(() => { resetFakeDate = fakeDate(new Date('2019-05-03T13:20:00Z')); }); afterEach(() => { resetFakeDate(); }); function daysFromNow(diff: number) { const date = new Date(); date.setDate(date.getDate() + diff); return date; } test('should be wrapped in SemanticTime and support passthrough className and label', () => { const wrapper = shallowWithIntl( <Timestamp useTime={false} className='test class' label='test label' />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(SemanticTime).exists()).toBeTruthy(); expect(wrapper.find(SemanticTime).prop('className')).toBe('test class'); expect(wrapper.find(SemanticTime).prop('aria-label')).toBe('test label'); }); test('should not be wrapped in SemanticTime', () => { const wrapper = shallowWithIntl( <Timestamp useTime={false} useSemanticOutput={false} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(SemanticTime).exists()).toBeFalsy(); }); test.each(moment.tz.names())('should render supported timezone %p', (timeZone) => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT+0000 (+00)').getTime()} useDate={false} timeZone={timeZone} />, { intl: createIntl({ locale: 'es', defaultLocale: 'es', timeZone: 'Etc/UTC', messages: defaultMessages, textComponent: 'span', }), }, ); expect(wrapper.find('time').prop('dateTime')).toEqual(expect.any(String)); expect(wrapper.text()).toMatch(/\d{1,2}:\d{2}\s(?:AM|PM|a\.\sm\.|p\.\sm\.)/); }); test('should render title-case Today', () => { const wrapper = mountWithIntl( <Timestamp useTime={false} ranges={[ RelativeRanges.TODAY_TITLE_CASE, ]} />, ); expect(wrapper.text()).toEqual('Today'); }); test('should render normal today', () => { const wrapper = mountWithIntl( <Timestamp value={daysFromNow(0)} useTime={false} ranges={[ RelativeRanges.TODAY_YESTERDAY, ]} />, ); expect(wrapper.text()).toEqual('today'); }); test('should render title-case Yesterday', () => { const wrapper = mountWithIntl( <Timestamp value={daysFromNow(-1)} useTime={false} ranges={[ RelativeRanges.YESTERDAY_TITLE_CASE, ]} />, ); expect(wrapper.text()).toEqual('Yesterday'); }); test('should render normal yesterday', () => { const wrapper = mountWithIntl( <Timestamp value={daysFromNow(-1)} useTime={false} ranges={[ RelativeRanges.TODAY_YESTERDAY, ]} />, ); expect(wrapper.text()).toEqual('yesterday'); }); test('should render normal tomorrow', () => { const wrapper = mountWithIntl( <Timestamp value={daysFromNow(1)} useTime={false} unit='day' />, ); expect(wrapper.text()).toEqual('tomorrow'); }); test('should render 3 days ago', () => { const wrapper = mountWithIntl( <Timestamp value={daysFromNow(-3)} useTime={false} unit='day' />, ); expect(wrapper.text()).toEqual('3 days ago'); }); test('should render 3 days ago as weekday', () => { const date = daysFromNow(-3); const wrapper = mountWithIntl( <Timestamp value={date} useTime={false} />, ); expect(wrapper.text()).toEqual(moment.utc(date).format('dddd')); }); test('should render 6 days ago as weekday', () => { const date = daysFromNow(-6); const wrapper = mountWithIntl( <Timestamp value={date} useTime={false} />, ); expect(wrapper.text()).toEqual(moment(date).format('dddd')); }); test('should render 2 days ago as weekday in supported timezone', () => { const date = daysFromNow(-2); const wrapper = mountWithIntl( <Timestamp value={date} timeZone='Asia/Manila' useTime={false} />, ); expect(wrapper.text()).toEqual(moment.utc(date).tz('Asia/Manila').format('dddd')); }); test('should render date in current year', () => { const date = daysFromNow(-20); const wrapper = mountWithIntl( <Timestamp value={date} useTime={false} />, ); expect(wrapper.text()).toEqual(moment.utc(date).format('MMMM DD')); }); test('should render date from previous year', () => { const date = daysFromNow(-365); const wrapper = mountWithIntl( <Timestamp value={date} useTime={false} />, ); expect(wrapper.text()).toEqual(moment.utc(date).format('MMMM DD, YYYY')); }); test('should render time without timezone', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT+0800 (+08)').getTime()} useDate={false} />, ); expect(wrapper.text()).toBe('12:15 PM'); }); test('should render time without timezone, in military time', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 23:15:13 GMT+0800 (+08)').getTime()} hourCycle='h23' useDate={false} />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2018-01-12T15:15:13.000'); expect(wrapper.text()).toBe('15:15'); }); test('should render date without timezone', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 23:15:13 GMT+0800 (+08)').getTime()} useTime={false} />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2018-01-12T15:15:13.000'); expect(wrapper.text()).toBe('January 12, 2018'); }); test('should render time with timezone enabled', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT+0000 (+00)').getTime()} useDate={false} timeZone='Australia/Sydney' />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2018-01-12T20:15:13.000'); expect(wrapper.text()).toBe('7:15 AM'); }); test('should render time with unsupported timezone', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT+0000 (+00)').getTime()} useDate={false} timeZone='US/Hawaii' />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2018-01-12T20:15:13.000'); expect(wrapper.text()).toBe('10:15 AM'); }); test('should render date with unsupported timezone', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT+0000 (+00)').getTime()} useTime={false} timeZone='US/Hawaii' />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2018-01-12T20:15:13.000'); expect(wrapper.text()).toBe('January 12, 2018'); }); test('should render datetime with timezone enabled, in military time', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT-0800').getTime()} hourCycle='h23' timeZone='Australia/Sydney' />, ); expect(wrapper.find('time').prop('dateTime')).toBe('2018-01-13T04:15:13.000'); expect(wrapper.text()).toBe('January 13, 2018 at 15:15'); }); test('should render time with unsupported timezone enabled, in military time', () => { const wrapper = mountWithIntl( <Timestamp value={new Date('Fri Jan 12 2018 20:15:13 GMT-0800 (+00)').getTime()} hourCycle='h23' useDate={false} timeZone='US/Alaska' />, ); expect(wrapper.text()).toBe('19:15'); }); });
3,405
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp/__snapshots__/semantic_time.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/timestamp/SemanticTime should support custom label 1`] = ` <Memo(SemanticTime) aria-label="A custom label" value={2020-06-05T10:20:30.000Z} > <time aria-label="A custom label" dateTime="2020-06-05T10:20:30.000" /> </Memo(SemanticTime)> `;
3,406
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp
petrpan-code/mattermost/mattermost/webapp/channels/src/components/timestamp/__snapshots__/timestamp.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/timestamp/Timestamp should be wrapped in SemanticTime and support passthrough className and label 1`] = ` <Memo(SemanticTime) aria-label="test label" className="test class" value={2019-05-03T13:20:00.000Z} > Friday </Memo(SemanticTime)> `; exports[`components/timestamp/Timestamp should not be wrapped in SemanticTime 1`] = `"Friday"`;
3,408
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/toast/toast.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import type {ReactWrapper} from 'enzyme'; import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import * as Utils from 'utils/utils'; import Toast from './toast'; import type {Props} from './toast'; describe('components/Toast', () => { const defaultProps: Props = { onClick: jest.fn(), show: true, showActions: true, onClickMessage: Utils.localizeMessage('postlist.toast.scrollToBottom', 'Jump to recents'), width: 1000, }; test('should match snapshot for showing toast', () => { const wrapper = shallow<Toast>(<Toast {...defaultProps}><span>{'child'}</span></Toast>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for hiding toast', () => { const wrapper = shallow<Toast>(<Toast {...{...defaultProps, show: false}}><span>{'child'}</span></Toast>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.toast__visible').length).toBe(0); }); test('should match snapshot for toast width less than 780px', () => { const wrapper = shallow<Toast>(<Toast {...{...defaultProps, width: 779}}><span>{'child'}</span></Toast>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot to not have actions', () => { const wrapper = shallow<Toast>(<Toast {...{...defaultProps, showActions: false}}><span>{'child'}</span></Toast>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('.toast__pointer').length).toBe(0); }); test('should dismiss', () => { defaultProps.onDismiss = jest.fn(); const wrapper: ReactWrapper<any, any, React.Component> = mountWithIntl(<Toast {... defaultProps}><span>{'child'}</span></Toast>); const toast = wrapper.find(Toast).instance(); if (toast instanceof Toast) { toast.handleDismiss(); } expect(defaultProps.onDismiss).toHaveBeenCalledTimes(1); }); test('should match snapshot to have extraClasses', () => { const wrapper = shallow<Toast>(<Toast {...{...defaultProps, extraClasses: 'extraClasses'}}><span>{'child'}</span></Toast>); expect(wrapper).toMatchSnapshot(); }); });
3,410
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/toast
petrpan-code/mattermost/mattermost/webapp/channels/src/components/toast/__snapshots__/toast.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/Toast should match snapshot for hiding toast 1`] = ` <div className="toast" > <div className="toast__message toast__pointer" onClick={[MockFunction]} > <div className="toast__jump" > <UnreadBelowIcon /> Jump to recents </div> <span> child </span> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={<div />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="toast__dismiss" data-testid="dismissToast" onClick={[Function]} > <CloseIcon className="close-btn" id="dismissToast" /> </div> </OverlayTrigger> </div> `; exports[`components/Toast should match snapshot for showing toast 1`] = ` <div className="toast toast__visible" > <div className="toast__message toast__pointer" onClick={[MockFunction]} > <div className="toast__jump" > <UnreadBelowIcon /> Jump to recents </div> <span> child </span> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="toast-close__tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Close" id="general_button.close" /> <div className="tooltip__shortcut--txt" > <Memo(MemoizedFormattedMessage) defaultMessage="esc" id="general_button.esc" /> </div> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="toast__dismiss" data-testid="dismissToast" onClick={[Function]} > <CloseIcon className="close-btn" id="dismissToast" /> </div> </OverlayTrigger> </div> `; exports[`components/Toast should match snapshot for toast width less than 780px 1`] = ` <div className="toast toast__visible" > <div className="toast__message toast__pointer" onClick={[MockFunction]} > <div className="toast__jump" > <UnreadBelowIcon /> Jump to recents </div> <span> child </span> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="toast-close__tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Close" id="general_button.close" /> <div className="tooltip__shortcut--txt" > <Memo(MemoizedFormattedMessage) defaultMessage="esc" id="general_button.esc" /> </div> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="toast__dismiss" data-testid="dismissToast" onClick={[Function]} > <CloseIcon className="close-btn" id="dismissToast" /> </div> </OverlayTrigger> </div> `; exports[`components/Toast should match snapshot to have extraClasses 1`] = ` <div className="toast extraClasses toast__visible" > <div className="toast__message toast__pointer" onClick={[MockFunction]} > <div className="toast__jump" > <UnreadBelowIcon /> Jump to recents </div> <span> child </span> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="toast-close__tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Close" id="general_button.close" /> <div className="tooltip__shortcut--txt" > <Memo(MemoizedFormattedMessage) defaultMessage="esc" id="general_button.esc" /> </div> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="toast__dismiss" data-testid="dismissToast-extraClasses" onClick={[Function]} > <CloseIcon className="close-btn" id="dismissToast" /> </div> </OverlayTrigger> </div> `; exports[`components/Toast should match snapshot to not have actions 1`] = ` <div className="toast toast__visible" > <div className="toast__message" > <span> child </span> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={<div />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="toast__dismiss" data-testid="dismissToast" onClick={[Function]} > <CloseIcon className="close-btn" id="dismissToast" /> </div> </OverlayTrigger> </div> `;
3,413
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/toast_wrapper/toast_wrapper.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {fireEvent, screen} from '@testing-library/react'; import React from 'react'; import type {ComponentProps} from 'react'; import Preferences from 'mattermost-redux/constants/preferences'; import {DATE_LINE} from 'mattermost-redux/utils/post_list'; import {HINT_TOAST_TESTID} from 'components/hint-toast/hint_toast'; import {SCROLL_TO_BOTTOM_DISMISS_BUTTON_TESTID, SCROLL_TO_BOTTOM_TOAST_TESTID} from 'components/scroll_to_bottom_toast/scroll_to_bottom_toast'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import {renderWithContext} from 'tests/react_testing_utils'; import {getHistory} from 'utils/browser_history'; import {PostListRowListIds} from 'utils/constants'; import ToastWrapper from './toast_wrapper'; import type {Props, ToastWrapperClass} from './toast_wrapper'; describe('components/ToastWrapper', () => { const baseProps: ComponentProps<typeof ToastWrapper> = { unreadCountInChannel: 0, unreadScrollPosition: Preferences.UNREAD_SCROLL_POSITION_START_FROM_LEFT, newRecentMessagesCount: 0, channelMarkedAsUnread: false, isNewMessageLineReached: false, shouldStartFromBottomWhenUnread: false, atLatestPost: false, postListIds: [ 'post1', 'post2', 'post3', DATE_LINE + 1551711600000, ], latestPostTimeStamp: 12345, atBottom: false, lastViewedBottom: 1234, width: 1000, updateNewMessagesAtInChannel: jest.fn(), scrollToNewMessage: jest.fn(), scrollToLatestMessages: jest.fn(), updateLastViewedBottomAt: jest.fn(), lastViewedAt: 12344, channelId: '', isCollapsedThreadsEnabled: false, rootPosts: {} as Props['rootPosts'], initScrollOffsetFromBottom: 1001, scrollToUnreadMessages: jest.fn(), showSearchHintToast: true, onSearchHintDismiss: jest.fn(), showScrollToBottomToast: false, onScrollToBottomToastDismiss: jest.fn(), hideScrollToBottomToast: jest.fn(), actions: { updateToastStatus: jest.fn(), }, match: { params: { team: 'team', }, } as unknown as Props['match'], } as unknown as Props; describe('unread count logic', () => { test('If not atLatestPost and channelMarkedAsUnread is false then unread count is equal to unreads in present chunk plus recent messages', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('unreadCount')).toBe(15); }); test('If atLatestPost and unreadScrollPosition is startFromNewest and prevState.unreadCountInChannel is not 0 then unread count then unread count is based on the unreadCountInChannel', () => { const props = { ...baseProps, atLatestPost: true, unreadCountInChannel: 10, unreadScrollPosition: Preferences.UNREAD_SCROLL_POSITION_START_FROM_NEWEST, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('unreadCount')).toBe(10); }); test('If atLatestPost and prevState.unreadCountInChannel is 0 then unread count is based on the number of posts below the new message indicator', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('unreadCount')).toBe(3); }); test('If channelMarkedAsUnread then unread count should be based on the unreadCountInChannel', () => { const props = { ...baseProps, atLatestPost: false, channelMarkedAsUnread: true, unreadCountInChannel: 10, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('unreadCount')).toBe(10); }); }); describe('toasts state', () => { test('Should have unread toast if unreadCount > 0', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(true); }); test('Should set state of have unread toast when atBottom changes from undefined', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, atBottom: null, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(undefined); wrapper.setProps({atBottom: false}); expect(wrapper.state('showUnreadToast')).toBe(true); }); test('Should have unread toast channel is marked as unread', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], channelMarkedAsUnread: false, atBottom: true, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(false); wrapper.setProps({channelMarkedAsUnread: true, atBottom: false}); expect(wrapper.state('showUnreadToast')).toBe(true); }); test('Should have unread toast channel is marked as unread again', () => { const props = { ...baseProps, channelMarkedAsUnread: false, atLatestPost: true, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(false); wrapper.setProps({ channelMarkedAsUnread: true, postListIds: [ 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }); expect(wrapper.state('showUnreadToast')).toBe(true); wrapper.setProps({atBottom: true}); expect(wrapper.state('showUnreadToast')).toBe(false); wrapper.setProps({atBottom: false}); wrapper.setProps({lastViewedAt: 12342}); expect(wrapper.state('showUnreadToast')).toBe(true); }); test('Should have archive toast if channel is not atLatestPost and focusedPostId exists', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: false, atBottom: null, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showMessageHistoryToast')).toBe(undefined); wrapper.setProps({atBottom: false}); expect(wrapper.state('showMessageHistoryToast')).toBe(true); }); test('Should have archive toast if channel initScrollOffsetFromBottom is greater than 1000 and focusedPostId exists', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: true, initScrollOffsetFromBottom: 1001, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showMessageHistoryToast')).toBe(true); }); test('Should not have unread toast if channel is marked as unread and at bottom', () => { const props = { ...baseProps, channelMarkedAsUnread: false, atLatestPost: true, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(false); wrapper.setProps({atBottom: true}); wrapper.setProps({ channelMarkedAsUnread: true, postListIds: [ 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }); expect(wrapper.state('showUnreadToast')).toBe(false); }); test('Should have showNewMessagesToast if there are unreads and lastViewedAt is less than latestPostTimeStamp', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); wrapper.setState({showUnreadToast: false, lastViewedBottom: 1234}); wrapper.setProps({latestPostTimeStamp: 1235}); expect(wrapper.state('showNewMessagesToast')).toBe(true); }); test('Should hide unread toast if atBottom is true', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(true); wrapper.setProps({atBottom: true}); expect(wrapper.state('showUnreadToast')).toBe(false); }); test('Should hide archive toast if channel is atBottom is true', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: true, initScrollOffsetFromBottom: 1001, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showMessageHistoryToast')).toBe(true); wrapper.setProps({atBottom: true}); expect(wrapper.state('showMessageHistoryToast')).toBe(false); }); test('Should hide showNewMessagesToast if atBottom is true', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); wrapper.setState({showUnreadToast: false}); wrapper.setProps({latestPostTimeStamp: 1235, lastViewedBottom: 1234}); expect(wrapper.state('showNewMessagesToast')).toBe(true); wrapper.setProps({atBottom: true}); expect(wrapper.state('showNewMessagesToast')).toBe(false); }); test('Should hide unread toast on scrollToNewMessage', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(true); (wrapper.instance() as ToastWrapperClass).scrollToLatestMessages(); expect(wrapper.state('showUnreadToast')).toBe(false); expect(baseProps.scrollToLatestMessages).toHaveBeenCalledTimes(1); }); test('Should hide new messages toast if lastViewedBottom is not less than latestPostTimeStamp', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); wrapper.setState({showUnreadToast: false}); wrapper.setProps({lastViewedBottom: 1234, latestPostTimeStamp: 1235, atBottom: false}); expect(wrapper.state('showNewMessagesToast')).toBe(true); wrapper.setProps({lastViewedBottom: 1235, latestPostTimeStamp: 1235}); (wrapper.instance() as ToastWrapperClass).scrollToNewMessage(); expect(wrapper.state('showNewMessagesToast')).toBe(false); expect(baseProps.scrollToNewMessage).toHaveBeenCalledTimes(1); }); test('Should hide unread toast if esc key is pressed', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(true); (wrapper.instance() as ToastWrapperClass).handleShortcut({key: 'ESC', keyCode: 27} as KeyboardEvent); expect(wrapper.state('showUnreadToast')).toBe(false); }); test('Should call for updateLastViewedBottomAt when new messages toast is present and if esc key is pressed', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); wrapper.setState({atBottom: false, showUnreadToast: false}); wrapper.setProps({atBottom: false, lastViewedBottom: 1234, latestPostTimeStamp: 1235}); expect(wrapper.state('showNewMessagesToast')).toBe(true); (wrapper.instance() as ToastWrapperClass).handleShortcut({key: 'ESC', keyCode: 27} as KeyboardEvent); expect(baseProps.updateLastViewedBottomAt).toHaveBeenCalledTimes(1); }); test('Changing unreadCount to 0 should set the showNewMessagesToast state to false', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ //order of the postIds is in reverse order so unreadCount should be 3 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); wrapper.setState({atBottom: false, showUnreadToast: false}); wrapper.setProps({atBottom: false, lastViewedBottom: 1234, latestPostTimeStamp: 1235}); expect(wrapper.state('showNewMessagesToast')).toBe(true); wrapper.setProps({postListIds: baseProps.postListIds}); expect(wrapper.state('showNewMessagesToast')).toBe(false); }); test('Should call updateToastStatus on toasts state change', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, }; const updateToastStatus = baseProps.actions.updateToastStatus; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadToast')).toBe(true); expect(updateToastStatus).toHaveBeenCalledWith(true); wrapper.setProps({atBottom: true, atLatestPost: true}); expect(updateToastStatus).toHaveBeenCalledTimes(2); expect(updateToastStatus).toHaveBeenCalledWith(false); }); test('Should call updateNewMessagesAtInChannel on addition of posts at the bottom of channel and user not at bottom', () => { const props = { ...baseProps, atLatestPost: true, postListIds: [ 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], atBottom: true, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); wrapper.setProps({atBottom: null}); wrapper.setProps({ postListIds: [ 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }); //should not call if atBottom is null expect(baseProps.updateNewMessagesAtInChannel).toHaveBeenCalledTimes(0); wrapper.setProps({ atBottom: false, postListIds: [ 'post0', 'post1', 'post2', 'post3', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post4', 'post5', ], }); expect(baseProps.updateNewMessagesAtInChannel).toHaveBeenCalledTimes(1); }); test('Should have unreadWithBottomStart toast if lastViewdAt and props.lastViewedAt !== prevState.lastViewedAt and shouldStartFromBottomWhenUnread and unreadCount > 0 and not isNewMessageLineReached ', () => { const props = { ...baseProps, lastViewedAt: 20000, unreadCountInChannel: 10, shouldStartFromBottomWhenUnread: true, isNewMessageLineReached: false, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadWithBottomStartToast')).toBe(true); }); test('Should hide unreadWithBottomStart toast if isNewMessageLineReached is set true', () => { const props = { ...baseProps, unreadCountInChannel: 10, shouldStartFromBottomWhenUnread: true, isNewMessageLineReached: false, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showUnreadWithBottomStartToast')).toBe(true); wrapper.setProps({isNewMessageLineReached: true}); expect(wrapper.state('showUnreadWithBottomStartToast')).toBe(false); }); }); describe('History toast', () => { test('Replace browser history when not at latest posts and in permalink view with call to scrollToLatestMessages', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: false, atBottom: false, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showMessageHistoryToast')).toBe(true); const instance = wrapper.instance() as ToastWrapperClass; instance.scrollToLatestMessages(); expect(getHistory().replace).toHaveBeenCalledWith('/team'); }); test('Replace browser history when not at latest posts and in permalink view with call to scrollToNewMessage', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: false, atBottom: false, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.state('showMessageHistoryToast')).toBe(true); const instance = wrapper.instance() as ToastWrapperClass; instance.scrollToNewMessage(); expect(getHistory().replace).toHaveBeenCalledWith('/team'); }); }); describe('Search hint toast', () => { test('should not be shown when unread toast should be shown', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, showSearchHintToast: true, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.find('.toast__hint')).toEqual({}); }); test('should not be shown when history toast should be shown', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: false, atBottom: false, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.find('.toast__hint')).toEqual({}); }); test('should be shown when no other toasts are shown', () => { const props = { ...baseProps, showSearchHintToast: true, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); expect(wrapper.find('.toast__hint')).toBeDefined(); }); test('should call the dismiss callback', () => { const dismissHandler = jest.fn(); const props = { ...baseProps, showSearchHintToast: true, onSearchHintDismiss: dismissHandler, }; const wrapper = shallowWithIntl(<ToastWrapper {...props}/>); const instance = wrapper.instance() as ToastWrapperClass; instance.hideSearchHintToast(); expect(dismissHandler).toHaveBeenCalled(); }); }); describe('Scroll-to-bottom toast', () => { test('should not be shown when unread toast should be shown', () => { const props = { ...baseProps, unreadCountInChannel: 10, newRecentMessagesCount: 5, showScrollToBottomToast: true, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToast = screen.queryByTestId(SCROLL_TO_BOTTOM_TOAST_TESTID); expect(scrollToBottomToast).not.toBeInTheDocument(); }); test('should not be shown when history toast should be shown', () => { const props = { ...baseProps, focusedPostId: 'asdasd', atLatestPost: false, atBottom: false, showScrollToBottomToast: true, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToast = screen.queryByTestId(SCROLL_TO_BOTTOM_TOAST_TESTID); expect(scrollToBottomToast).not.toBeInTheDocument(); }); test('should NOT be shown if showScrollToBottomToast is false', () => { const props = { ...baseProps, showScrollToBottomToast: false, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToast = screen.queryByTestId(SCROLL_TO_BOTTOM_TOAST_TESTID); expect(scrollToBottomToast).not.toBeInTheDocument(); }); test('should be shown when no other toasts are shown', () => { const props = { ...baseProps, showSearchHintToast: false, showScrollToBottomToast: true, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToast = screen.queryByTestId(SCROLL_TO_BOTTOM_TOAST_TESTID); expect(scrollToBottomToast).toBeInTheDocument(); }); test('should be shown along side with Search hint toast', () => { const props = { ...baseProps, showSearchHintToast: true, showScrollToBottomToast: true, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToast = screen.queryByTestId(SCROLL_TO_BOTTOM_TOAST_TESTID); const hintToast = screen.queryByTestId(HINT_TOAST_TESTID); // Assert that both components exist expect(scrollToBottomToast).toBeInTheDocument(); expect(hintToast).toBeInTheDocument(); }); test('should call scrollToLatestMessages on click, and hide this toast (do not call dismiss function)', () => { const props = { ...baseProps, showScrollToBottomToast: true, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToast = screen.getByTestId(SCROLL_TO_BOTTOM_TOAST_TESTID); fireEvent.click(scrollToBottomToast); expect(baseProps.scrollToLatestMessages).toHaveBeenCalledTimes(1); // * Do not dismiss the toast, hide it only expect(baseProps.onScrollToBottomToastDismiss).toHaveBeenCalledTimes(0); expect(baseProps.hideScrollToBottomToast).toHaveBeenCalledTimes(1); }); test('should call the dismiss callback', () => { const props = { ...baseProps, showScrollToBottomToast: true, }; renderWithContext(<ToastWrapper {...props}/>); const scrollToBottomToastDismiss = screen.getByTestId(SCROLL_TO_BOTTOM_DISMISS_BUTTON_TESTID); fireEvent.click(scrollToBottomToastDismiss); expect(baseProps.onScrollToBottomToastDismiss).toHaveBeenCalledTimes(1); }); }); });
3,440
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal/trial_benefits_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 {Provider} from 'react-redux'; import {GenericModal} from '@mattermost/components'; import {trackEvent} from 'actions/telemetry_actions.jsx'; import Carousel from 'components/common/carousel/carousel'; import TrialBenefitsModal from 'components/trial_benefits_modal/trial_benefits_modal'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {TELEMETRY_CATEGORIES} from 'utils/constants'; const mockLocation = {pathname: '', search: '', hash: ''}; jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); jest.mock('components/admin_console/blockable_link', () => { return () => { return <div/>; }; }); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom') as typeof import('react-router-dom'), useLocation: () => mockLocation, })); describe('components/trial_benefits_modal/trial_benefits_modal', () => { // required state to mount using the provider const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'false', }, }, }, views: { modals: { modalState: { trial_benefits_modal: { open: 'true', }, }, }, admin: { navigationBlock: { blocked: true, }, }, }, }; const props = { onExited: jest.fn(), trialJustStarted: false, }; const store = mockStore(state); test('should match snapshot', () => { const wrapper = shallow( <Provider store={store}> <TrialBenefitsModal {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when trial has already started', () => { const wrapper = shallow( <Provider store={store}> <TrialBenefitsModal {...props} trialJustStarted={true} /> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should show the benefits modal', () => { const wrapper = mountWithIntl( <Provider store={store}> <TrialBenefitsModal {...props}/> </Provider>, ); expect(wrapper.find('TrialBenefitsModal').find('Carousel')).toHaveLength(1); }); test('should hide the benefits modal', () => { const trialBenefitsModalHidden = { modals: { modalState: {}, }, }; const localStore = {...state, views: trialBenefitsModalHidden}; const store = mockStore(localStore); const wrapper = mountWithIntl( <Provider store={store}> <TrialBenefitsModal {...props}/> </Provider>, ); expect(wrapper.find('TrialBenefitsModal').find('Carousel')).toHaveLength(0); }); test('should call on close', () => { const mockOnClose = jest.fn(); const wrapper = mountWithIntl( <Provider store={store}> <TrialBenefitsModal {...props} onClose={mockOnClose} trialJustStarted={true} /> </Provider>, ); wrapper.find(GenericModal).props().onExited(); expect(mockOnClose).toHaveBeenCalled(); }); test('should call on exited', () => { const mockOnExited = jest.fn(); const wrapper = mountWithIntl( <Provider store={store}> <TrialBenefitsModal {...props} onExited={mockOnExited} /> </Provider>, ); wrapper.find(GenericModal).props().onExited(); expect(mockOnExited).toHaveBeenCalled(); }); test('should handle slide prev next click', () => { const wrapper = mountWithIntl( <Provider store={store}> <TrialBenefitsModal {...props} /> </Provider>, ); wrapper.find(Carousel).props().onNextSlideClick!(5); expect(trackEvent).toHaveBeenCalledWith( TELEMETRY_CATEGORIES.SELF_HOSTED_START_TRIAL_MODAL, 'benefits_modal_post_enterprise_view', ); wrapper.find(Carousel).props().onNextSlideClick!(4); expect(trackEvent).toHaveBeenCalledWith( TELEMETRY_CATEGORIES.SELF_HOSTED_START_TRIAL_MODAL, 'benefits_modal_slide_shown_playbooks', ); wrapper.find(Carousel).props().onPrevSlideClick!(2); expect(trackEvent).toHaveBeenCalledWith( TELEMETRY_CATEGORIES.SELF_HOSTED_START_TRIAL_MODAL, 'benefits_modal_slide_shown_ldap', ); }); test('should present the just started trial modal content', () => { const wrapper = mountWithIntl( <Provider store={store}> <TrialBenefitsModal {...props} trialJustStarted={true} /> </Provider>, ); const title = wrapper.find('#trialBenefitsModalStarted-trialStart div.title').text(); expect(title).toBe('Your trial has started! Explore the benefits of Enterprise'); }); test('should have a shorter title and not include the cta button when in cloud env', () => { const cloudState = {...state, entities: {...state.entities, general: {...state.entities.general, license: {Cloud: 'true'}}}}; const cloudStore = mockStore(cloudState); const wrapper = mountWithIntl( <Provider store={cloudStore}> <TrialBenefitsModal {...props} trialJustStarted={true} /> </Provider>, ); const title = wrapper.find('#trialBenefitsModalStarted-trialStart div.title').text(); expect(title).toBe('Your trial has started!'); const ctaBtn = wrapper.find('#trialBenefitsModalStarted-trialStart button.btn-primary'); expect(ctaBtn).toHaveLength(0); }); test('should show the invite people call to action when trial started from the team', () => { const cloudState = {...state, entities: {...state.entities, general: {...state.entities.general, license: {Cloud: 'true'}}}}; const cloudStore = mockStore(cloudState); const wrapper = mountWithIntl( <Provider store={cloudStore}> <TrialBenefitsModal {...props} trialJustStarted={true} /> </Provider>, ); const title = wrapper.find('#trialBenefitsModalStarted-trialStart div.title').text(); expect(title).toBe('Your trial has started!'); const ctaBtn = wrapper.find('.buttons-section-wrapper a span'); expect(ctaBtn.text()).toBe('Invite people'); }); test('should show hide the invite people call to action when trial started from system console', () => { const cloudState = {...state, entities: {...state.entities, general: {...state.entities.general, license: {Cloud: 'true'}}}}; const cloudStore = mockStore(cloudState); mockLocation.pathname = '/admin_console'; const wrapper = mountWithIntl( <Provider store={cloudStore}> <TrialBenefitsModal {...props} trialJustStarted={true} /> </Provider>, ); const title = wrapper.find('#trialBenefitsModalStarted-trialStart div.title').text(); expect(title).toBe('Your trial has started!'); const ctaBtn = wrapper.find('.buttons-section-wrapper a span'); expect(ctaBtn.text()).toBe('Close'); }); });
3,443
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal/trial_benefits_modal_step.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 TrialBenefitsModalStep from 'components/trial_benefits_modal/trial_benefits_modal_step'; describe('components/trial_benefits_modal/trial_benefits_modal_step', () => { const props = { id: 'stepId', title: 'Step title', description: 'Step description', svgWrapperClassName: 'stepClassname', svgElement: <svg/>, buttonLabel: 'button', }; test('should match snapshot', () => { const wrapper = shallow( <TrialBenefitsModalStep {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with optional params', () => { const wrapper = shallow( <TrialBenefitsModalStep {...props} bottomLeftMessage='Step bottom message' pageURL='/test/page' onClose={jest.fn()} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,446
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal/trial_benefits_modal_step_more.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 {useHistory} from 'react-router-dom'; import {trackEvent} from 'actions/telemetry_actions.jsx'; import TrialBenefitsModalStepMore from 'components/trial_benefits_modal/trial_benefits_modal_step_more'; import {TELEMETRY_CATEGORIES} from 'utils/constants'; jest.mock('react-router-dom', () => { const original = jest.requireActual('react-router-dom'); return { ...original, useHistory: jest.fn().mockReturnValue({ push: jest.fn(), }), }; }); jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); describe('components/trial_benefits_modal/trial_benefits_modal_step_more', () => { const props = { id: 'thing', route: '/test/page', message: 'Test Message', }; test('should match snapshot', () => { const wrapper = shallow( <TrialBenefitsModalStepMore {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should handle on click', () => { const mockHistory = useHistory(); const mockOnClick = jest.fn(); const wrapper = shallow( <TrialBenefitsModalStepMore {...props} onClick={mockOnClick} />, ); wrapper.find('.learn-more-button').simulate('click'); expect(mockHistory.push).toHaveBeenCalledWith(props.route); expect(mockOnClick).toHaveBeenCalled(); expect(trackEvent).toHaveBeenCalledWith(TELEMETRY_CATEGORIES.SELF_HOSTED_START_TRIAL_MODAL, 'benefits_modal_section_opened_thing'); }); });
3,448
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal/__snapshots__/trial_benefits_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/trial_benefits_modal/trial_benefits_modal should match snapshot 1`] = ` <ContextProvider value={ Object { "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "subscription": Subscription { "handleChangeWrapper": [Function], "listeners": Object { "notify": [Function], }, "onStateChange": [Function], "parentSub": undefined, "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "unsubscribe": null, }, } } > <TrialBenefitsModal onExited={[MockFunction]} trialJustStarted={false} /> </ContextProvider> `; exports[`components/trial_benefits_modal/trial_benefits_modal should match snapshot when trial has already started 1`] = ` <ContextProvider value={ Object { "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "subscription": Subscription { "handleChangeWrapper": [Function], "listeners": Object { "notify": [Function], }, "onStateChange": [Function], "parentSub": undefined, "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "unsubscribe": null, }, } } > <TrialBenefitsModal onExited={[MockFunction]} trialJustStarted={true} /> </ContextProvider> `;
3,449
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal/__snapshots__/trial_benefits_modal_step.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/trial_benefits_modal/trial_benefits_modal_step should match snapshot 1`] = ` <div className="TrialBenefitsModalStep slide-container" id="trialBenefitsModalStep-stepId" > <div className="title" > Step title </div> <div className="description" > Step description </div> <div className="stepClassname svg-wrapper" > <svg /> </div> </div> `; exports[`components/trial_benefits_modal/trial_benefits_modal_step should match snapshot with optional params 1`] = ` <div className="TrialBenefitsModalStep slide-container" id="trialBenefitsModalStep-stepId" > <div className="title" > Step title </div> <div className="description" > Step description </div> <TrialBenefitsModalStepMore id="stepId" message="button" onClick={[MockFunction]} route="/test/page" /> <div className="stepClassname svg-wrapper" > <svg /> </div> <div className="bottom-text-left-message" > Step bottom message </div> </div> `;
3,450
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/trial_benefits_modal/__snapshots__/trial_benefits_modal_step_more.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/trial_benefits_modal/trial_benefits_modal_step_more should match snapshot 1`] = ` <a className="TrialBenefitsModalStepMore learn-more-button" onClick={[Function]} > Test Message </a> `;
3,452
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/unarchive_channel_modal/unarchive_channel_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 {Modal} from 'react-bootstrap'; import {TestHelper} from 'utils/test_helper'; import UnarchiveChannelModal from './unarchive_channel_modal'; describe('components/unarchive_channel_modal', () => { const channel = TestHelper.getChannelMock({ create_at: 1508265709607, creator_id: 'zaktnt8bpbgu8mb6ez9k64r7sa', delete_at: 0, display_name: 'testing', header: 'test', id: 'owsyt8n43jfxjpzh9np93mx1wa', last_post_at: 1508265709635, name: 'testing', purpose: 'test', team_id: 'eatxocwc3bg9ffo9xyybnj4omr', type: 'O', update_at: 1508265709607, }); const currentTeamDetails = { name: 'mattermostDev', }; const baseProps = { channel, currentTeamDetails, actions: { unarchiveChannel: jest.fn(), }, onExited: jest.fn(), penultimateViewedChannelName: 'my-prev-channel', }; test('should match snapshot for unarchive_channel_modal', () => { const wrapper = shallow( <UnarchiveChannelModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match state when onHide is called', () => { const wrapper = shallow<UnarchiveChannelModal>( <UnarchiveChannelModal {...baseProps}/>, ); wrapper.setState({show: true}); wrapper.instance().onHide(); expect(wrapper.state('show')).toEqual(false); }); test('should have called actions.unarchiveChannel when handleUnarchive is called', () => { const actions = {unarchiveChannel: jest.fn()}; const props = {...baseProps, actions}; const wrapper = shallow<UnarchiveChannelModal>( <UnarchiveChannelModal {...props}/>, ); wrapper.setState({show: true}); wrapper.instance().handleUnarchive(); expect(actions.unarchiveChannel).toHaveBeenCalledTimes(1); expect(actions.unarchiveChannel).toHaveBeenCalledWith(props.channel.id); }); test('should have called props.onHide when Modal.onExited is called', () => { const wrapper = shallow( <UnarchiveChannelModal {...baseProps}/>, ); wrapper.find(Modal).props().onExited!(document.createElement('div')); expect(baseProps.onExited).toHaveBeenCalledTimes(1); }); });
3,454
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/unarchive_channel_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/unarchive_channel_modal/__snapshots__/unarchive_channel_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/unarchive_channel_modal should match snapshot for unarchive_channel_modal 1`] = ` <Modal animation={true} aria-labelledby="unarchiveChannelModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal" dialogComponentClass={[Function]} enforceFocus={true} id="unarchiveChannelModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} 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="unarchiveChannelModalLabel" > <MemoizedFormattedMessage defaultMessage="Confirm UNARCHIVE Channel" id="unarchive_channel.confirm" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="alert alert-danger" > <FormattedMarkdownMessage defaultMessage="Are you sure you wish to unarchive the **{display_name}** channel?" id="unarchive_channel.viewArchived.question" values={ Object { "display_name": "testing", } } /> </div> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-tertiary" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Cancel" id="unarchive_channel.cancel" /> </button> <button autoFocus={true} className="btn btn-danger" data-dismiss="modal" id="unarchiveChannelModalDeleteButton" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Unarchive" id="unarchive_channel.del" /> </button> </ModalFooter> </Modal> `;
3,457
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/update_user_group_modal/update_user_group_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 UpdateUserGroupModal from './update_user_group_modal'; describe('component/update_user_group_modal', () => { const baseProps = { onExited: jest.fn(), groupId: 'groupid123', group: { id: 'groupid123', name: 'group', display_name: 'Group Name', description: 'Group description', source: 'custom', remote_id: null, create_at: 1637349374137, update_at: 1637349374137, delete_at: 0, has_syncables: false, member_count: 6, allow_reference: true, scheme_admin: false, }, backButtonCallback: jest.fn(), actions: { patchGroup: jest.fn().mockImplementation(() => Promise.resolve()), openModal: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <UpdateUserGroupModal {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,459
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/update_user_group_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/update_user_group_modal/__snapshots__/update_user_group_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/update_user_group_modal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="createUserGroupsModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal user-groups-modal-update" dialogComponentClass={[Function]} enforceFocus={true} id="createUserGroupsModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <button aria-label="Back" className="modal-header-back-button btn btn-icon" onClick={[Function]} type="button" > <i className="icon icon-arrow-left" /> </button> <ModalTitle bsClass="modal-title" componentClass="h1" id="updateGroupsModalTitle" > <MemoizedFormattedMessage defaultMessage="Edit Group Details" id="user_groups_modal.editGroupTitle" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" className="overflow--visible" componentClass="div" > <div className="user-groups-modal__content" > <div className="group-name-input-wrapper" > <ForwardRef autoFocus={true} customMessage={ Object { "type": "error", "value": "", } } data-testid="nameInput" onChange={[Function]} placeholder="Name" type="text" value="Group Name" /> </div> <div className="group-mention-input-wrapper" > <ForwardRef customMessage={ Object { "type": "error", "value": "", } } data-testid="nameInput" onChange={[Function]} placeholder="Mention" type="text" value="@group" /> </div> <div className="update-buttons-wrapper" > <button className="btn btn-tertiary" onClick={[Function]} > Back </button> <SaveButton btnClass="" defaultMessage="Save Details" disabled={true} extraClasses="" id="saveItems" onClick={[Function]} saving={false} savingMessage="Saving..." /> </div> </div> </ModalBody> </Modal> `;
3,464
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover/user_group_popover.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ReactWrapper} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import {BrowserRouter} from 'react-router-dom'; import type {Group} from '@mattermost/types/groups'; import type {UserProfile} from '@mattermost/types/users'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {act} from 'tests/react_testing_utils'; import mockStore from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; import UserGroupPopover from './user_group_popover'; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn().mockReturnValue(() => {}), })); jest.mock('react-virtualized-auto-sizer', () => ({children}: {children: any}) => children({height: 100, width: 100}), ); const actImmediate = (wrapper: ReactWrapper) => act( () => new Promise<void>((resolve) => { setImmediate(() => { wrapper.update(); resolve(); }); }), ); describe('component/user_group_popover', () => { const profiles: Record<string, UserProfile> = {}; const profilesInGroup: Record<Group['id'], Set<UserProfile['id']>> = {}; const group1 = TestHelper.getGroupMock({ id: 'group1', member_count: 15, }); const group2 = TestHelper.getGroupMock({ id: 'group2', member_count: 5, }); profilesInGroup[group1.id] = new Set(); profilesInGroup[group2.id] = new Set(); for (let i = 0; i < 15; ++i) { const user = TestHelper.getUserMock({ id: 'id' + i, username: 'username' + i, first_name: 'Name' + i, last_name: 'Surname' + i, email: 'test' + i + '@test.com', }); profiles[user.id] = user; profilesInGroup[group1.id].add(user.id); if (i < 5) { profilesInGroup[group2.id].add(user.id); } } const initialState = { entities: { teams: { currentTeamId: 'team_id1', teams: { team_id1: { id: 'team_id1', name: 'team1', }, }, }, general: { config: {}, }, users: { profiles, profilesInGroup, }, preferences: { myPreferences: {}, }, }, views: { modals: { modalState: {}, }, search: { popoverSearch: '', }, }, }; const baseProps = { searchTerm: '', group: group1, canManageGroup: true, showUserOverlay: jest.fn(), hide: jest.fn(), returnFocus: jest.fn(), actions: { setPopoverSearchTerm: jest.fn(), openModal: jest.fn(), searchProfiles: jest.fn().mockImplementation(() => Promise.resolve()), }, }; test('should match snapshot', async () => { const store = await mockStore(initialState); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <UserGroupPopover {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); expect(wrapper).toMatchSnapshot(); }); test('should open modal', async () => { const store = await mockStore(initialState); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <UserGroupPopover {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); expect(wrapper.find('button.user-group-popover_header-button').exists()).toBe(true); wrapper.find('button.user-group-popover_header-button').simulate('click'); expect(baseProps.actions.openModal).toBeCalled(); expect(baseProps.hide).toBeCalled(); }); test('should not show search bar', async () => { const store = await mockStore(initialState); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <UserGroupPopover {...baseProps} group={group2} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); expect(wrapper.find('.user-group-popover_search-bar').exists()).toBe(false); }); test('should show and set search term', async () => { const store = await mockStore(initialState); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <UserGroupPopover {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); expect(wrapper.find('.user-group-popover_search-bar input').exists()).toBe(true); wrapper.find('.user-group-popover_search-bar input').simulate('change', {target: {value: 'a'}}); expect(baseProps.actions.setPopoverSearchTerm).toHaveBeenCalledWith('a'); }); test('should show users', async () => { const store = await mockStore(initialState); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <UserGroupPopover {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); expect(wrapper.find('.group-member-list_item').length).toBeGreaterThan(0); }); });
3,466
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover/__snapshots__/user_group_popover.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/user_group_popover should match snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <BrowserRouter> <Router history={ Object { "action": "POP", "block": [Function], "createHref": [Function], "go": [Function], "goBack": [Function], "goForward": [Function], "length": 1, "listen": [Function], "location": Object { "hash": "", "pathname": "undefinedundefined", "search": "", "state": undefined, }, "push": [Function], "replace": [Function], } } > <Memo(UserGroupPopover) actions={ Object { "openModal": [MockFunction], "searchProfiles": [MockFunction], "setPopoverSearchTerm": [MockFunction] { "calls": Array [ Array [ "", ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, } } canManageGroup={true} group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "group1", "member_count": 15, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[MockFunction]} returnFocus={[MockFunction]} searchTerm="" showUserOverlay={[MockFunction]} > <Popover actions={ Object { "openModal": [MockFunction], "searchProfiles": [MockFunction], "setPopoverSearchTerm": [MockFunction] { "calls": Array [ Array [ "", ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, } } canManageGroup={true} group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "group1", "member_count": 15, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[MockFunction]} id="user-group-popover" placement="right" popoverSize="sm" popoverStyle="info" returnFocus={[MockFunction]} searchTerm="" showUserOverlay={[MockFunction]} > <Popover bsClass="popover" bsSize="small" bsStyle="info" id="user-group-popover" placement="right" > <div className="popover popover-sm popover-info right" id="user-group-popover" role="tooltip" style={ Object { "display": "block", "left": undefined, "top": undefined, } } > <div className="arrow" style={ Object { "left": undefined, "top": undefined, } } /> <div className="popover-content" > <span onFocus={[Function]} tabIndex={0} /> <Body aria-label="group_display_name" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div aria-label="group_display_name" aria-modal={true} className="Body-jPXXyK jkivLB a11y__popup" onKeyDown={[Function]} role="dialog" > <Header> <div className="Header-ibKheB hIZrPW" > <Heading> <div className="Heading-dalVaC VzXTr" > <Title className="overflow--ellipsis text-nowrap" > <span className="Title-gqsoLG eUZcLS overflow--ellipsis text-nowrap" > group_display_name </span> </Title> <CloseButton aria-label="Close" className="btn btn-sm btn-compact btn-icon" onClick={[Function]} > <button aria-label="Close" className="CloseButton-lhxEdi gyMeQZ btn btn-sm btn-compact btn-icon" onClick={[Function]} > <i className="icon icon-close" /> </button> </CloseButton> </div> </Heading> <Subtitle> <div className="Subtitle-ocLvS yXVnq" > <span className="overflow--ellipsis text-nowrap" > @ group_name </span> <Dot> <span className="NoShrink-kvXWXm Dot-etDJYJ wzpro jiooBj" > • </span> </Dot> <FormattedMessage defaultMessage="{member_count} {member_count, plural, one {Member} other {Members}}" id="user_group_popover.memberCount" tagName={ Object { "$$typeof": Symbol(react.forward_ref), "attrs": Array [], "componentStyle": e { "baseHash": -1318562053, "baseStyle": undefined, "componentId": "NoShrink-kvXWXm", "isStatic": false, "rules": Array [ "flex:0 0 auto;", ], "staticRulesId": "", }, "foldedComponentIds": Array [], "render": [Function], "shouldForwardProp": undefined, "styledComponentId": "NoShrink-kvXWXm", "target": "span", "toString": [Function], "warnTooManyClasses": [Function], "withComponent": [Function], } } values={ Object { "member_count": 15, } } > <NoShrink> <span className="NoShrink-kvXWXm wzpro" > 15 Members </span> </NoShrink> </FormattedMessage> </div> </Subtitle> <HeaderButton aria-label="group_display_name @group_name 15 Members View full group info" className="user-group-popover_header-button" onClick={[Function]} > <button aria-label="group_display_name @group_name 15 Members View full group info" className="HeaderButton-jHgPlb jFywol user-group-popover_header-button" onClick={[Function]} /> </HeaderButton> </div> </Header> <SearchBar> <div className="SearchBar-cqKmJF easqtW" > <MagnifyIcon> <svg fill="currentColor" height="1em" version="1.1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M20.224,18.829l-3.775-3.775C17.418,13.791,18,12.215,18,10.5C18,6.358,14.642,3,10.5,3S3,6.358,3,10.5S6.358,18,10.5,18c1.708,0,3.278-0.578,4.539-1.539l3.775,3.749c0.39,0.388,1.02,0.388,1.41,0C20.592,19.823,20.592,19.216,20.224,18.829z M5,10.5 C5,7.462,7.462,5,10.5,5S16,7.462,16,10.5S13.538,16,10.5,16S5,13.538,5,10.5z" /> </svg> </MagnifyIcon> <QuickInput className="user-group-popover_search-bar" clearable={true} delayInputUpdate={false} onChange={[Function]} onClear={[Function]} placeholder="Search members" tooltipPosition="bottom" type="text" value="" > <div> <input className="user-group-popover_search-bar" defaultValue="" onChange={[Function]} placeholder="Search members" type="text" /> </div> </QuickInput> </div> </SearchBar> <Connect(Component) group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "group1", "member_count": 15, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[MockFunction]} searchState={0} showUserOverlay={[MockFunction]} > <Memo(GroupMemberList) actions={ Object { "closeRightHandSide": [Function], "getUsersInGroup": [Function], "openDirectChannelToUserId": [Function], } } group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "group1", "member_count": 15, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[MockFunction]} members={ Array [ Object { "displayName": "username0", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name0", "id": "id0", "is_bot": false, "last_activity_at": 0, "last_name": "Surname0", "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": "username0", }, }, Object { "displayName": "username1", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name1", "id": "id1", "is_bot": false, "last_activity_at": 0, "last_name": "Surname1", "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": "username1", }, }, Object { "displayName": "username10", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name10", "id": "id10", "is_bot": false, "last_activity_at": 0, "last_name": "Surname10", "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": "username10", }, }, Object { "displayName": "username11", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name11", "id": "id11", "is_bot": false, "last_activity_at": 0, "last_name": "Surname11", "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": "username11", }, }, Object { "displayName": "username12", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name12", "id": "id12", "is_bot": false, "last_activity_at": 0, "last_name": "Surname12", "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": "username12", }, }, Object { "displayName": "username13", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name13", "id": "id13", "is_bot": false, "last_activity_at": 0, "last_name": "Surname13", "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": "username13", }, }, Object { "displayName": "username14", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name14", "id": "id14", "is_bot": false, "last_activity_at": 0, "last_name": "Surname14", "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": "username14", }, }, Object { "displayName": "username2", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name2", "id": "id2", "is_bot": false, "last_activity_at": 0, "last_name": "Surname2", "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": "username2", }, }, Object { "displayName": "username3", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name3", "id": "id3", "is_bot": false, "last_activity_at": 0, "last_name": "Surname3", "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": "username3", }, }, Object { "displayName": "username4", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name4", "id": "id4", "is_bot": false, "last_activity_at": 0, "last_name": "Surname4", "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": "username4", }, }, Object { "displayName": "username5", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name5", "id": "id5", "is_bot": false, "last_activity_at": 0, "last_name": "Surname5", "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": "username5", }, }, Object { "displayName": "username6", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name6", "id": "id6", "is_bot": false, "last_activity_at": 0, "last_name": "Surname6", "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": "username6", }, }, Object { "displayName": "username7", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name7", "id": "id7", "is_bot": false, "last_activity_at": 0, "last_name": "Surname7", "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": "username7", }, }, Object { "displayName": "username8", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name8", "id": "id8", "is_bot": false, "last_activity_at": 0, "last_name": "Surname8", "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": "username8", }, }, Object { "displayName": "username9", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name9", "id": "id9", "is_bot": false, "last_activity_at": 0, "last_name": "Surname9", "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": "username9", }, }, ] } searchState={0} searchTerm="" showUserOverlay={[MockFunction]} teamUrl="/team1" > <UserList role="list" style={ Object { "height": 307.20000000000005, } } > <div className="UserList-XqScV gnsdGQ" role="list" style={ Object { "height": 307.20000000000005, } } > <Component> <InfiniteLoader isItemLoaded={[Function]} itemCount={15} loadMoreItems={[Function]} threshold={5} > <List direction="ltr" height={100} itemCount={15} itemSize={[Function]} layout="vertical" onItemsRendered={[Function]} overscanCount={2} useIsScrolling={false} width={100} > <div onScroll={[Function]} style={ Object { "WebkitOverflowScrolling": "touch", "direction": "ltr", "height": 100, "overflow": "auto", "position": "relative", "width": 100, "willChange": "transform", } } > <div style={ Object { "height": 708, "pointerEvents": undefined, "width": "100%", } } > <Item index={0} key="0" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 0, "width": "100%", } } > <UserListItem className="group-member-list_item" first={true} key="id0" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 0, "width": "100%", } } > <div className="UserListItem-iCIMiI bTPvin group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 0, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id0/image?_=0" username="username0" > <img alt="username0 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id0/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > username0 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id0" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id0" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id0" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to username0" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to username0" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={1} key="1" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 48, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id1" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 48, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 48, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id1/image?_=0" username="username1" > <img alt="username1 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id1/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > username1 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id1" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id1" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id1" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to username1" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to username1" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={2} key="2" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 88, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id10" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 88, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 88, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id10/image?_=0" username="username10" > <img alt="username10 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id10/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > username10 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id10" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id10" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id10" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to username10" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to username10" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={3} key="3" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 128, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id11" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 128, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 128, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id11/image?_=0" username="username11" > <img alt="username11 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id11/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > username11 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id11" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id11" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id11" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to username11" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to username11" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={4} key="4" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 168, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id12" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 168, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 168, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id12/image?_=0" username="username12" > <img alt="username12 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id12/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > username12 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id12" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id12" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id12" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to username12" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to username12" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> </div> </div> </List> </InfiniteLoader> </Component> </div> </UserList> </Memo(GroupMemberList)> </Connect(Component)> </div> </Body> <span onFocus={[Function]} tabIndex={0} /> </div> </div> </Popover> </Popover> </Memo(UserGroupPopover)> </Router> </BrowserRouter> </Provider> `;
3,467
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover/group_member_list/group_member_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ReactWrapper} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import {BrowserRouter} from 'react-router-dom'; import {General} from 'mattermost-redux/constants'; import {displayUsername} from 'mattermost-redux/utils/user_utils'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {act} from 'tests/react_testing_utils'; import mockStore from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; import GroupMemberList from './group_member_list'; import type {GroupMember} from './group_member_list'; import {Load} from '../constants'; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn().mockReturnValue(() => {}), })); jest.mock('react-virtualized-auto-sizer', () => ({children}: {children: any}) => children({height: 100, width: 100}), ); const actImmediate = (wrapper: ReactWrapper) => act( () => new Promise<void>((resolve) => { setImmediate(() => { wrapper.update(); resolve(); }); }), ); describe('component/user_group_popover/group_member_list', () => { const group = TestHelper.getGroupMock({ member_count: 5, }); const members: GroupMember[] = []; for (let i = 0; i < 5; ++i) { const user = TestHelper.getUserMock({ id: 'id' + i, username: 'username' + i, first_name: 'Name' + i, last_name: 'Surname' + i, email: 'test' + i + '@test.com', }); const displayName = displayUsername(user, General.TEAMMATE_NAME_DISPLAY.SHOW_FULLNAME); members.push({user, displayName}); } const baseProps = { searchTerm: '', group, canManageGroup: true, showUserOverlay: jest.fn(), hide: jest.fn(), searchState: Load.DONE, members, teamUrl: 'team', actions: { getUsersInGroup: jest.fn().mockImplementation(() => Promise.resolve()), openDirectChannelToUserId: jest.fn().mockImplementation(() => Promise.resolve()), closeRightHandSide: jest.fn(), }, }; test('should match snapshot', async () => { const store = await mockStore({}); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <GroupMemberList {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); expect(wrapper).toMatchSnapshot(); }); test('should open dms', async () => { const store = await mockStore({}); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <GroupMemberList {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); wrapper.find('.group-member-list_dm-button').first().simulate('click'); expect(baseProps.actions.openDirectChannelToUserId).toBeCalledTimes(0); }); test('should show user overlay and hide', async () => { const store = await mockStore({}); const wrapper = mountWithIntl( <Provider store={store}> <BrowserRouter> <GroupMemberList {...baseProps} /> </BrowserRouter> </Provider>, ); await actImmediate(wrapper); wrapper.find('.group-member-list_item').first().simulate('click'); expect(baseProps.showUserOverlay).toBeCalledTimes(0); expect(baseProps.hide).toBeCalledTimes(0); }); });
3,470
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover/group_member_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_group_popover/group_member_list/__snapshots__/group_member_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/user_group_popover/group_member_list should match snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <BrowserRouter> <Router history={ Object { "action": "POP", "block": [Function], "createHref": [Function], "go": [Function], "goBack": [Function], "goForward": [Function], "length": 1, "listen": [Function], "location": Object { "hash": "", "pathname": "undefinedundefined", "search": "", "state": undefined, }, "push": [Function], "replace": [Function], } } > <Memo(GroupMemberList) actions={ Object { "closeRightHandSide": [MockFunction], "getUsersInGroup": [MockFunction], "openDirectChannelToUserId": [MockFunction], } } canManageGroup={true} group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "group_id", "member_count": 5, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[MockFunction]} members={ Array [ Object { "displayName": "Name0 Surname0", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name0", "id": "id0", "is_bot": false, "last_activity_at": 0, "last_name": "Surname0", "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": "username0", }, }, Object { "displayName": "Name1 Surname1", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name1", "id": "id1", "is_bot": false, "last_activity_at": 0, "last_name": "Surname1", "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": "username1", }, }, Object { "displayName": "Name2 Surname2", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name2", "id": "id2", "is_bot": false, "last_activity_at": 0, "last_name": "Surname2", "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": "username2", }, }, Object { "displayName": "Name3 Surname3", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name3", "id": "id3", "is_bot": false, "last_activity_at": 0, "last_name": "Surname3", "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": "username3", }, }, Object { "displayName": "Name4 Surname4", "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "[email protected]", "first_name": "Name4", "id": "id4", "is_bot": false, "last_activity_at": 0, "last_name": "Surname4", "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": "username4", }, }, ] } searchState={0} searchTerm="" showUserOverlay={[MockFunction]} teamUrl="team" > <UserList role="list" style={ Object { "height": 216, } } > <div className="UserList-XqScV gnsdGQ" role="list" style={ Object { "height": 216, } } > <Component> <InfiniteLoader isItemLoaded={[Function]} itemCount={5} loadMoreItems={[Function]} threshold={5} > <List direction="ltr" height={100} itemCount={5} itemSize={[Function]} layout="vertical" onItemsRendered={[Function]} overscanCount={2} useIsScrolling={false} width={100} > <div onScroll={[Function]} style={ Object { "WebkitOverflowScrolling": "touch", "direction": "ltr", "height": 100, "overflow": "auto", "position": "relative", "width": 100, "willChange": "transform", } } > <div style={ Object { "height": 216, "pointerEvents": undefined, "width": "100%", } } > <Item index={0} key="0" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 0, "width": "100%", } } > <UserListItem className="group-member-list_item" first={true} key="id0" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 0, "width": "100%", } } > <div className="UserListItem-iCIMiI bTPvin group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 0, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id0/image?_=0" username="username0" > <img alt="username0 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id0/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > Name0 Surname0 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id0" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id0" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id0" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to Name0 Surname0" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to Name0 Surname0" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={1} key="1" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 48, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id1" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 48, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 48, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id1/image?_=0" username="username1" > <img alt="username1 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id1/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > Name1 Surname1 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id1" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id1" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id1" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to Name1 Surname1" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to Name1 Surname1" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={2} key="2" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 88, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id2" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 88, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 88, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id2/image?_=0" username="username2" > <img alt="username2 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id2/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > Name2 Surname2 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id2" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id2" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id2" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to Name2 Surname2" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to Name2 Surname2" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={3} key="3" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 128, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id3" last={false} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 128, "width": "100%", } } > <div className="UserListItem-iCIMiI cXUsja group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 128, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id3/image?_=0" username="username3" > <img alt="username3 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id3/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > Name3 Surname3 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id3" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id3" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id3" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to Name3 Surname3" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to Name3 Surname3" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> <Item index={4} key="4" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 168, "width": "100%", } } > <UserListItem className="group-member-list_item" first={false} key="id4" last={true} role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 168, "width": "100%", } } > <div className="UserListItem-iCIMiI krPIGz group-member-list_item" role="listitem" style={ Object { "height": undefined, "left": 0, "position": "absolute", "right": undefined, "top": 168, "width": "100%", } } > <UserButton aria-haspopup="dialog" onClick={[Function]} > <button aria-haspopup="dialog" className="UserButton-bZNeGd lLsMM" onClick={[Function]} > <Memo(Avatar) className="avatar-post-preview" size="sm" tabIndex={-1} url="/api/v4/users/id4/image?_=0" username="username4" > <img alt="username4 profile image" className="Avatar Avatar-sm avatar-post-preview" loading="lazy" onError={[Function]} src="/api/v4/users/id4/image?_=0" tabIndex={-1} /> </Memo(Avatar)> <Username className="overflow--ellipsis text-nowrap" > <span className="Username-hebqVM cKlgOV overflow--ellipsis text-nowrap" > Name4 Surname4 </span> </Username> <Gap className="group-member-list_gap" > <span className="Gap-pVXiI hWeVKL group-member-list_gap" /> </Gap> </button> </UserButton> <DMContainer className="group-member-list_dm-button" > <div className="DMContainer-ilPVMc Cnskx group-member-list_dm-button" > <SimpleTooltip content="Send message" id="name-id4" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="name-id4" placement="top" > Send message </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="name-id4" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > Send message </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <DMButton aria-label="Send message to Name4 Surname4" className="btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button aria-label="Send message to Name4 Surname4" className="DMButton-hIFgRF ecgFEo btn btn-icon btn-xs" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-send" /> </button> </DMButton> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> </div> </DMContainer> </div> </UserListItem> </Item> </div> </div> </List> </InfiniteLoader> </Component> </div> </UserList> </Memo(GroupMemberList)> </Router> </BrowserRouter> </Provider> `;
3,471
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/ad_ldap_upsell_banner.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import type {ReactWrapper} from 'enzyme'; import React from 'react'; import * as reactRedux from 'react-redux'; import {act} from 'tests/react_testing_utils'; import mockStore from 'tests/test_store'; import {CloudProducts, LicenseSkus} from 'utils/constants'; import ADLDAPUpsellBanner from './ad_ldap_upsell_banner'; const actImmediate = (wrapper: ReactWrapper) => act( () => new Promise<void>((resolve) => { setImmediate(() => { wrapper.update(); resolve(); }); }), ); describe('component/user_groups_modal/ad_ldap_upsell_banner', () => { const useDispatchMock = jest.spyOn(reactRedux, 'useDispatch'); const useSelectorMock = jest.spyOn(reactRedux, 'useSelector'); beforeEach(() => { useDispatchMock.mockClear(); useSelectorMock.mockClear(); }); const initState = { entities: { general: { license: { Cloud: 'false', SkuShortName: LicenseSkus.Professional, ExpiresAt: 100000000, }, config: {}, }, cloud: {}, admin: { prevTrialLicense: { IsLicensed: 'false', }, }, users: { currentUserId: 'user1', profiles: { user1: { id: 'user1', roles: 'system_admin', }, }, }, }, }; test('should display for admin users on professional with option to start trial if no self-hosted trial before', () => { const store = mockStore(initState); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(1); expect(wrapper.find('.ad-ldap-banner-btn').text()).toEqual('Start trial'); }); test('should display for admin users on professional with option to start trial if no cloud trial before', async () => { const state = JSON.parse(JSON.stringify(initState)); state.entities.admin = {}; state.entities.general.license = { Cloud: 'true', ExpiresAt: 100000000, }; state.entities.cloud = { subscription: { product_id: 'prod_professional', is_free_trial: 'false', trial_end_at: 0, }, products: { prod_professional: { id: 'prod_professional', sku: CloudProducts.PROFESSIONAL, }, }, }; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); await actImmediate(wrapper); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(1); expect(wrapper.find('.ad-ldap-banner-btn').text()).toEqual('Start trial'); }); test('should display for admin users on professional with option to contact sales if self-hosted trialed before', () => { const state = JSON.parse(JSON.stringify(initState)); state.entities.admin.prevTrialLicense.IsLicensed = 'true'; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(1); expect(wrapper.find('.ad-ldap-banner-btn').text()).toEqual('Contact sales to use'); }); test('should display for admin users on professional with option to contact sales if cloud trialed before', async () => { const state = JSON.parse(JSON.stringify(initState)); state.entities.admin = {}; state.entities.general.license = { Cloud: 'true', ExpiresAt: 100000000, }; state.entities.cloud = { subscription: { product_id: 'prod_professional', is_free_trial: 'false', trial_end_at: 1, }, products: { prod_professional: { id: 'prod_professional', sku: CloudProducts.PROFESSIONAL, }, }, }; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); await actImmediate(wrapper); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(1); expect(wrapper.find('.ad-ldap-banner-btn').text()).toEqual('Contact sales to use'); }); test('should not display for non admin users', () => { const state = JSON.parse(JSON.stringify(initState)); state.entities.users.profiles.user1.roles = 'system_user'; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(0); }); test('should not display for non self-hosted professional users', () => { const state = JSON.parse(JSON.stringify(initState)); state.entities.general.license.SkuShortName = LicenseSkus.Enterprise; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(0); }); test('should not display for non cloud professional users', async () => { const state = JSON.parse(JSON.stringify(initState)); state.entities.admin = {}; state.entities.general.license = { Cloud: 'true', ExpiresAt: 100000000, }; state.entities.cloud = { subscription: { product_id: 'prod_starter', is_free_trial: 'false', trial_end_at: 1, }, products: { prod_starter: { id: 'prod_starter', sku: CloudProducts.STARTER, }, }, }; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mount( <reactRedux.Provider store={store}> <ADLDAPUpsellBanner/> </reactRedux.Provider>, ); await actImmediate(wrapper); expect(wrapper.find('#ad_ldap_upsell_banner')).toHaveLength(0); }); });
3,476
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_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 {Group} from '@mattermost/types/groups'; import UserGroupsModal from './user_groups_modal'; describe('component/user_groups_modal', () => { const baseProps = { onExited: jest.fn(), groups: [], myGroups: [], archivedGroups: [], searchTerm: '', currentUserId: '', backButtonAction: jest.fn(), actions: { getGroups: jest.fn(), setModalSearchTerm: jest.fn(), getGroupsByUserIdPaginated: jest.fn(), searchGroups: jest.fn(), }, }; function getGroups(numberOfGroups: number) { const groups: Group[] = []; for (let i = 0; i < numberOfGroups; i++) { groups.push({ id: `group${i}`, name: `group${i}`, display_name: `Group ${i}`, description: `Group ${i} description`, source: 'custom', remote_id: null, create_at: 1637349374137, update_at: 1637349374137, delete_at: 0, has_syncables: false, member_count: i + 1, allow_reference: true, scheme_admin: false, }); } return groups; } test('should match snapshot without groups', () => { const wrapper = shallow( <UserGroupsModal {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with groups', () => { const groups = getGroups(3); const myGroups = getGroups(1); const wrapper = shallow( <UserGroupsModal {...baseProps} groups={groups} myGroups={myGroups} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,478
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/__snapshots__/user_groups_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/user_groups_modal should match snapshot with groups 1`] = ` <Modal animation={true} aria-labelledby="userGroupsModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal user-groups-modal" dialogComponentClass={[Function]} enforceFocus={true} id="userGroupsModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <Connect(Component) backButtonAction={[MockFunction]} onExited={[MockFunction]} /> <ModalBody bsClass="modal-body" componentClass="div" > <div className="user-groups-search" > <ForwardRef className="user-group-search-input" data-testid="searchInput" inputPrefix={ <i className="icon icon-magnify" /> } onChange={[Function]} placeholder="Search Groups" type="text" value="" /> </div> <Memo(UserGroupsFilter) getGroups={[Function]} selectedFilter="all" /> <Connect(Component) backButtonAction={[MockFunction]} groups={ Array [ Object { "allow_reference": true, "create_at": 1637349374137, "delete_at": 0, "description": "Group 0 description", "display_name": "Group 0", "has_syncables": false, "id": "group0", "member_count": 1, "name": "group0", "remote_id": null, "scheme_admin": false, "source": "custom", "update_at": 1637349374137, }, Object { "allow_reference": true, "create_at": 1637349374137, "delete_at": 0, "description": "Group 1 description", "display_name": "Group 1", "has_syncables": false, "id": "group1", "member_count": 2, "name": "group1", "remote_id": null, "scheme_admin": false, "source": "custom", "update_at": 1637349374137, }, Object { "allow_reference": true, "create_at": 1637349374137, "delete_at": 0, "description": "Group 2 description", "display_name": "Group 2", "has_syncables": false, "id": "group2", "member_count": 3, "name": "group2", "remote_id": null, "scheme_admin": false, "source": "custom", "update_at": 1637349374137, }, ] } hasNextPage={true} loadMoreGroups={[Function]} loading={false} onExited={[MockFunction]} searchTerm="" /> </ModalBody> </Modal> `; exports[`component/user_groups_modal should match snapshot without groups 1`] = ` <Modal animation={true} aria-labelledby="userGroupsModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal user-groups-modal" dialogComponentClass={[Function]} enforceFocus={true} id="userGroupsModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <Connect(Component) backButtonAction={[MockFunction]} onExited={[MockFunction]} /> <ModalBody bsClass="modal-body" componentClass="div" > <div className="user-groups-search" > <ForwardRef className="user-group-search-input" data-testid="searchInput" inputPrefix={ <i className="icon icon-magnify" /> } onChange={[Function]} placeholder="Search Groups" type="text" value="" /> </div> <Memo(UserGroupsFilter) getGroups={[Function]} selectedFilter="all" /> <NoResultsIndicator variant="UserGroups" /> <Memo(ADLDAPUpsellBanner) /> </ModalBody> </Modal> `;
3,481
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_list/user_groups_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 {Group, GroupPermissions} from '@mattermost/types/groups'; import UserGroupsList from './user_groups_list'; describe('component/user_groups_modal', () => { const baseProps = { onExited: jest.fn(), onScroll: jest.fn(), groups: [], searchTerm: '', backButtonAction: jest.fn(), groupPermissionsMap: {}, loading: false, loadMoreGroups: jest.fn(), hasNextPage: false, actions: { openModal: jest.fn(), archiveGroup: jest.fn(), restoreGroup: jest.fn(), }, }; function getGroups(numberOfGroups: number) { const groups: Group[] = []; for (let i = 0; i < numberOfGroups; i++) { groups.push({ id: `group${i}`, name: `group${i}`, display_name: `Group ${i}`, description: `Group ${i} description`, source: 'custom', remote_id: null, create_at: 1637349374137, update_at: 1637349374137, delete_at: 0, has_syncables: false, member_count: i + 1, allow_reference: true, scheme_admin: false, }); } return groups; } function getPermissions(groups: Group[]) { const groupPermissionsMap: Record<string, GroupPermissions> = {}; groups.forEach((g) => { groupPermissionsMap[g.id] = { can_delete: true, can_manage_members: true, can_restore: true, }; }); return groupPermissionsMap; } test('should match snapshot without groups', () => { const wrapper = shallow( <UserGroupsList {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with groups', () => { const groups = getGroups(3); const permissions = getPermissions(groups); const wrapper = shallow( <UserGroupsList {...baseProps} groups={groups} groupPermissionsMap={permissions} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,483
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_list/__snapshots__/user_groups_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/user_groups_modal should match snapshot with groups 1`] = ` <div className="user-groups-modal__content user-groups-list" style={ Object { "overflow": "overlay", } } > <InfiniteLoader isItemLoaded={[Function]} itemCount={100000} loadMoreItems={[MockFunction]} > <Component /> </InfiniteLoader> <Memo(ADLDAPUpsellBanner) /> </div> `; exports[`component/user_groups_modal should match snapshot without groups 1`] = ` <div className="user-groups-modal__content user-groups-list" style={ Object { "overflow": "overlay", } } > <InfiniteLoader isItemLoaded={[Function]} itemCount={100000} loadMoreItems={[MockFunction]} > <Component /> </InfiniteLoader> <Memo(ADLDAPUpsellBanner) /> </div> `;
3,485
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_modal_header/user_groups_modal_header.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 UserGroupsModalHeader from './user_groups_modal_header'; describe('component/user_groups_modal', () => { const baseProps = { onExited: jest.fn(), backButtonAction: jest.fn(), canCreateCustomGroups: true, actions: { openModal: jest.fn(), }, }; test('should match snapshot without groups', () => { const wrapper = shallow( <UserGroupsModalHeader {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with groups', () => { const wrapper = shallow( <UserGroupsModalHeader {...baseProps} canCreateCustomGroups={false} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,487
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_modal_header
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_groups_modal/user_groups_modal_header/__snapshots__/user_groups_modal_header.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/user_groups_modal should match snapshot with groups 1`] = ` <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="userGroupsModalLabel" > <MemoizedFormattedMessage defaultMessage="User Groups" id="user_groups_modal.title" /> </ModalTitle> </ModalHeader> `; exports[`component/user_groups_modal should match snapshot without groups 1`] = ` <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="userGroupsModalLabel" > <MemoizedFormattedMessage defaultMessage="User Groups" id="user_groups_modal.title" /> </ModalTitle> <button className="user-groups-create btn btn-secondary btn-sm" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Create Group" id="user_groups_modal.createNew" /> </button> </ModalHeader> `;