level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
2,842
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_body_additional_content
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_body_additional_content/__snapshots__/post_body_additional_content.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`PostBodyAdditionalContent with a YouTube video should not render content when isEmbedVisible is false 1`] = ` <div> <button aria-label="Toggle Embed Visibility" className="style--none post__embed-visibility color--link pull-left" data-expanded={false} key="toggle" onClick={[Function]} /> <span> some children </span> </div> `; exports[`PostBodyAdditionalContent with a YouTube video should render correctly 1`] = ` <div> <button aria-label="Toggle Embed Visibility" className="style--none post__embed-visibility color--link pull-left" data-expanded={true} key="toggle" onClick={[Function]} /> <span> some children </span> <Connect(YoutubeVideo) link="https://www.youtube.com/watch?v=d-YO3v-wJts" postId="post_id_1" show={true} /> </div> `; exports[`PostBodyAdditionalContent with a YouTube video should render the toggle after a message containing more than just a link 1`] = ` <div> <span> some children </span> <button aria-label="Toggle Embed Visibility" className="style--none post__embed-visibility color--link " data-expanded={true} key="toggle" onClick={[Function]} /> <Connect(YoutubeVideo) link="https://www.youtube.com/watch?v=d-YO3v-wJts" postId="post_id_1" show={true} /> </div> `; exports[`PostBodyAdditionalContent with a message attachment should render correctly 1`] = ` <div> <span> some children </span> <MessageAttachmentList attachments={Array []} imagesMetadata={Object {}} postId="post_id_1" /> </div> `; exports[`PostBodyAdditionalContent with a normal link Should render nothing if the plugin matches but isEmbedVisible is false 1`] = ` <div> <span> some children </span> </div> `; exports[`PostBodyAdditionalContent with a normal link Should render nothing if the registered plugins don't match 1`] = ` <div> <span> some children </span> </div> `; exports[`PostBodyAdditionalContent with a normal link Should render the plugin component if it matches and is not toggeable 1`] = ` <div> <span> some children </span> <EmbedMP3 embed={ Object { "type": "link", "url": "https://example.com/song.mp3", } } webSocketClient={ WebSocketClient { "closeCallback": null, "closeListeners": Set {}, "conn": null, "connectFailCount": 0, "connectionId": "", "connectionUrl": null, "errorCallback": null, "errorListeners": Set {}, "eventCallback": null, "firstConnectCallback": null, "firstConnectListeners": Set {}, "messageListeners": Set {}, "missedEventCallback": null, "missedMessageListeners": Set {}, "reconnectCallback": null, "reconnectListeners": Set {}, "responseCallbacks": Object {}, "responseSequence": 1, "serverSequence": 0, } } /> </div> `; exports[`PostBodyAdditionalContent with a normal link Should render the plugin component if it matches and is toggeable 1`] = ` <div> <button aria-label="Toggle Embed Visibility" className="style--none post__embed-visibility color--link pull-left" data-expanded={true} key="toggle" onClick={[Function]} /> <span> some children </span> <EmbedMP3 embed={ Object { "type": "link", "url": "https://example.com/song.mp3", } } webSocketClient={ WebSocketClient { "closeCallback": null, "closeListeners": Set {}, "conn": null, "connectFailCount": 0, "connectionId": "", "connectionUrl": null, "errorCallback": null, "errorListeners": Set {}, "eventCallback": null, "firstConnectCallback": null, "firstConnectListeners": Set {}, "messageListeners": Set {}, "missedEventCallback": null, "missedMessageListeners": Set {}, "reconnectCallback": null, "reconnectListeners": Set {}, "responseCallbacks": Object {}, "responseSequence": 1, "serverSequence": 0, } } /> </div> `; exports[`PostBodyAdditionalContent with a permalinklink Render permalink preview 1`] = ` <div> <span> some children </span> <Connect(PostMessagePreview) handleFileDropdownOpened={[MockFunction]} metadata={ Object { "channel_display_name": "channel1", "channel_id": "channel_id", "channel_type": "O", "post_id": "post_id123", "team_name": "core", } } /> </div> `; exports[`PostBodyAdditionalContent with a permalinklink Render permalink preview with no data 1`] = ` <div> <span> some children </span> </div> `; exports[`PostBodyAdditionalContent with an image preview should render correctly 1`] = ` <div> <button aria-label="Toggle Embed Visibility" className="style--none post__embed-visibility color--link pull-left" data-expanded={true} key="toggle" onClick={[Function]} /> <span> some children </span> <Connect(PostImage) imageMetadata={Object {}} link="https://example.com/image.png" post={ Object { "channel_id": "channel_id", "create_at": 1, "id": "post_id_1", "message": "https://example.com/image.png", "metadata": Object { "embeds": Array [ Object { "type": "image", "url": "https://example.com/image.png", }, ], "emojis": Array [], "files": Array [], "images": Object { "https://example.com/image.png": Object {}, }, "reactions": Array [], }, "root_id": "root_id", } } /> </div> `; exports[`PostBodyAdditionalContent with an image preview should render the toggle after a message containing more than just a link 1`] = ` <div> <span> some children </span> <button aria-label="Toggle Embed Visibility" className="style--none post__embed-visibility color--link " data-expanded={true} key="toggle" onClick={[Function]} /> <Connect(PostImage) imageMetadata={Object {}} link="https://example.com/image.png" post={ Object { "channel_id": "channel_id", "create_at": 1, "id": "post_id_1", "message": "This is an image: https://example.com/image.png", "metadata": Object { "embeds": Array [ Object { "type": "image", "url": "https://example.com/image.png", }, ], "emojis": Array [], "files": Array [], "images": Object { "https://example.com/image.png": Object {}, }, "reactions": Array [], }, "root_id": "root_id", } } /> </div> `; exports[`PostBodyAdditionalContent with an opengraph preview should render correctly 1`] = ` <div> <span> some children </span> <Connect(PostAttachmentOpenGraph) isEmbedVisible={true} link="https://example.com/image.png" post={ Object { "channel_id": "channel_id", "create_at": 1, "id": "post_id_1", "message": "https://example.com/image.png", "metadata": Object { "embeds": Array [ Object { "type": "opengraph", "url": "https://example.com/image.png", }, ], }, "root_id": "root_id", } } postId="post_id_1" toggleEmbedVisibility={[Function]} /> </div> `; exports[`PostBodyAdditionalContent with an opengraph preview should render the toggle after a message containing more than just a link 1`] = ` <div> <span> some children </span> <Connect(PostAttachmentOpenGraph) isEmbedVisible={true} link="https://example.com/image.png" post={ Object { "channel_id": "channel_id", "create_at": 1, "id": "post_id_1", "message": "This is a link: https://example.com/image.png", "metadata": Object { "embeds": Array [ Object { "type": "opengraph", "url": "https://example.com/image.png", }, ], }, "root_id": "root_id", } } postId="post_id_1" toggleEmbedVisibility={[Function]} /> </div> `;
2,846
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_flag_icon/post_flag_icon.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 PostFlagIcon from 'components/post_view/post_flag_icon/post_flag_icon'; describe('components/post_view/PostFlagIcon', () => { const baseProps = { postId: 'post_id', isFlagged: false, actions: { flagPost: jest.fn(), unflagPost: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow(<PostFlagIcon {...baseProps}/>); // for unflagged icon expect(wrapper).toMatchSnapshot(); expect(wrapper.find('button').hasClass('post-menu__item')).toBe(true); wrapper.find('button').simulate('click', {preventDefault: jest.fn}); expect(baseProps.actions.flagPost).toHaveBeenCalledTimes(1); expect(baseProps.actions.flagPost).toBeCalledWith('post_id'); expect(baseProps.actions.unflagPost).not.toBeCalled(); // for flagged icon wrapper.setProps({isFlagged: true}); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('button').hasClass('post-menu__item')).toBe(true); wrapper.find('button').simulate('click', {preventDefault: jest.fn}); expect(baseProps.actions.flagPost).toHaveBeenCalledTimes(1); expect(baseProps.actions.unflagPost).toHaveBeenCalledTimes(1); expect(baseProps.actions.unflagPost).toBeCalledWith('post_id'); }); });
2,848
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_flag_icon
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_flag_icon/__snapshots__/post_flag_icon.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/PostFlagIcon should match snapshot 1`] = ` <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={400} key="flagtooltipkey" overlay={ <Tooltip className="hidden-xs" id="flagTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Save Message" id="flag_post.flag" /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-label="save" className="post-menu__item" id="CENTER_flagIcon_post_id" onClick={[Function]} > <FlagIcon className="icon icon--small" /> </button> </OverlayTrigger> `; exports[`components/post_view/PostFlagIcon should match snapshot 2`] = ` <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={400} key="flagtooltipkeyflagged" overlay={ <Tooltip className="hidden-xs" id="flagTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Remove from Saved" id="flag_post.unflag" /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-label="remove from saved" className="post-menu__item" id="CENTER_flagIcon_post_id" onClick={[Function]} > <FlagIconFilled className="icon icon--small icon--small-filled post-menu__item--selected" /> </button> </OverlayTrigger> `;
2,853
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list/post_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 VirtPostList from 'components/post_view/post_list_virtualized/post_list_virtualized'; import {PostRequestTypes} from 'utils/constants'; import PostList, {MAX_EXTRA_PAGES_LOADED} from './post_list'; const actionsProp = { loadPostsAround: jest.fn().mockImplementation(() => Promise.resolve({atLatestMessage: true, atOldestmessage: true})), loadUnreads: jest.fn().mockImplementation(() => Promise.resolve({atLatestMessage: true, atOldestmessage: true})), loadPosts: jest.fn().mockImplementation(() => Promise.resolve({moreToLoad: false})), syncPostsInChannel: jest.fn().mockResolvedValue({}), loadLatestPosts: jest.fn().mockImplementation(() => Promise.resolve({atLatestMessage: true, atOldestmessage: true})), markChannelAsRead: jest.fn(), updateNewMessagesAtInChannel: jest.fn(), toggleShouldStartFromBottomWhenUnread: jest.fn(), }; const lastViewedAt = 1532345226632; const channelId = 'fake-id'; const createFakePosIds = (num: number) => { const postIds = []; for (let i = 1; i <= num; i++) { postIds.push(`1234${i}`); } return postIds; }; const baseProps = { actions: actionsProp, lastViewedAt, channelId, postListIds: [], changeUnreadChunkTimeStamp: jest.fn(), toggleShouldStartFromBottomWhenUnread: jest.fn(), isFirstLoad: true, atLatestPost: false, formattedPostIds: [], isPrefetchingInProcess: false, isMobileView: false, hasInaccessiblePosts: false, shouldStartFromBottomWhenUnread: false, }; describe('components/post_view/post_list', () => { it('snapshot for loading when there are no posts', () => { const wrapper = shallow( <PostList {...{...baseProps, postListIds: []}}/>, ); expect(wrapper).toMatchSnapshot(); }); it('snapshot with couple of posts', () => { const postIds = createFakePosIds(2); const wrapper = shallow( <PostList {...{...baseProps, postListIds: postIds}}/>, ); expect(wrapper).toMatchSnapshot(); }); it('Should call postsOnLoad', async () => { const emptyPostList: string[] = []; const wrapper = shallow<PostList>( <PostList {...{...baseProps, postListIds: emptyPostList}}/>, ); expect(actionsProp.loadUnreads).toHaveBeenCalledWith(baseProps.channelId); await wrapper.instance().postsOnLoad('undefined'); expect(wrapper.state('loadingNewerPosts')).toBe(false); expect(wrapper.state('loadingOlderPosts')).toBe(false); }); it('Should not call loadUnreads if isPrefetchingInProcess is true', async () => { const emptyPostList: string[] = []; shallow(<PostList {...{...baseProps, postListIds: emptyPostList, isPrefetchingInProcess: true}}/>); expect(actionsProp.loadUnreads).not.toHaveBeenCalledWith(baseProps.channelId); }); it('Should call for before and afterPosts', async () => { const postIds = createFakePosIds(2); const wrapper = shallow<PostList>( <PostList {...{...baseProps, postListIds: postIds}}/>, ); wrapper.find(VirtPostList).prop('actions').loadOlderPosts(); expect(wrapper.state('loadingOlderPosts')).toEqual(true); expect(actionsProp.loadPosts).toHaveBeenCalledWith({channelId: baseProps.channelId, postId: postIds[postIds.length - 1], type: PostRequestTypes.BEFORE_ID}); await wrapper.instance().callLoadPosts('undefined', 'undefined', undefined); expect(wrapper.state('loadingOlderPosts')).toBe(false); wrapper.find(VirtPostList).prop('actions').loadNewerPosts(); expect(wrapper.state('loadingNewerPosts')).toEqual(true); expect(actionsProp.loadPosts).toHaveBeenCalledWith({channelId: baseProps.channelId, postId: postIds[0], type: PostRequestTypes.AFTER_ID}); await wrapper.instance().callLoadPosts('undefined', 'undefined', undefined); expect(wrapper.state('loadingNewerPosts')).toBe(false); }); it('VirtPostList Should have formattedPostIds as prop', async () => { const postIds = createFakePosIds(2); const wrapper = shallow( <PostList {...{...baseProps, postListIds: postIds}}/>, ); const formattedPostIds = wrapper.find(VirtPostList).prop('postListIds'); expect(formattedPostIds).toEqual([]); }); it('getOldestVisiblePostId and getLatestVisiblePostId should return based on postListIds', async () => { const postIds = createFakePosIds(10); const formattedPostIds = ['1', '2']; const wrapper = shallow<PostList>( <PostList {...{...baseProps, postListIds: postIds, formattedPostIds}}/>, ); const instance = wrapper.instance(); expect(instance.getOldestVisiblePostId()).toEqual('123410'); expect(instance.getLatestVisiblePostId()).toEqual('12341'); }); it('Should call for permalink posts', async () => { const focusedPostId = 'new'; const wrapper = shallow( <PostList {...{...baseProps, focusedPostId}}/>, ); expect(actionsProp.loadPostsAround).toHaveBeenCalledWith(baseProps.channelId, focusedPostId); await actionsProp.loadPostsAround(); expect(wrapper.state('loadingOlderPosts')).toBe(false); expect(wrapper.state('loadingNewerPosts')).toBe(false); }); it('Should call for loadLatestPosts', async () => { const wrapper = shallow( <PostList {...{...baseProps, postListIds: [], isFirstLoad: false}}/>, ); expect(actionsProp.loadLatestPosts).toHaveBeenCalledWith(baseProps.channelId); await actionsProp.loadLatestPosts(); expect(wrapper.state('loadingOlderPosts')).toBe(false); expect(wrapper.state('loadingNewerPosts')).toBe(false); }); describe('getPostsSince', () => { test('should call getPostsSince on channel switch', () => { const postIds = createFakePosIds(2); shallow(<PostList {...{...baseProps, isFirstLoad: false, postListIds: postIds, latestPostTimeStamp: 1234}}/>); expect(actionsProp.syncPostsInChannel).toHaveBeenCalledWith(baseProps.channelId, 1234, false); }); }); describe('canLoadMorePosts', () => { test('Should not call loadLatestPosts if postListIds is empty', async () => { const wrapper = shallow(<PostList {...{...baseProps, isFirstLoad: false, postListIds: []}}/>); expect(actionsProp.loadLatestPosts).toHaveBeenCalledWith(baseProps.channelId); await actionsProp.loadLatestPosts(); expect(wrapper.state('loadingOlderPosts')).toBe(false); expect(wrapper.state('loadingNewerPosts')).toBe(false); }); test('Should not call loadPosts if olderPosts or newerPosts are loading', async () => { const postIds = createFakePosIds(2); const wrapper = shallow(<PostList {...{...baseProps, isFirstLoad: false, postListIds: postIds}}/>); wrapper.setState({loadingOlderPosts: true}); wrapper.find(VirtPostList).prop('actions').canLoadMorePosts(undefined); expect(actionsProp.loadPosts).not.toHaveBeenCalled(); wrapper.setState({loadingOlderPosts: false}); wrapper.setState({loadingNewerPosts: true}); wrapper.find(VirtPostList).prop('actions').canLoadMorePosts(undefined); expect(actionsProp.loadPosts).not.toHaveBeenCalled(); }); test('Should not call loadPosts if there were more than MAX_EXTRA_PAGES_LOADED', async () => { const postIds = createFakePosIds(2); const wrapper = shallow<PostList>(<PostList {...{...baseProps, isFirstLoad: false, postListIds: postIds}}/>); wrapper.instance().extraPagesLoaded = MAX_EXTRA_PAGES_LOADED + 1; wrapper.find(VirtPostList).prop('actions').canLoadMorePosts(undefined); expect(actionsProp.loadPosts).not.toHaveBeenCalled(); }); test('Should call getPostsBefore if not all older posts are loaded', async () => { const postIds = createFakePosIds(2); const wrapper = shallow(<PostList {...{...baseProps, isFirstLoad: false, postListIds: postIds}}/>); wrapper.setProps({atOldestPost: false}); wrapper.find(VirtPostList).prop('actions').canLoadMorePosts(undefined); expect(actionsProp.loadPosts).toHaveBeenCalledWith({channelId: baseProps.channelId, postId: postIds[postIds.length - 1], type: PostRequestTypes.BEFORE_ID}); }); test('Should call getPostsAfter if all older posts are loaded and not newerPosts', async () => { const postIds = createFakePosIds(2); const wrapper = shallow(<PostList {...{...baseProps, isFirstLoad: false, postListIds: postIds}}/>); wrapper.setProps({atOldestPost: true}); wrapper.find(VirtPostList).prop('actions').canLoadMorePosts(undefined); expect(actionsProp.loadPosts).toHaveBeenCalledWith({channelId: baseProps.channelId, postId: postIds[0], type: PostRequestTypes.AFTER_ID}); }); test('Should call getPostsAfter canLoadMorePosts is requested with AFTER_ID', async () => { const postIds = createFakePosIds(2); const wrapper = shallow(<PostList {...{...baseProps, isFirstLoad: false, postListIds: postIds}}/>); wrapper.find(VirtPostList).prop('actions').canLoadMorePosts(PostRequestTypes.AFTER_ID); expect(actionsProp.loadPosts).toHaveBeenCalledWith({channelId: baseProps.channelId, postId: postIds[0], type: PostRequestTypes.AFTER_ID}); }); }); describe('Auto retry of load more posts', () => { test('Should retry loadPosts on failure of loadPosts', async () => { const postIds = createFakePosIds(2); const loadPosts = jest.fn().mockImplementation(() => Promise.resolve({moreToLoad: true, error: {}})); const props = { ...baseProps, postListIds: postIds, actions: { ...actionsProp, loadPosts, }, }; const wrapper = shallow( <PostList {...props}/>, ); wrapper.find(VirtPostList).prop('actions').loadOlderPosts(); expect(wrapper.state('loadingOlderPosts')).toEqual(true); expect(loadPosts).toHaveBeenCalledTimes(1); expect(loadPosts).toHaveBeenCalledWith({channelId: baseProps.channelId, postId: postIds[postIds.length - 1], type: PostRequestTypes.BEFORE_ID}); await loadPosts(); expect(wrapper.state('loadingOlderPosts')).toBe(false); expect(loadPosts).toHaveBeenCalledTimes(3); }); }); describe('markChannelAsReadAndViewed', () => { test('Should call markChannelAsReadAndViewed on postsOnLoad', async () => { const emptyPostList: string[] = []; const wrapper = shallow<PostList>( <PostList {...{...baseProps, postListIds: emptyPostList}}/>, ); await wrapper.instance().postsOnLoad('undefined'); expect(actionsProp.markChannelAsRead).toHaveBeenCalledWith(baseProps.channelId); }); test('Should not call markChannelAsReadAndViewed as it is a permalink', async () => { const emptyPostList: string[] = []; const focusedPostId = 'new'; shallow( <PostList {...{...baseProps, postListIds: emptyPostList, focusedPostId}}/>, ); await actionsProp.loadPostsAround(); expect(actionsProp.markChannelAsRead).not.toHaveBeenCalled(); }); }); });
2,855
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list/__snapshots__/post_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/post_list snapshot for loading when there are no posts 1`] = ` <div className="post-list-holder-by-time" key="postlist-fake-id" > <div className="post-list__table" > <div className="post-list__content" id="virtualizedPostListContent" > <PostList actions={ Object { "canLoadMorePosts": [Function], "changeUnreadChunkTimeStamp": [MockFunction], "loadNewerPosts": [Function], "loadOlderPosts": [Function], "toggleShouldStartFromBottomWhenUnread": [MockFunction], "updateNewMessagesAtInChannel": [MockFunction], } } atLatestPost={false} autoRetryEnable={true} channelId="fake-id" isMobileView={false} lastViewedAt={1532345226632} loadingNewerPosts={false} loadingOlderPosts={false} postListIds={Array []} shouldStartFromBottomWhenUnread={false} /> </div> </div> </div> `; exports[`components/post_view/post_list snapshot with couple of posts 1`] = ` <div className="post-list-holder-by-time" key="postlist-fake-id" > <div className="post-list__table" > <div className="post-list__content" id="virtualizedPostListContent" > <PostList actions={ Object { "canLoadMorePosts": [Function], "changeUnreadChunkTimeStamp": [MockFunction], "loadNewerPosts": [Function], "loadOlderPosts": [Function], "toggleShouldStartFromBottomWhenUnread": [MockFunction], "updateNewMessagesAtInChannel": [MockFunction], } } atLatestPost={false} autoRetryEnable={true} channelId="fake-id" isMobileView={false} lastViewedAt={1532345226632} loadingNewerPosts={false} loadingOlderPosts={false} postListIds={Array []} shouldStartFromBottomWhenUnread={false} /> </div> </div> </div> `;
2,857
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list_row/post_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 {ChannelType} from '@mattermost/types/channels'; import type {CloudUsage} from '@mattermost/types/cloud'; import * as PostListUtils from 'mattermost-redux/utils/post_list'; import Post from 'components/post'; import ChannelIntroMessage from 'components/post_view/channel_intro_message/'; import CombinedUserActivityPost from 'components/post_view/combined_user_activity_post'; import DateSeparator from 'components/post_view/date_separator'; import NewMessageSeparator from 'components/post_view/new_message_separator/new_message_separator'; import {PostListRowListIds} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import PostListRow from './post_list_row'; describe('components/post_view/post_list_row', () => { const defaultProps = { listId: '1234', loadOlderPosts: jest.fn(), loadNewerPosts: jest.fn(), togglePostMenu: jest.fn(), isLastPost: false, shortcutReactToLastPostEmittedFrom: 'NO_WHERE', loadingNewerPosts: false, loadingOlderPosts: false, isCurrentUserLastPostGroupFirstPost: false, actions: { emitShortcutReactToLastPostFrom: jest.fn(), }, channelLimitExceeded: false, limitsLoaded: false, limits: {}, usage: {} as CloudUsage, post: TestHelper.getPostMock({id: 'post_id_1'}), currentUserId: 'user_id_1', newMessagesSeparatorActions: [], lastViewedAt: 0, channelId: 'channel_id_1', }; test('should render more messages loading indicator', () => { const listId = PostListRowListIds.OLDER_MESSAGES_LOADER; const props = { ...defaultProps, listId, loadingOlderPosts: true, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render manual load messages trigger', () => { const listId = PostListRowListIds.LOAD_OLDER_MESSAGES_TRIGGER; const loadOlderPosts = jest.fn(); const props = { ...defaultProps, listId, loadOlderPosts, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); wrapper.prop('onClick')(); expect(loadOlderPosts).toHaveBeenCalledTimes(1); }); test('should render channel intro message', () => { const listId = PostListRowListIds.CHANNEL_INTRO_MESSAGE; const props = { ...defaultProps, channel: { id: '123', name: 'test-channel-1', display_name: 'Test Channel 1', type: ('P' as ChannelType), team_id: 'team-1', header: '', purpose: '', creator_id: '', scheme_id: '', group_constrained: false, create_at: 0, update_at: 0, delete_at: 0, last_post_at: 0, last_root_post_at: 0, }, fullWidth: true, listId, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(ChannelIntroMessage).exists()).toBe(true); }); test('should render new messages line', () => { const listId = PostListRowListIds.START_OF_NEW_MESSAGES; const props = { ...defaultProps, listId, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(NewMessageSeparator).exists()).toBe(true); }); test('should render date line', () => { const listId = `${PostListRowListIds.DATE_LINE}1553106600000`; const props = { ...defaultProps, listId, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(DateSeparator).exists()).toBe(true); }); test('should render combined post', () => { const props = { ...defaultProps, shouldHighlight: false, listId: `${PostListUtils.COMBINED_USER_ACTIVITY}1234-5678`, previousListId: 'abcd', }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(CombinedUserActivityPost).exists()).toBe(true); }); test('should render post', () => { const props = { ...defaultProps, shouldHighlight: false, listId: '1234', previousListId: 'abcd', }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(Post).exists()).toBe(true); }); test('should have class hideAnimation for OLDER_MESSAGES_LOADER if loadingOlderPosts is false', () => { const listId = PostListRowListIds.OLDER_MESSAGES_LOADER; const props = { ...defaultProps, listId, loadingOlderPosts: false, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have class hideAnimation for NEWER_MESSAGES_LOADER if loadingNewerPosts is false', () => { const listId = PostListRowListIds.NEWER_MESSAGES_LOADER; const props = { ...defaultProps, listId, loadingNewerPosts: false, }; const wrapper = shallow( <PostListRow {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
2,859
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list_row
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list_row/__snapshots__/post_list_row.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/post_list_row should have class hideAnimation for NEWER_MESSAGES_LOADER if loadingNewerPosts is false 1`] = ` <div className="loading-screen" > <div className="loading__content hideAnimation" > <div className="round round-1" /> <div className="round round-2" /> <div className="round round-3" /> </div> </div> `; exports[`components/post_view/post_list_row should have class hideAnimation for OLDER_MESSAGES_LOADER if loadingOlderPosts is false 1`] = ` <div className="loading-screen" > <div className="loading__content hideAnimation" > <div className="round round-1" /> <div className="round round-2" /> <div className="round round-3" /> </div> </div> `; exports[`components/post_view/post_list_row should render channel intro message 1`] = `<Connect(ChannelIntroMessage) />`; exports[`components/post_view/post_list_row should render combined post 1`] = ` <Connect(Connect(PostComponent)) combinedId="user-activity-1234-5678" isLastPost={false} location="CENTER" previousPostId="abcd" shouldHighlight={false} togglePostMenu={[MockFunction]} /> `; exports[`components/post_view/post_list_row should render date line 1`] = ` <Memo(DateSeparator) date={1553106600000} key="1553106600000" /> `; exports[`components/post_view/post_list_row should render manual load messages trigger 1`] = ` <button className="more-messages-text theme style--none color--link" onClick={[MockFunction]} > <MemoizedFormattedMessage defaultMessage="Load More Messages" id="posts_view.loadMore" /> </button> `; exports[`components/post_view/post_list_row should render more messages loading indicator 1`] = ` <div className="loading-screen" > <div className="loading__content" > <div className="round round-1" /> <div className="round round-2" /> <div className="round round-3" /> </div> </div> `; exports[`components/post_view/post_list_row should render new messages line 1`] = ` <NewMessageSeparator channelId="channel_id_1" lastViewedAt={0} newMessagesSeparatorActions={Array []} separatorId="start-of-new-messages" /> `; exports[`components/post_view/post_list_row should render post 1`] = ` <Connect(PostComponent) isLastPost={false} location="CENTER" post={ Object { "channel_id": "", "create_at": 0, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "post_id_1", "is_pinned": false, "message": "post message", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } previousPostId="abcd" shouldHighlight={false} togglePostMenu={[MockFunction]} /> `;
2,860
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list_virtualized/latest_post_reader.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {createIntl, useIntl} from 'react-intl'; import enMessages from 'i18n/en.json'; import esMessages from 'i18n/es.json'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import LatestPostReader from './latest_post_reader'; jest.mock('react-intl', () => ({ ...jest.requireActual('react-intl'), useIntl: jest.fn(), })); describe('LatestPostReader', () => { const author = TestHelper.getUserMock({ username: 'some_user', }); const post = TestHelper.getPostMock({ user_id: author.id, message: 'This is a test.', }); const baseState = { entities: { emojis: { customEmoji: {}, }, general: { config: {}, }, posts: { posts: { [post.id]: post, }, reactions: {}, }, preferences: { myPreferences: {}, }, users: { profiles: { [author.id]: author, }, }, }, }; const baseProps = { postIds: [post.id], }; test('should render aria-label as a child in the given locale', () => { (useIntl as jest.Mock).mockImplementation(() => createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'})); const {rerender} = renderWithContext( <LatestPostReader {...baseProps}/>, baseState, ); const prevMessage = screen.getByText(`January 1, ${author.username} wrote, This is a test`, {exact: false}); expect(prevMessage).toBeInTheDocument(); expect(prevMessage).toHaveClass('sr-only'); (useIntl as jest.Mock).mockImplementation(() => createIntl({locale: 'es', messages: esMessages, defaultLocale: 'es'})); rerender(<LatestPostReader {...baseProps}/>); const januaryInSpanish = 'enero'; const message = screen.getByText(`${januaryInSpanish}, ${author.username} wrote, This is a test`, {exact: false}); expect(message).toBeInTheDocument(); expect(message).toHaveClass('sr-only'); }); test('should be able to handle an empty post array', () => { const props = { ...baseProps, postIds: [], }; renderWithContext(<LatestPostReader {...props}/>, baseState); // body should be empty const message = screen.queryByText('This is a test'); expect(message).not.toBeInTheDocument(); }); });
2,862
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_list_virtualized/post_list_virtualized.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {DynamicSizeList} from 'dynamic-virtualized-list'; import {shallow} from 'enzyme'; import React from 'react'; import type {ComponentProps} from 'react'; import {DATE_LINE} from 'mattermost-redux/utils/post_list'; import PostListRow from 'components/post_view/post_list_row'; import {PostListRowListIds, PostRequestTypes} from 'utils/constants'; import PostList from './post_list_virtualized'; describe('PostList', () => { const baseActions = { loadOlderPosts: jest.fn(), loadNewerPosts: jest.fn(), canLoadMorePosts: jest.fn(), changeUnreadChunkTimeStamp: jest.fn(), toggleShouldStartFromBottomWhenUnread: jest.fn(), updateNewMessagesAtInChannel: jest.fn(), }; const baseProps: ComponentProps<typeof PostList> = { channelId: 'channel', focusedPostId: '', postListIds: [ 'post1', 'post2', 'post3', DATE_LINE + 1551711600000, ], latestPostTimeStamp: 12345, loadingNewerPosts: false, loadingOlderPosts: false, atOldestPost: false, atLatestPost: false, isMobileView: false, autoRetryEnable: false, lastViewedAt: 0, shouldStartFromBottomWhenUnread: false, actions: baseActions, }; const postListIdsForClassNames = [ 'post1', 'post2', 'post3', DATE_LINE + 1551711600000, 'post4', PostListRowListIds.START_OF_NEW_MESSAGES, 'post5', ]; describe('renderRow', () => { const postListIds = ['a', 'b', 'c', 'd']; test('should get previous item ID correctly for oldest row', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const row = shallow(wrapper.instance().renderRow({ data: postListIds, itemId: 'd', style: {}, })); expect(row.find(PostListRow).prop('previousListId')).toEqual(''); }); test('should get previous item ID correctly for other rows', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const row = shallow(wrapper.instance().renderRow({ data: postListIds, itemId: 'b', style: {}, })); expect(row.find(PostListRow).prop('previousListId')).toEqual('c'); }); test('should highlight the focused post', () => { const props = { ...baseProps, focusedPostId: 'b', }; const wrapper = shallow<PostList>(<PostList {...props}/>); let row = shallow(wrapper.instance().renderRow({ data: postListIds, itemId: 'c', style: {}, })); expect(row.find(PostListRow).prop('shouldHighlight')).toEqual(false); row = shallow(wrapper.instance().renderRow({ data: postListIds, itemId: 'b', style: {}, })); expect(row.find(PostListRow).prop('shouldHighlight')).toEqual(true); }); }); describe('onScroll', () => { test('should call checkBottom', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.instance().checkBottom = jest.fn(); const scrollOffset = 1234; const scrollHeight = 1000; const clientHeight = 500; wrapper.instance().onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.instance().checkBottom).toHaveBeenCalledWith(scrollOffset, scrollHeight, clientHeight); }); test('should call canLoadMorePosts with AFTER_ID if loader is visible', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollOffset = 1234; const scrollHeight = 1000; const clientHeight = 500; instance.listRef = {current: {_getRangeToRender: () => [0, 70, 12, 1]} as unknown as DynamicSizeList}; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: true, scrollHeight, clientHeight, }); expect(baseProps.actions.canLoadMorePosts).toHaveBeenCalledWith(PostRequestTypes.AFTER_ID); }); test('should not call canLoadMorePosts with AFTER_ID if loader is below the fold by couple of messages', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollOffset = 1234; const scrollHeight = 1000; const clientHeight = 500; instance.listRef = {current: {_getRangeToRender: () => [0, 70, 12, 2]} as unknown as DynamicSizeList}; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: true, scrollHeight, clientHeight, }); expect(baseProps.actions.canLoadMorePosts).not.toHaveBeenCalled(); }); test('should show search channel hint if user scrolled too far away from the bottom of the list', () => { const screenHeightSpy = jest.spyOn(window.screen, 'height', 'get').mockImplementation(() => 500); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollHeight = 3000; const clientHeight = 500; const scrollOffset = 500; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.state('showSearchHint')).toBe(true); screenHeightSpy.mockRestore(); }); test('should not show search channel hint if user scrolls not that far away', () => { const screenHeightSpy = jest.spyOn(window.screen, 'height', 'get').mockImplementation(() => 500); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollHeight = 3000; const clientHeight = 500; const scrollOffset = 2500; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.state('showSearchHint')).toBe(false); screenHeightSpy.mockRestore(); }); test('should hide search channel hint in case of dismiss', () => { const screenHeightSpy = jest.spyOn(window.screen, 'height', 'get').mockImplementation(() => 500); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollHeight = 3000; const clientHeight = 500; const scrollOffset = 500; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); instance.handleSearchHintDismiss(); expect(wrapper.state('showSearchHint')).toBe(false); screenHeightSpy.mockRestore(); }); test('should not show search channel hint on mobile', () => { const screenHeightSpy = jest.spyOn(window.screen, 'height', 'get').mockImplementation(() => 500); const props = { ...baseProps, isMobileView: true, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); const scrollHeight = 3000; const clientHeight = 500; const scrollOffset = 500; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.state('showSearchHint')).toBe(false); screenHeightSpy.mockRestore(); }); test('should not show search channel hint if it has already been dismissed', () => { const screenHeightSpy = jest.spyOn(window.screen, 'height', 'get').mockImplementation(() => 500); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollHeight = 3000; const clientHeight = 500; const scrollOffset = 500; instance.handleSearchHintDismiss(); instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.state('showSearchHint')).toBe(false); screenHeightSpy.mockRestore(); }); test('should hide search channel hint in case of resize to mobile', () => { const screenHeightSpy = jest.spyOn(window.screen, 'height', 'get').mockImplementation(() => 500); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); const scrollHeight = 3000; const clientHeight = 500; const scrollOffset = 500; instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.state('showSearchHint')).toBe(true); wrapper.setProps({ isMobileView: true, }); instance.onScroll({ scrollDirection: 'forward', scrollOffset, scrollUpdateWasRequested: false, scrollHeight, clientHeight, }); expect(wrapper.state('showSearchHint')).toBe(false); screenHeightSpy.mockRestore(); }); }); describe('isAtBottom', () => { const scrollHeight = 1000; const clientHeight = 500; for (const testCase of [ { name: 'when viewing the top of the post list', scrollOffset: 0, expected: false, }, { name: 'when 11 pixel from the bottom', scrollOffset: 489, expected: false, }, { name: 'when 9 pixel from the bottom also considered to be bottom', scrollOffset: 490, expected: true, }, { name: 'when clientHeight is less than scrollHeight', // scrollHeight is a state value in virt list and can be one cycle off when compared to actual value scrollOffset: 501, expected: true, }, ]) { test(testCase.name, () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); expect(wrapper.instance().isAtBottom(testCase.scrollOffset, scrollHeight, clientHeight)).toBe(testCase.expected); }); } }); describe('updateAtBottom', () => { test('should update atBottom and lastViewedBottom when atBottom changes', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.setState({lastViewedBottom: 1234, atBottom: false}); wrapper.instance().updateAtBottom(true); expect(wrapper.state('atBottom')).toBe(true); expect(wrapper.state('lastViewedBottom')).not.toBe(1234); }); test('should not update lastViewedBottom when atBottom does not change', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.setState({lastViewedBottom: 1234, atBottom: false}); wrapper.instance().updateAtBottom(false); expect(wrapper.state('lastViewedBottom')).toBe(1234); }); test('should update lastViewedBottom with latestPostTimeStamp as that is greater than Date.now()', () => { Date.now = jest.fn().mockReturnValue(12344); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.setState({lastViewedBottom: 1234, atBottom: false}); wrapper.instance().updateAtBottom(true); expect(wrapper.state('lastViewedBottom')).toBe(12345); }); test('should update lastViewedBottom with Date.now() as it is greater than latestPostTimeStamp', () => { Date.now = jest.fn().mockReturnValue(12346); const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.setState({lastViewedBottom: 1234, atBottom: false}); wrapper.instance().updateAtBottom(true); expect(wrapper.state('lastViewedBottom')).toBe(12346); }); }); describe('Scroll correction logic on mount of posts at the top', () => { test('should return previous scroll position from getSnapshotBeforeUpdate', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); instance.componentDidUpdate = jest.fn(); instance.postListRef = {current: {scrollHeight: 100, parentElement: {scrollTop: 10}} as unknown as HTMLDivElement}; wrapper.setState({atBottom: false}); wrapper.setProps({atOldestPost: true}); expect(instance.componentDidUpdate).toHaveBeenCalledTimes(2); expect((instance.componentDidUpdate as jest.Mock).mock.calls[1][2]).toEqual({previousScrollTop: 10, previousScrollHeight: 100}); instance.postListRef = {current: {scrollHeight: 200, parentElement: {scrollTop: 30}} as unknown as HTMLDivElement}; wrapper.setProps({postListIds: [ 'post1', 'post2', 'post3', DATE_LINE + 1551711600000, 'post4', ]}); expect(instance.componentDidUpdate).toHaveBeenCalledTimes(3); expect((instance.componentDidUpdate as jest.Mock).mock.calls[2][2]).toEqual({previousScrollTop: 30, previousScrollHeight: 200}); }); test('should not return previous scroll position from getSnapshotBeforeUpdate as list is at bottom', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); instance.componentDidUpdate = jest.fn(); instance.postListRef = {current: {scrollHeight: 100, parentElement: {scrollTop: 10}} as unknown as HTMLDivElement}; wrapper.setProps({atOldestPost: true}); wrapper.setState({atBottom: true}); expect((instance.componentDidUpdate as jest.Mock).mock.calls[1][2]).toEqual(null); }); }); describe('initRangeToRender', () => { test('should return 0 to 50 for channel with more than 100 messages', () => { const postListIds = []; for (let i = 0; i < 110; i++) { postListIds.push(`post${i}`); } const props = { ...baseProps, postListIds, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); expect(instance.initRangeToRender).toEqual([0, 50]); }); test('should return range if new messages are present', () => { const postListIds = []; for (let i = 0; i < 120; i++) { postListIds.push(`post${i}`); } postListIds[65] = PostListRowListIds.START_OF_NEW_MESSAGES; const props = { ...baseProps, postListIds, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); expect(instance.initRangeToRender).toEqual([35, 95]); }); }); describe('renderRow', () => { test('should have appropriate classNames for rows with START_OF_NEW_MESSAGES and DATE_LINE', () => { const props = { ...baseProps, postListIds: postListIdsForClassNames, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); const post3Row = shallow(instance.renderRow({ data: postListIdsForClassNames, itemId: 'post3', style: {}, })); const post5Row = shallow(instance.renderRow({ data: postListIdsForClassNames, itemId: 'post5', style: {}, })); expect(post3Row.prop('className')).toEqual('post-row__padding top'); expect(post5Row.prop('className')).toEqual('post-row__padding bottom'); }); test('should have both top and bottom classNames as post is in between DATE_LINE and START_OF_NEW_MESSAGES', () => { const props = { ...baseProps, postListIds: [ 'post1', 'post2', 'post3', DATE_LINE + 1551711600000, 'post4', PostListRowListIds.START_OF_NEW_MESSAGES, 'post5', ], }; const wrapper = shallow<PostList>(<PostList {...props}/>); const row = shallow(wrapper.instance().renderRow({ data: props.postListIds, itemId: 'post4', style: {}, })); expect(row.prop('className')).toEqual('post-row__padding bottom top'); }); test('should have empty string as className when both previousItemId and nextItemId are posts', () => { const props = { ...baseProps, postListIds: [ 'post1', 'post2', 'post3', DATE_LINE + 1551711600000, 'post4', PostListRowListIds.START_OF_NEW_MESSAGES, 'post5', ], }; const wrapper = shallow<PostList>(<PostList {...props}/>); const row = shallow(wrapper.instance().renderRow({ data: props.postListIds, itemId: 'post2', style: {}, })); expect(row.prop('className')).toEqual(''); }); }); describe('updateFloatingTimestamp', () => { test('should not update topPostId as is it not mobile view', () => { const props = { ...baseProps, isMobileView: false, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); instance.onItemsRendered({visibleStartIndex: 0, visibleStopIndex: 0}); expect(wrapper.state('topPostId')).toBe(''); }); test('should update topPostId with latest visible postId', () => { const props = { ...baseProps, isMobileView: true, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); instance.onItemsRendered({visibleStartIndex: 1, visibleStopIndex: 0}); expect(wrapper.state('topPostId')).toBe('post2'); instance.onItemsRendered({visibleStartIndex: 2, visibleStopIndex: 0}); expect(wrapper.state('topPostId')).toBe('post3'); }); }); describe('scrollToLatestMessages', () => { test('should call scrollToBottom', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.setProps({atLatestPost: true}); const instance = wrapper.instance(); instance.scrollToBottom = jest.fn(); instance.scrollToLatestMessages(); expect(instance.scrollToBottom).toHaveBeenCalled(); }); test('should call changeUnreadChunkTimeStamp', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); const instance = wrapper.instance(); instance.scrollToLatestMessages(); expect(baseActions.changeUnreadChunkTimeStamp).toHaveBeenCalledWith(0); }); }); describe('postIds state', () => { test('should have LOAD_NEWER_MESSAGES_TRIGGER and LOAD_OLDER_MESSAGES_TRIGGER', () => { const wrapper = shallow<PostList>(<PostList {...baseProps}/>); wrapper.setProps({autoRetryEnable: false}); const postListIdsState = wrapper.state('postListIds'); expect(postListIdsState[0]).toBe(PostListRowListIds.LOAD_NEWER_MESSAGES_TRIGGER); expect(postListIdsState[postListIdsState.length - 1]).toBe(PostListRowListIds.LOAD_OLDER_MESSAGES_TRIGGER); }); }); describe('initScrollToIndex', () => { test('return date index if it is just above new message line', () => { const postListIds = [ 'post1', 'post2', 'post3', 'post4', PostListRowListIds.START_OF_NEW_MESSAGES, DATE_LINE + 1551711600000, 'post5', ]; const props = { ...baseProps, postListIds, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); const initScrollToIndex = instance.initScrollToIndex(); expect(initScrollToIndex).toEqual({index: 6, position: 'start', offset: -50}); }); }); test('return new message line index if there is no date just above it', () => { const postListIds = [ 'post1', 'post2', 'post3', 'post4', PostListRowListIds.START_OF_NEW_MESSAGES, 'post5', ]; const props = { ...baseProps, postListIds, }; const wrapper = shallow<PostList>(<PostList {...props}/>); const instance = wrapper.instance(); const initScrollToIndex = instance.initScrollToIndex(); expect(initScrollToIndex).toEqual({index: 5, position: 'start', offset: -50}); }); });
2,865
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_message_preview/post_message_preview.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 type {Post, PostEmbed} from '@mattermost/types/posts'; import type {UserProfile} from '@mattermost/types/users'; import {General} from 'mattermost-redux/constants'; import PostMessagePreview from './post_message_preview'; import type {Props} from './post_message_preview'; describe('PostMessagePreview', () => { const previewPost = { id: 'post_id', message: 'post message', metadata: {}, } as Post; const user = { id: 'user_1', username: 'username1', } as UserProfile; const baseProps: Props = { metadata: { channel_display_name: 'channel name', team_name: 'team1', post_id: 'post_id', channel_type: 'O', channel_id: 'channel_id', }, previewPost, user, hasImageProxy: false, enablePostIconOverride: false, isEmbedVisible: true, compactDisplay: false, currentTeamUrl: 'team1', channelDisplayName: 'channel name', handleFileDropdownOpened: jest.fn(), actions: { toggleEmbedVisibility: jest.fn(), }, isPostPriorityEnabled: false, }; test('should render correctly', () => { const wrapper = shallow(<PostMessagePreview {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should render without preview', () => { const wrapper = shallow( <PostMessagePreview {...baseProps} previewPost={undefined} />, ); expect(wrapper).toMatchSnapshot(); }); test('show render without preview when preview posts becomes undefined after being defined', () => { const props = {...baseProps}; let wrapper = shallow( <PostMessagePreview {...props} />, ); expect(wrapper).toMatchSnapshot(); let permalink = wrapper.find('.permalink'); expect(permalink.length).toBe(1); // now we'll set the preview post to undefined. This happens when the // previewed post is deleted. props.previewPost = undefined; wrapper = shallow( <PostMessagePreview {...props} />, ); expect(wrapper).toMatchSnapshot(); permalink = wrapper.find('.permalink'); expect(permalink.length).toBe(0); }); test('should not render bot icon', () => { const postProps = { override_icon_url: 'https://fakeicon.com/image.jpg', use_user_icon: 'false', from_webhook: 'false', }; const postPreview = { ...previewPost, props: postProps, } as unknown as Post; const props = { ...baseProps, previewPost: postPreview, }; const wrapper = shallow( <PostMessagePreview {...props} />, ); expect(wrapper).toMatchSnapshot(); }); test('should render bot icon', () => { const postProps = { override_icon_url: 'https://fakeicon.com/image.jpg', use_user_icon: false, from_webhook: 'true', }; const postPreview = { ...previewPost, props: postProps, } as unknown as Post; const props = { ...baseProps, previewPost: postPreview, enablePostIconOverride: true, }; const wrapper = shallow( <PostMessagePreview {...props} />, ); expect(wrapper).toMatchSnapshot(); }); describe('nested previews', () => { const files = { file_ids: [ 'file_1', 'file_2', ], }; const opengraphMetadata = { type: 'opengraph', url: 'https://example.com', } as PostEmbed; test('should render opengraph preview', () => { const postPreview = { ...previewPost, metadata: { embeds: [opengraphMetadata], }, } as Post; const props = { ...baseProps, previewPost: postPreview, }; const wrapper = shallow(<PostMessagePreview {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should render file preview', () => { const postPreview = { ...previewPost, ...files, } as Post; const props = { ...baseProps, previewPost: postPreview, }; const wrapper = shallow(<PostMessagePreview {...props}/>); expect(wrapper).toMatchSnapshot(); }); }); describe('direct and group messages', () => { const channelTypes = [General.DM_CHANNEL, General.GM_CHANNEL] as ChannelType[]; test.each(channelTypes)('should render preview for %s message', (type) => { const metadata = { ...baseProps.metadata, team_name: '', channel_type: type, channel_id: 'channel_id', }; const props = { ...baseProps, metadata, }; const wrapper = shallow( <PostMessagePreview {...props} />, ); expect(wrapper).toMatchSnapshot(); }); }); });
2,867
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_message_preview
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_message_preview/__snapshots__/post_message_preview.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`PostMessagePreview direct and group messages should render preview for D message 1`] = ` <PostAttachmentContainer className="permalink" link="team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object {}, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview direct and group messages should render preview for G message 1`] = ` <PostAttachmentContainer className="permalink" link="team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object {}, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview nested previews should render file preview 1`] = ` <PostAttachmentContainer className="permalink" link="/team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "file_ids": Array [ "file_1", "file_2", ], "id": "post_id", "message": "post message", "metadata": Object {}, } } /> <Connect(FileAttachmentList) compactDisplay={false} handleFileDropdownOpened={[MockFunction]} isInPermalink={true} post={ Object { "file_ids": Array [ "file_1", "file_2", ], "id": "post_id", "message": "post message", "metadata": Object {}, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview nested previews should render opengraph preview 1`] = ` <PostAttachmentContainer className="permalink" link="/team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object { "embeds": Array [ Object { "type": "opengraph", "url": "https://example.com", }, ], }, } } /> <Connect(PostAttachmentOpenGraph) isEmbedVisible={true} isInPermalink={true} link="https://example.com" post={ Object { "id": "post_id", "message": "post message", "metadata": Object { "embeds": Array [ Object { "type": "opengraph", "url": "https://example.com", }, ], }, } } postId="post_id" toggleEmbedVisibility={[Function]} /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview should not render bot icon 1`] = ` <PostAttachmentContainer className="permalink" link="/team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object {}, "props": Object { "from_webhook": "false", "override_icon_url": "https://fakeicon.com/image.jpg", "use_user_icon": "false", }, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview should render bot icon 1`] = ` <PostAttachmentContainer className="permalink" link="/team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="https://fakeicon.com/image.jpg" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object {}, "props": Object { "from_webhook": "true", "override_icon_url": "https://fakeicon.com/image.jpg", "use_user_icon": false, }, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview should render correctly 1`] = ` <PostAttachmentContainer className="permalink" link="/team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object {}, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview should render without preview 1`] = `""`; exports[`PostMessagePreview show render without preview when preview posts becomes undefined after being defined 1`] = ` <PostAttachmentContainer className="permalink" link="/team1/pl/post_id" > <div className="post-preview" > <div className="post-preview__header" > <div className="col col__name" > <div className="post__img" > <span className="profile-icon" > <Memo(Avatar) className="avatar-post-preview" size="sm" url="/api/v4/users/user_1/image?_=0" username="username1" /> </span> </div> </div> <div className="col col__name permalink--username" > <Connect(UserProfile) disablePopover={true} hasMention={true} overwriteName="" userId="user_1" /> </div> <div className="col d-flex align-items-center" > <Connect(injectIntl(Timestamp)) className="post-preview__time" day="numeric" units={ Array [ "now", "minute", "hour", "day", ] } useTime={false} /> </div> </div> <Connect(PostMessageView) maxHeight={105} overflowType="ellipsis" post={ Object { "id": "post_id", "message": "post message", "metadata": Object {}, } } /> <div className="post__preview-footer" > <p> <MemoizedFormattedMessage defaultMessage="Only visible to users in ~{channel}" id="post_message_preview.channel" values={ Object { "channel": "channel name", } } /> </p> </div> </div> </PostAttachmentContainer> `; exports[`PostMessagePreview show render without preview when preview posts becomes undefined after being defined 2`] = `""`;
2,869
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_message_view/post_message_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 type {Post, PostType} from '@mattermost/types/posts'; import {Posts} from 'mattermost-redux/constants'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import PostMessageView from 'components/post_view/post_message_view/post_message_view'; describe('components/post_view/PostAttachment', () => { const post = { id: 'post_id', message: 'post message', } as Post; const baseProps = { post, enableFormatting: true, options: {}, compactDisplay: false, isRHS: false, isRHSOpen: false, isRHSExpanded: false, theme: {} as Theme, pluginPostTypes: {}, currentRelativeTeamUrl: 'dummy_team_url', }; test('should match snapshot', () => { const wrapper = shallow(<PostMessageView {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on Show More', () => { const wrapper = shallow(<PostMessageView {...baseProps}/>); wrapper.setState({hasOverflow: true, collapse: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on Show Less', () => { const wrapper = shallow(<PostMessageView {...baseProps}/>); wrapper.setState({hasOverflow: true, collapse: false}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on deleted post', () => { const props = {...baseProps, post: {...post, state: Posts.POST_DELETED as 'DELETED'}}; const wrapper = shallow(<PostMessageView {...props}/>); const instance = wrapper.instance() as PostMessageView; expect(wrapper).toMatchSnapshot(); expect(instance.renderDeletedPost()).toMatchSnapshot(); }); test('should match snapshot, on edited post', () => { const props = {...baseProps, post: {...post, edit_at: 1}}; const wrapper = shallow(<PostMessageView {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on ephemeral post', () => { const props = {...baseProps, post: {...post, type: Posts.POST_TYPES.EPHEMERAL as PostType}}; const wrapper = shallow(<PostMessageView {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match checkOverflow state on handleHeightReceived change', () => { const wrapper = shallow(<PostMessageView {...baseProps}/>); const instance = wrapper.instance() as PostMessageView; wrapper.setState({checkOverflow: 0}); instance.handleHeightReceived(1); expect(wrapper.state('checkOverflow')).toEqual(1); instance.handleHeightReceived(0); expect(wrapper.state('checkOverflow')).toEqual(1); }); });
2,871
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_message_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_message_view/__snapshots__/post_message_view.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/PostAttachment should match snapshot 1`] = ` <Connect(ShowMore) checkOverflow={0} text="post message" > <div className="post-message__text" dir="auto" id="postMessageText_post_id" onClick={[Function]} tabIndex={0} > <Connect(PostMarkdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="post message" options={Object {}} post={ Object { "id": "post_id", "message": "post message", } } /> </div> <Connect(Pluggable) onHeightChange={[Function]} pluggableName="PostMessageAttachment" postId="post_id" /> </Connect(ShowMore)> `; exports[`components/post_view/PostAttachment should match snapshot, on Show Less 1`] = ` <Connect(ShowMore) checkOverflow={0} text="post message" > <div className="post-message__text" dir="auto" id="postMessageText_post_id" onClick={[Function]} tabIndex={0} > <Connect(PostMarkdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="post message" options={Object {}} post={ Object { "id": "post_id", "message": "post message", } } /> </div> <Connect(Pluggable) onHeightChange={[Function]} pluggableName="PostMessageAttachment" postId="post_id" /> </Connect(ShowMore)> `; exports[`components/post_view/PostAttachment should match snapshot, on Show More 1`] = ` <Connect(ShowMore) checkOverflow={0} text="post message" > <div className="post-message__text" dir="auto" id="postMessageText_post_id" onClick={[Function]} tabIndex={0} > <Connect(PostMarkdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="post message" options={Object {}} post={ Object { "id": "post_id", "message": "post message", } } /> </div> <Connect(Pluggable) onHeightChange={[Function]} pluggableName="PostMessageAttachment" postId="post_id" /> </Connect(ShowMore)> `; exports[`components/post_view/PostAttachment should match snapshot, on deleted post 1`] = ` <p> <MemoizedFormattedMessage defaultMessage="(message deleted)" id="post_body.deleted" /> </p> `; exports[`components/post_view/PostAttachment should match snapshot, on deleted post 2`] = ` <p> <Memo(MemoizedFormattedMessage) defaultMessage="(message deleted)" id="post_body.deleted" /> </p> `; exports[`components/post_view/PostAttachment should match snapshot, on edited post 1`] = ` <Connect(ShowMore) checkOverflow={0} text="post message" > <div className="post-message__text" dir="auto" id="postMessageText_post_id" onClick={[Function]} tabIndex={0} > <Connect(PostMarkdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="post message" options={Object {}} post={ Object { "edit_at": 1, "id": "post_id", "message": "post message", } } /> </div> <Connect(Pluggable) onHeightChange={[Function]} pluggableName="PostMessageAttachment" postId="post_id" /> </Connect(ShowMore)> `; exports[`components/post_view/PostAttachment should match snapshot, on ephemeral post 1`] = ` <Connect(ShowMore) checkOverflow={0} text="post message" > <div className="post-message__text" dir="auto" id="postMessageText_post_id" onClick={[Function]} tabIndex={0} > <Connect(PostMarkdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="post message" options={Object {}} post={ Object { "id": "post_id", "message": "post message", "type": "system_ephemeral", } } /> </div> <Connect(Pluggable) onHeightChange={[Function]} pluggableName="PostMessageAttachment" postId="post_id" /> </Connect(ShowMore)> `;
2,873
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_pre_header/post_pre_header.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {FormattedMessage} from 'react-intl'; import PostPreHeader from 'components/post_view/post_pre_header/post_pre_header'; import FlagIconFilled from 'components/widgets/icons/flag_icon_filled'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; describe('components/PostPreHeader', () => { const baseProps = { channelId: 'channel_id', actions: { showFlaggedPosts: jest.fn(), showPinnedPosts: jest.fn(), }, }; test('should not render anything if the post is neither flagged nor pinned', () => { const props = { ...baseProps, isFlagged: false, isPinned: false, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find('div')).toHaveLength(0); expect(wrapper).toMatchSnapshot(); }); test('should not render anything if both skipFlagged and skipPinned are true', () => { const props = { ...baseProps, isFlagged: true, isPinned: true, skipFlagged: true, skipPinned: true, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find('div')).toHaveLength(0); expect(wrapper).toMatchSnapshot(); }); test('should properly handle flagged posts (and not pinned)', () => { const props = { ...baseProps, isFlagged: true, isPinned: false, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find('span.icon-pin')).toHaveLength(0); expect(wrapper.find(FlagIconFilled)).toHaveLength(1); expect(wrapper.find(FormattedMessage)).toHaveLength(1); expect(wrapper.find(FormattedMessage).prop('defaultMessage')).toEqual('Saved'); expect(wrapper).toMatchSnapshot(); // case of skipFlagged is true wrapper.setProps({...props, skipFlagged: true}); expect(wrapper.find(FlagIconFilled)).toHaveLength(0); expect(wrapper.find(FormattedMessage)).toHaveLength(0); expect(wrapper).toMatchSnapshot(); }); test('should properly handle pinned posts (and not flagged)', () => { const props = { ...baseProps, isFlagged: false, isPinned: true, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find(FlagIconFilled)).toHaveLength(0); expect(wrapper.find('span.icon-pin')).toHaveLength(1); expect(wrapper.find(FormattedMessage)).toHaveLength(1); expect(wrapper.find(FormattedMessage).prop('defaultMessage')).toEqual('Pinned'); expect(wrapper).toMatchSnapshot(); // case of skipPinned is true wrapper.setProps({...props, skipPinned: true}); expect(wrapper.find('span.icon-pin')).toHaveLength(0); expect(wrapper.find(FormattedMessage)).toHaveLength(0); expect(wrapper).toMatchSnapshot(); }); describe('should properly handle posts that are flagged and pinned', () => { test('both skipFlagged and skipPinned are not true', () => { const props = { ...baseProps, isFlagged: true, isPinned: true, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find(FlagIconFilled)).toHaveLength(1); expect(wrapper.find('span.icon-pin')).toHaveLength(1); expect(wrapper.find(FormattedMessage)).toHaveLength(2); expect(wrapper.find(FormattedMessage).first().prop('defaultMessage')).toEqual('Pinned'); expect(wrapper.find(FormattedMessage).last().prop('defaultMessage')).toEqual('Saved'); expect(wrapper).toMatchSnapshot(); }); test('skipFlagged is true', () => { const props = { ...baseProps, isFlagged: true, isPinned: true, skipFlagged: true, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find(FlagIconFilled)).toHaveLength(0); expect(wrapper.find('span.icon-pin')).toHaveLength(1); expect(wrapper.find(FormattedMessage)).toHaveLength(1); expect(wrapper.find(FormattedMessage).prop('defaultMessage')).toEqual('Pinned'); expect(wrapper).toMatchSnapshot(); }); test('skipPinned is true', () => { const props = { ...baseProps, isFlagged: true, isPinned: true, skipPinned: true, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find('span.icon-pin')).toHaveLength(0); expect(wrapper.find(FlagIconFilled)).toHaveLength(1); expect(wrapper.find(FormattedMessage)).toHaveLength(1); expect(wrapper.find(FormattedMessage).prop('defaultMessage')).toEqual('Saved'); expect(wrapper).toMatchSnapshot(); }); }); test('should properly handle link clicks', () => { const props = { ...baseProps, isFlagged: true, isPinned: true, }; const wrapper = shallowWithIntl( <PostPreHeader {...props}/>, ); expect(wrapper.find(FlagIconFilled)).toHaveLength(1); expect(wrapper.find('span.icon-pin')).toHaveLength(1); expect(wrapper.find(FormattedMessage)).toHaveLength(2); expect(wrapper).toMatchSnapshot(); wrapper.find('a').first().simulate('click'); expect(baseProps.actions.showPinnedPosts).toHaveBeenNthCalledWith(1, baseProps.channelId); wrapper.find('a').last().simulate('click'); expect(baseProps.actions.showFlaggedPosts).toHaveBeenNthCalledWith(1); }); });
2,875
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_pre_header
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_pre_header/__snapshots__/post_pre_header.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/PostPreHeader should not render anything if both skipFlagged and skipPinned are true 1`] = `""`; exports[`components/PostPreHeader should not render anything if the post is neither flagged nor pinned 1`] = `""`; exports[`components/PostPreHeader should properly handle flagged posts (and not pinned) 1`] = ` <div className="post-pre-header" > <div className="post-pre-header__icons-container" > <FlagIconFilled className="icon icon--post-pre-header" /> </div> <div className="post-pre-header__text-container" > <span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Saved" id="post_pre_header.flagged" /> </a> </span> </div> </div> `; exports[`components/PostPreHeader should properly handle flagged posts (and not pinned) 2`] = `""`; exports[`components/PostPreHeader should properly handle link clicks 1`] = ` <div className="post-pre-header" > <div className="post-pre-header__icons-container" > <span className="icon-pin icon icon--post-pre-header" /> <FlagIconFilled className="icon icon--post-pre-header" /> </div> <div className="post-pre-header__text-container" > <span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Pinned" id="post_pre_header.pinned" /> </a> <span className="post-pre-header__link-separator" > ⬤ </span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Saved" id="post_pre_header.flagged" /> </a> </span> </div> </div> `; exports[`components/PostPreHeader should properly handle pinned posts (and not flagged) 1`] = ` <div className="post-pre-header" > <div className="post-pre-header__icons-container" > <span className="icon-pin icon icon--post-pre-header" /> </div> <div className="post-pre-header__text-container" > <span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Pinned" id="post_pre_header.pinned" /> </a> </span> </div> </div> `; exports[`components/PostPreHeader should properly handle pinned posts (and not flagged) 2`] = `""`; exports[`components/PostPreHeader should properly handle posts that are flagged and pinned both skipFlagged and skipPinned are not true 1`] = ` <div className="post-pre-header" > <div className="post-pre-header__icons-container" > <span className="icon-pin icon icon--post-pre-header" /> <FlagIconFilled className="icon icon--post-pre-header" /> </div> <div className="post-pre-header__text-container" > <span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Pinned" id="post_pre_header.pinned" /> </a> <span className="post-pre-header__link-separator" > ⬤ </span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Saved" id="post_pre_header.flagged" /> </a> </span> </div> </div> `; exports[`components/PostPreHeader should properly handle posts that are flagged and pinned skipFlagged is true 1`] = ` <div className="post-pre-header" > <div className="post-pre-header__icons-container" > <span className="icon-pin icon icon--post-pre-header" /> </div> <div className="post-pre-header__text-container" > <span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Pinned" id="post_pre_header.pinned" /> </a> </span> </div> </div> `; exports[`components/PostPreHeader should properly handle posts that are flagged and pinned skipPinned is true 1`] = ` <div className="post-pre-header" > <div className="post-pre-header__icons-container" > <FlagIconFilled className="icon icon--post-pre-header" /> </div> <div className="post-pre-header__text-container" > <span> <a onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Saved" id="post_pre_header.flagged" /> </a> </span> </div> </div> `;
2,877
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_reaction/post_reaction.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 {Emoji} from '@mattermost/types/emojis'; import PostReaction from 'components/post_view/post_reaction/post_reaction'; describe('components/post_view/PostReaction', () => { const baseProps = { channelId: 'current_channel_id', postId: 'post_id_1', teamId: 'current_team_id', getDotMenuRef: jest.fn(), showIcon: false, showEmojiPicker: false, toggleEmojiPicker: jest.fn(), actions: { toggleReaction: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow(<PostReaction {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should call toggleReaction and toggleEmojiPicker on handleToggleEmoji', () => { const wrapper = shallow(<PostReaction {...baseProps}/>); const instance = wrapper.instance() as PostReaction; instance.handleToggleEmoji({name: 'smile'} as Emoji); expect(baseProps.actions.toggleReaction).toHaveBeenCalledTimes(1); expect(baseProps.actions.toggleReaction).toHaveBeenCalledWith('post_id_1', 'smile'); expect(baseProps.toggleEmojiPicker).toHaveBeenCalledTimes(1); }); });
2,879
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_reaction
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/post_reaction/__snapshots__/post_reaction.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/PostReaction should match snapshot 1`] = ` <Connect(Component) channelId="current_channel_id" permissions={ Array [ "add_reaction", ] } teamId="current_team_id" > <Connect(EmojiPickerOverlay) onEmojiClick={[Function]} onHide={[MockFunction]} show={false} target={[MockFunction]} topOffset={-7} /> <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="reaction-icon-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add Reaction" id="post_info.tooltip.add_reactions" /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add reaction" className="post-menu__item post-menu__item--reactions" data-testid="post-reaction-emoji-icon" id="CENTER_reaction_post_id_1" onClick={[MockFunction]} > <Memo(EmojiIcon) className="icon icon--small" /> </button> </OverlayTrigger> </Connect(Component)> `;
2,887
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction/reaction.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 {Reaction as ReactionType} from '@mattermost/types/reactions'; import Reaction from 'components/post_view/reaction/reaction'; import {TestHelper} from 'utils/test_helper'; describe('components/post_view/Reaction', () => { const post = TestHelper.getPostMock({ id: 'post_id', }); const reactions: ReactionType[] = [{ user_id: 'user_id_2', post_id: post.id, emoji_name: ':smile:', create_at: 0, }, { user_id: 'user_id_3', post_id: post.id, emoji_name: ':smile:', create_at: 0}]; const emojiName = 'smile'; const actions = { addReaction: jest.fn(), getMissingProfilesByIds: jest.fn(), removeReaction: jest.fn(), }; const currentUserId = 'user_id_1'; const baseProps = { canAddReactions: true, canRemoveReactions: true, currentUserId, post, currentUserReacted: false, emojiName, reactionCount: 2, reactions, emojiImageUrl: 'emoji_image_url', actions, }; test('should match snapshot', () => { const wrapper = shallow<Reaction>(<Reaction {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when a current user reacted to a post', () => { const newReactions = [{ user_id: 'user_id_1', post_id: post.id, emoji_name: ':cry:', create_at: 0, }, { user_id: 'user_id_3', post_id: post.id, emoji_name: ':smile:', create_at: 0}]; const props = { ...baseProps, currentUserReacted: true, reactions: newReactions, }; const wrapper = shallow<Reaction>(<Reaction {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should return null/empty if no emojiImageUrl', () => { const props = {...baseProps, emojiImageUrl: ''}; const wrapper = shallow<Reaction>(<Reaction {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should apply read-only class if user does not have permission to add reaction', () => { const props = {...baseProps, canAddReactions: false}; const wrapper = shallow<Reaction>(<Reaction {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should apply read-only class if user does not have permission to remove reaction', () => { const newCurrentUserId = 'user_id_2'; const props = { ...baseProps, canRemoveReactions: false, currentUserId: newCurrentUserId, currentUserReacted: true, }; const wrapper = shallow<Reaction>(<Reaction {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should have called actions.getMissingProfilesByIds when loadMissingProfiles is called', () => { const wrapper = shallow<Reaction>(<Reaction {...baseProps}/>); wrapper.instance().loadMissingProfiles(); expect(actions.getMissingProfilesByIds).toHaveBeenCalledTimes(1); expect(actions.getMissingProfilesByIds).toHaveBeenCalledWith([reactions[0].user_id, reactions[1].user_id]); }); });
2,889
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction/__snapshots__/reaction.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/Reaction should apply read-only class if user does not have permission to add reaction 1`] = ` <OverlayTrigger defaultOverlayShown={false} delayShow={500} onEnter={[Function]} overlay={ <Tooltip id="post_id-smile-reaction" > <Memo(Connect(ReactionTooltip)) canAddReactions={false} canRemoveReactions={true} currentUserReacted={false} emojiIcon={ <img className="Reaction__emoji emoticon" src="emoji_image_url" /> } emojiName="smile" reactions={ Array [ Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_2", }, Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_3", }, ] } /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <button aria-label="react with smile" className="Reaction Reaction--unreacted Reaction--read-only" id="postReaction-post_id-smile" onClick={[Function]} > <span className="d-flex align-items-center" > <img className="Reaction__emoji emoticon" src="emoji_image_url" /> <span className="Reaction__count" > <span className="Reaction__number" > <span className="Reaction__number--display" > 2 </span> <span className="Reaction__number--unreacted" onAnimationEnd={[Function]} > 2 </span> <span className="Reaction__number--reacted" > 3 </span> </span> </span> </span> </button> </OverlayTrigger> `; exports[`components/post_view/Reaction should apply read-only class if user does not have permission to remove reaction 1`] = ` <OverlayTrigger defaultOverlayShown={false} delayShow={500} onEnter={[Function]} overlay={ <Tooltip id="post_id-smile-reaction" > <Memo(Connect(ReactionTooltip)) canAddReactions={true} canRemoveReactions={false} currentUserReacted={true} emojiIcon={ <img className="Reaction__emoji emoticon" src="emoji_image_url" /> } emojiName="smile" reactions={ Array [ Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_2", }, Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_3", }, ] } /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <button aria-label="react with smile" className="Reaction Reaction--reacted Reaction--read-only" id="postReaction-post_id-smile" onClick={[Function]} > <span className="d-flex align-items-center" > <img className="Reaction__emoji emoticon" src="emoji_image_url" /> <span className="Reaction__count" > <span className="Reaction__number" > <span className="Reaction__number--display" > 2 </span> <span className="Reaction__number--unreacted" onAnimationEnd={[Function]} > 1 </span> <span className="Reaction__number--reacted" > 2 </span> </span> </span> </span> </button> </OverlayTrigger> `; exports[`components/post_view/Reaction should match snapshot 1`] = ` <OverlayTrigger defaultOverlayShown={false} delayShow={500} onEnter={[Function]} overlay={ <Tooltip id="post_id-smile-reaction" > <Memo(Connect(ReactionTooltip)) canAddReactions={true} canRemoveReactions={true} currentUserReacted={false} emojiIcon={ <img className="Reaction__emoji emoticon" src="emoji_image_url" /> } emojiName="smile" reactions={ Array [ Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_2", }, Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_3", }, ] } /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <button aria-label="react with smile" className="Reaction Reaction--unreacted " id="postReaction-post_id-smile" onClick={[Function]} > <span className="d-flex align-items-center" > <img className="Reaction__emoji emoticon" src="emoji_image_url" /> <span className="Reaction__count" > <span className="Reaction__number" > <span className="Reaction__number--display" > 2 </span> <span className="Reaction__number--unreacted" onAnimationEnd={[Function]} > 2 </span> <span className="Reaction__number--reacted" > 3 </span> </span> </span> </span> </button> </OverlayTrigger> `; exports[`components/post_view/Reaction should match snapshot when a current user reacted to a post 1`] = ` <OverlayTrigger defaultOverlayShown={false} delayShow={500} onEnter={[Function]} overlay={ <Tooltip id="post_id-smile-reaction" > <Memo(Connect(ReactionTooltip)) canAddReactions={true} canRemoveReactions={true} currentUserReacted={true} emojiIcon={ <img className="Reaction__emoji emoticon" src="emoji_image_url" /> } emojiName="smile" reactions={ Array [ Object { "create_at": 0, "emoji_name": ":cry:", "post_id": "post_id", "user_id": "user_id_1", }, Object { "create_at": 0, "emoji_name": ":smile:", "post_id": "post_id", "user_id": "user_id_3", }, ] } /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <button aria-label="remove reaction smile" className="Reaction Reaction--reacted " id="postReaction-post_id-smile" onClick={[Function]} > <span className="d-flex align-items-center" > <img className="Reaction__emoji emoticon" src="emoji_image_url" /> <span className="Reaction__count" > <span className="Reaction__number" > <span className="Reaction__number--display" > 2 </span> <span className="Reaction__number--unreacted" onAnimationEnd={[Function]} > 1 </span> <span className="Reaction__number--reacted" > 2 </span> </span> </span> </span> </button> </OverlayTrigger> `; exports[`components/post_view/Reaction should return null/empty if no emojiImageUrl 1`] = `""`;
2,890
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction/reaction_tooltip/index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Reaction} from '@mattermost/types/reactions'; import type {GlobalState} from '@mattermost/types/store'; import {TestHelper} from 'utils/test_helper'; import {makeGetNamesOfUsers} from './index'; describe('makeGetNamesOfUsers', () => { test('should sort users by who reacted first', () => { const getNamesOfUsers = makeGetNamesOfUsers(); const post1 = TestHelper.getPostMock({id: 'post1'}); const user1 = TestHelper.getUserMock({id: 'user1', username: 'username_1'}); const user2 = TestHelper.getUserMock({id: 'user2', username: 'username_2'}); const user3 = TestHelper.getUserMock({id: 'user3', username: 'username_3'}); const baseDate = Date.now(); const reactions = [ {user_id: user2.id, create_at: baseDate}, // Will be sorted 2nd, after the logged-in user {user_id: user1.id, create_at: baseDate + 5000}, // Logged-in user, will be sorted first although 2nd user reacted first {user_id: user3.id, create_at: baseDate + 8000}, // Last to react, will be sorted last ] as Reaction[]; const state = { entities: { general: { config: {}, }, posts: { posts: { post1, }, reactions: { post1: reactions, }, }, preferences: { myPreferences: {}, }, users: { currentUserId: user1.id, profiles: { user1, user2, user3, }, }, }, } as unknown as GlobalState; const names = getNamesOfUsers(state, reactions); expect(names).toEqual(['You', 'username_2', 'username_3']); }); });
2,895
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction_list/reactions_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 Reaction from 'components/post_view/reaction'; import {TestHelper} from 'utils/test_helper'; import ReactionList from './reaction_list'; describe('components/ReactionList', () => { const reaction = { user_id: '1rj9fokoeffrigu7sk5uc8aiih', post_id: 'xbqfo5qb4bb4ffmj9hqfji6fiw', emoji_name: 'expressionless', create_at: 1542994995740, }; const reactions = {[reaction.user_id + '-' + reaction.emoji_name]: reaction}; const post = TestHelper.getPostMock({ id: 'post_id', }); const teamId = 'teamId'; const actions = { toggleReaction: jest.fn(), }; const baseProps = { post, teamId, reactions, canAddReactions: true, actions, }; test('should render nothing when no reactions', () => { const props = { ...baseProps, reactions: {}, }; const wrapper = shallow<ReactionList>( <ReactionList {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render when there are reactions', () => { const wrapper = shallow<ReactionList>( <ReactionList {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); /* This test uses 3 different reactions from 2 users. Reactions A and B are done by the first user. React C is an additional reaction with the same emoji as the first by a second user. When the first user removes Reaction A, the ordering should not change. First Render : Reactions A, B and C Second Render : Reactions B, C In both cases, the emoji order should be the same */ test('should render consistently when reactions from state are not in the same order', () => { const reactionA = reaction; const reactionB = {...reaction, emoji_name: '+1', create_at: reaction.create_at + 100}; const reactionC = {...reaction, user_id: 'x8pb0', create_at: reaction.create_at + 200}; const propsA = { ...baseProps, reactions: { [reactionA.user_id + '-' + reactionA.emoji_name]: reactionA, [reactionB.user_id + '-' + reactionB.emoji_name]: reactionB, [reactionC.user_id + '-' + reactionC.emoji_name]: reactionC, }, }; const propsB = { ...baseProps, reactions: { [reactionB.user_id + '-' + reactionB.emoji_name]: reactionB, [reactionC.user_id + '-' + reactionC.emoji_name]: reactionC, }, }; const wrapper = shallow<ReactionList>( <ReactionList {...propsA}/>, ); const firstRender = wrapper.find(Reaction).map((node) => node.key); wrapper.setProps(propsB); const secondRender = wrapper.find(Reaction).map((node) => node.key); expect(firstRender.length).toBe(2); expect(firstRender).toEqual(secondRender); }); });
2,896
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction_list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/reaction_list/__snapshots__/reactions_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ReactionList should render nothing when no reactions 1`] = `""`; exports[`components/ReactionList should render when there are reactions 1`] = ` <div aria-label="reactions" className="post-reaction-list" > <Connect(Reaction) emojiName="expressionless" key="expressionless" post={ Object { "channel_id": "", "create_at": 0, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "post_id", "is_pinned": false, "message": "post message", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } reactions={ Array [ Object { "create_at": 1542994995740, "emoji_name": "expressionless", "post_id": "xbqfo5qb4bb4ffmj9hqfji6fiw", "user_id": "1rj9fokoeffrigu7sk5uc8aiih", }, ] } /> <div className="post-add-reaction" > <span className="emoji-picker__container" > <Connect(EmojiPickerOverlay) onEmojiClick={[Function]} onHide={[Function]} rightOffset={15} show={false} target={[Function]} topOffset={-5} /> <Connect(Component) channelId="" permissions={ Array [ "add_reaction", ] } teamId="teamId" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addReactionTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add a reaction" id="reaction_list.addReactionTooltip" /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-label="Add a reaction" className="Reaction" onClick={[Function]} > <span className="Reaction__add" id="addReaction-post_id" > <AddReactionIcon /> </span> </button> </OverlayTrigger> </Connect(Component)> </span> </div> </div> `;
2,898
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/show_more/show_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 ShowMore from 'components/post_view/show_more/show_more'; describe('components/post_view/ShowMore', () => { const children = (<div><p>{'text'}</p></div>); const baseProps = { checkOverflow: 0, isAttachmentText: false, isRHSExpanded: false, isRHSOpen: false, maxHeight: 200, text: 'text', compactDisplay: false, }; test('should match snapshot', () => { const wrapper = shallow(<ShowMore {...baseProps}>{children}</ShowMore>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, PostMessageView on collapsed view', () => { const wrapper = shallow(<ShowMore {...baseProps}/>); wrapper.setState({isOverflow: true, isCollapsed: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, PostMessageView on expanded view', () => { const wrapper = shallow(<ShowMore {...baseProps}/>); wrapper.setState({isOverflow: true, isCollapsed: false}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, PostAttachment on collapsed view', () => { const wrapper = shallow( <ShowMore {...baseProps} isAttachmentText={true} />, ); wrapper.setState({isOverflow: true, isCollapsed: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, PostAttachment on expanded view', () => { const wrapper = shallow( <ShowMore {...baseProps} isAttachmentText={true} />, ); wrapper.setState({isOverflow: true, isCollapsed: false}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, PostMessageView on expanded view with compactDisplay', () => { const wrapper = shallow( <ShowMore {...baseProps} compactDisplay={true} />, ); wrapper.setState({isOverflow: true, isCollapsed: false}); expect(wrapper).toMatchSnapshot(); }); test('should call checkTextOverflow', () => { const wrapper = shallow(<ShowMore {...baseProps}/>); const instance = wrapper.instance() as ShowMore; instance.checkTextOverflow = jest.fn(); expect(instance.checkTextOverflow).not.toBeCalled(); wrapper.setProps({isRHSExpanded: true}); expect(instance.checkTextOverflow).toBeCalledTimes(1); wrapper.setProps({isRHSExpanded: false}); expect(instance.checkTextOverflow).toBeCalledTimes(2); wrapper.setProps({isRHSOpen: true}); expect(instance.checkTextOverflow).toBeCalledTimes(3); wrapper.setProps({isRHSOpen: false}); expect(instance.checkTextOverflow).toBeCalledTimes(4); wrapper.setProps({text: 'text change'}); expect(instance.checkTextOverflow).toBeCalledTimes(5); wrapper.setProps({text: 'text another change'}); expect(instance.checkTextOverflow).toBeCalledTimes(6); wrapper.setProps({checkOverflow: 1}); expect(instance.checkTextOverflow).toBeCalledTimes(7); wrapper.setProps({checkOverflow: 1}); expect(instance.checkTextOverflow).toBeCalledTimes(7); }); });
2,900
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/show_more
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_view/show_more/__snapshots__/show_more.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/post_view/ShowMore should match snapshot 1`] = ` <div className="post-message post-message--collapsed" > <div className="post-message__text-container" style={ Object { "maxHeight": 200, } } > <div> <p> text </p> </div> </div> </div> `; exports[`components/post_view/ShowMore should match snapshot, PostAttachment on collapsed view 1`] = ` <div className="post-message post-message--collapsed post-message--overflow" > <div className="post-message__text-container" style={ Object { "maxHeight": 200, } } /> <div className="post-collapse" > <div className="post-attachment-collapse__show-more" > <div className="post-collapse__show-more-line" /> <button className="post-collapse__show-more-button" id="showMoreButton" onClick={[Function]} > <span className="fa fa-angle-down" /> Show more </button> <div className="post-collapse__show-more-line" /> </div> </div> </div> `; exports[`components/post_view/ShowMore should match snapshot, PostAttachment on expanded view 1`] = ` <div className="post-message post-message--expanded post-message--overflow" > <div className="post-message__text-container" style={ Object { "maxHeight": undefined, } } /> <div className="post-collapse" > <div className="post-attachment-collapse__show-more" > <div className="post-collapse__show-more-line" /> <button className="post-collapse__show-more-button" id="showMoreButton" onClick={[Function]} > <span className="fa fa-angle-up" /> Show less </button> <div className="post-collapse__show-more-line" /> </div> </div> </div> `; exports[`components/post_view/ShowMore should match snapshot, PostMessageView on collapsed view 1`] = ` <div className="post-message post-message--collapsed post-message--overflow" > <div className="post-message__text-container" style={ Object { "maxHeight": 200, } } /> <div className="post-collapse" > <div className="post-collapse__show-more" > <div className="post-collapse__show-more-line" /> <button className="post-collapse__show-more-button" id="showMoreButton" onClick={[Function]} > <span className="fa fa-angle-down" /> Show more </button> <div className="post-collapse__show-more-line" /> </div> </div> </div> `; exports[`components/post_view/ShowMore should match snapshot, PostMessageView on expanded view 1`] = ` <div className="post-message post-message--expanded post-message--overflow" > <div className="post-message__text-container" style={ Object { "maxHeight": undefined, } } /> <div className="post-collapse" > <div className="post-collapse__show-more" > <div className="post-collapse__show-more-line" /> <button className="post-collapse__show-more-button" id="showMoreButton" onClick={[Function]} > <span className="fa fa-angle-up" /> Show less </button> <div className="post-collapse__show-more-line" /> </div> </div> </div> `; exports[`components/post_view/ShowMore should match snapshot, PostMessageView on expanded view with compactDisplay 1`] = ` <div className="post-message post-message--expanded post-message--overflow" > <div className="post-message__text-container" style={ Object { "maxHeight": undefined, } } /> <div className="post-collapse" > <div className="post-collapse__show-more" > <div className="post-collapse__show-more-line" /> <button className="post-collapse__show-more-button" id="showMoreButton" onClick={[Function]} > <span className="fa fa-angle-up" /> Show less </button> <div className="post-collapse__show-more-line" /> </div> </div> </div> `;
2,905
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace/invite_members.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ComponentProps} from 'react'; import {withIntl} from 'tests/helpers/intl-test-helper'; import {fireEvent, render, screen} from 'tests/react_testing_utils'; import InviteMembers from './invite_members'; describe('InviteMembers component', () => { let defaultProps: ComponentProps<any>; const setEmailsFn = jest.fn(); beforeEach(() => { defaultProps = { disableEdits: false, browserSiteUrl: 'https://my-org.mattermost.com', formUrl: 'https://my-org.mattermost.com/signup', teamInviteId: '1234', className: 'test-class', configSiteUrl: 'https://my-org.mattermost.com/config', onPageView: jest.fn(), previous: <div>{'Previous step'}</div>, next: jest.fn(), setEmails: setEmailsFn, show: true, transitionDirection: 'forward', inferredProtocol: null, isSelfHosted: true, emails: [], }; }); it('should match snapshot', () => { const component = withIntl(<InviteMembers {...defaultProps}/>); const {container} = render(component); expect(container).toMatchSnapshot(); }); it('should match snapshot when it is cloud', () => { const component = withIntl( <InviteMembers {...defaultProps} isSelfHosted={false} />, ); const {container} = render(component); expect(container).toMatchSnapshot(); }); it('renders invite URL', () => { const component = withIntl(<InviteMembers {...defaultProps}/>); render(component); const inviteLink = screen.getByTestId('shareLinkInput'); expect(inviteLink).toHaveAttribute( 'value', 'https://my-org.mattermost.com/config/signup_user_complete/?id=1234', ); }); it('renders submit button with correct text', () => { const component = withIntl(<InviteMembers {...defaultProps}/>); render(component); const button = screen.getByRole('button', {name: 'Finish setup'}); expect(button).toBeInTheDocument(); }); it('button is disabled when disableEdits is true', () => { const component = withIntl( <InviteMembers {...defaultProps} disableEdits={true} />, ); render(component); const button = screen.getByRole('button', {name: 'Finish setup'}); expect(button).toBeDisabled(); }); it('invokes next prop on button click', () => { const component = withIntl(<InviteMembers {...defaultProps}/>); render(component); const button = screen.getByRole('button', {name: 'Finish setup'}); fireEvent.click(button); expect(defaultProps.next).toHaveBeenCalled(); }); it('shows send invites button when in cloud', () => { const component = withIntl( <InviteMembers {...defaultProps} isSelfHosted={false} />, ); render(component); const button = screen.getByRole('button', {name: 'Send invites'}); expect(button).toBeInTheDocument(); }); });
2,909
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace/invite_members_link.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {trackEvent} from 'actions/telemetry_actions'; import {withIntl} from 'tests/helpers/intl-test-helper'; import {fireEvent, render, screen} from 'tests/react_testing_utils'; import InviteMembersLink from './invite_members_link'; jest.mock('actions/telemetry_actions', () => ({ trackEvent: jest.fn(), })); describe('components/preparing-workspace/invite_members_link', () => { const inviteURL = 'https://invite-url.mattermost.com'; it('should match snapshot', () => { const component = withIntl(<InviteMembersLink inviteURL={inviteURL}/>); const {container} = render(component); expect(container).toMatchSnapshot(); }); it('should match snapshot when displayed including the input field', () => { const component = withIntl( <InviteMembersLink inviteURL={inviteURL} inputAndButtonStyle={true} />, ); const {container} = render(component); expect(container).toMatchSnapshot(); }); it('renders only with the button if the inputAndButton option is false', () => { const component = withIntl( <InviteMembersLink inviteURL={inviteURL} inputAndButtonStyle={false} />, ); render(component); const input = screen.queryByText(inviteURL); expect(input).not.toBeInTheDocument(); const button = screen.getByRole('button', {name: /copy link/i}); expect(button).toBeInTheDocument(); }); it('renders an input field with the invite URL', () => { const component = withIntl( <InviteMembersLink inviteURL={inviteURL} inputAndButtonStyle={true} />, ); render(component); const input = screen.getByDisplayValue(inviteURL); expect(input).toBeInTheDocument(); }); it('renders a button to copy the invite URL', () => { const component = withIntl(<InviteMembersLink inviteURL={inviteURL}/>); render(component); const button = screen.getByRole('button', {name: /copy link/i}); expect(button).toBeInTheDocument(); }); it('calls the trackEvent function when the copy button is clicked', () => { const component = withIntl(<InviteMembersLink inviteURL={inviteURL}/>); render(component); const button = screen.getByRole('button', {name: /copy link/i}); fireEvent.click(button); expect(trackEvent).toHaveBeenCalledWith( 'first_admin_setup', 'admin_setup_click_copy_invite_link', ); }); it('changes the button text to "Link Copied" when the URL is copied', () => { const component = withIntl(<InviteMembersLink inviteURL={inviteURL}/>); render(component); const button = screen.getByRole('button', {name: /copy link/i}); const originalText = 'Copy Link'; const linkCopiedText = 'Link Copied'; expect(button).toHaveTextContent(originalText); fireEvent.click(button); expect(button).toHaveTextContent(linkCopiedText); }); });
2,916
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace/organization_status.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {withIntl} from 'tests/helpers/intl-test-helper'; import {render} from 'tests/react_testing_utils'; import {BadUrlReasons} from 'utils/url'; import OrganizationStatus, {TeamApiError} from './organization_status'; describe('components/preparing-workspace/organization_status', () => { const defaultProps = { error: null, }; it('should match snapshot', () => { const {container} = render(<OrganizationStatus {...defaultProps}/>); expect(container.firstChild).toMatchSnapshot(); }); it('should render no error message when error prop is null', () => { const {queryByText, container} = render(<OrganizationStatus {...defaultProps}/>); expect((container.getElementsByClassName('Organization__status').length)).toBe(1); expect(queryByText(/empty/i)).not.toBeInTheDocument(); expect(queryByText(/team api error/i)).not.toBeInTheDocument(); expect(queryByText(/length/i)).not.toBeInTheDocument(); expect(queryByText(/reserved/i)).not.toBeInTheDocument(); }); it('should render an error message for an empty organization name', () => { const component = withIntl(<OrganizationStatus error={BadUrlReasons.Empty}/>); const {getByText} = render(component); expect(getByText(/You must enter an organization name/i)).toBeInTheDocument(); }); it('should render an error message for a team API error', () => { const component = withIntl(<OrganizationStatus error={TeamApiError}/>); const {getByText} = render(component); expect(getByText(/There was an error, please try again/i)).toBeInTheDocument(); }); it('should render an error message for an organization name with invalid length', () => { const component = withIntl(<OrganizationStatus error={BadUrlReasons.Length}/>); const {getByText} = render(component); expect(getByText(/Organization name must be between 2 and 64 characters/i)).toBeInTheDocument(); }); });
2,933
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace/__snapshots__/invite_members.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`InviteMembers component should match snapshot 1`] = ` <div> <div class="InviteMembers-body test-class" > <div class="SingleColumnLayout" style="width: 547px;" > <div> <div class="PageLine PageLine--no-left" style="margin-bottom: 50px; margin-left: 50px; height: calc(25vh);" /> <div> Previous step </div> <h1 class="PreparingWorkspaceTitle" > <span> Invite your team members </span> </h1> <p class="PreparingWorkspaceDescription" > <span> Collaboration is tough by yourself. Invite a few team members using the invitation link below. </span> </p> <div class="PreparingWorkspacePageBody" > <div class="InviteMembersLink" > <input aria-label="team invite link" class="InviteMembersLink__input" data-testid="shareLinkInput" readonly="" type="text" value="https://my-org.mattermost.com/config/signup_user_complete/?id=1234" /> <button class="InviteMembersLink__button" data-testid="shareLinkInputButton" > <i class="icon icon-link-variant" /> <span> Copy Link </span> </button> </div> </div> <div class="InviteMembers__submit" > <button class="primary-button" > <span> Finish setup </span> </button> </div> <div class="PageLine PageLine--no-left" style="margin-top: 50px; margin-left: 50px; height: calc(35vh);" /> </div> </div> </div> </div> `; exports[`InviteMembers component should match snapshot when it is cloud 1`] = ` <div> <div class="InviteMembers-body test-class" > <div class="SingleColumnLayout" style="width: 547px;" > <div> <div class="PageLine PageLine--no-left" style="margin-bottom: 50px; margin-left: 50px; height: calc(25vh);" /> <div> Previous step </div> <h1 class="PreparingWorkspaceTitle" > <span> Who works with you? </span> </h1> <p class="PreparingWorkspaceDescription" > <span> Collaboration is tough by yourself. Invite a few team members. Separate each email address with a space or comma. </span> </p> <div class="PreparingWorkspacePageBody" > <div class="UsersEmailsInput empty no-selections css-2b097c-container" > <span aria-live="assertive" class="css-1laao21-a11yText" > <p id="aria-selection-event" >   </p> <p id="aria-context" >   0 results available. Use Up and Down to choose options, press Enter to select the currently focused option, press Escape to exit the menu, press Tab to select the option and exit the menu. </p> </span> <div class="users-emails-input__control users-emails-input__control--is-focused users-emails-input__control--menu-is-open css-1pahdxg-control" > <div class="users-emails-input__value-container users-emails-input__value-container--is-multi css-1hwfws3" > <div class="users-emails-input__placeholder css-1lxtzh0-placeholder" > Enter email addresses </div> <div class="css-gftnqw-Input" > <div class="users-emails-input__input" style="display: inline-block;" > <input aria-autocomplete="list" aria-label="Invite People" 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> <div class="users-emails-input__menu css-26l3qy-menu" > <div class="users-emails-input__menu-list users-emails-input__menu-list--is-multi css-4ljt47-MenuList" /> </div> </div> </div> <div class="InviteMembers__submit" > <button class="primary-button" disabled="" > <span> Send invites </span> </button> <div class="InviteMembersLink" > <button class="InviteMembersLink__button--single" data-testid="shareLinkInputButton" > <i class="icon icon-content-copy" /> <span> Copy Link </span> </button> </div> </div> <div class="PageLine PageLine--no-left" style="margin-top: 50px; margin-left: 50px; height: calc(35vh);" /> </div> </div> </div> </div> `;
2,934
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace/__snapshots__/invite_members_link.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/preparing-workspace/invite_members_link should match snapshot 1`] = ` <div> <div class="InviteMembersLink" > <button class="InviteMembersLink__button--single" data-testid="shareLinkInputButton" > <i class="icon icon-content-copy" /> <span> Copy Link </span> </button> </div> </div> `; exports[`components/preparing-workspace/invite_members_link should match snapshot when displayed including the input field 1`] = ` <div> <div class="InviteMembersLink" > <input aria-label="team invite link" class="InviteMembersLink__input" data-testid="shareLinkInput" readonly="" type="text" value="https://invite-url.mattermost.com" /> <button class="InviteMembersLink__button" data-testid="shareLinkInputButton" > <i class="icon icon-link-variant" /> <span> Copy Link </span> </button> </div> </div> `;
2,935
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace
petrpan-code/mattermost/mattermost/webapp/channels/src/components/preparing_workspace/__snapshots__/organization_status.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/preparing-workspace/organization_status should match snapshot 1`] = ` <div class="Organization__status" /> `;
2,949
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/product_notices_modal/product_notices.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 {GenericModal} from '@mattermost/components'; import {isDesktopApp, getDesktopVersion} from 'utils/user_agent'; import ProductNoticesModal from './product_notices_modal'; jest.mock('utils/user_agent'); describe('ProductNoticesModal', () => { const noticesData = [{ id: '124', title: 'for sysadmin', description: 'your eyes only! [test](https://test.com)', image: 'https://raw.githubusercontent.com/reflog/notices-experiment/master/images/2020-08-11_11-42.png', actionText: 'Download', actionParam: 'http://download.com/path', sysAdminOnly: true, teamAdminOnly: false, }, { id: '123', title: 'title', description: 'descr', actionText: 'Download', actionParam: 'http://download.com/path', sysAdminOnly: false, teamAdminOnly: false, }]; const baseProps = { version: '5.28.0', currentTeamId: 'currentTeamId', socketStatus: { connected: true, connectionId: '', lastConnectAt: 1599760193593, lastDisconnectAt: 0, }, actions: { getInProductNotices: jest.fn().mockResolvedValue({data: noticesData}), updateNoticesAsViewed: jest.fn().mockResolvedValue({}), }, }; test('Should match snapshot when there are no notices', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('Should match snapshot for system admin notice', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); expect(wrapper).toMatchSnapshot(); }); test('Match snapshot for user notice', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); wrapper.setState({presentNoticeIndex: 1}); expect(wrapper).toMatchSnapshot(); }); test('Match snapshot for single notice', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); wrapper.setState({noticesData: [noticesData[1]]}); expect(wrapper).toMatchSnapshot(); }); test('Should change the state of presentNoticeIndex on click of next, previous button', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); expect(wrapper.state('presentNoticeIndex')).toBe(0); wrapper.find(GenericModal).prop('handleConfirm')?.(); expect(wrapper.state('presentNoticeIndex')).toBe(1); wrapper.find(GenericModal).prop('handleCancel')?.(); expect(wrapper.state('presentNoticeIndex')).toBe(0); }); test('Should not have previous button if there is only one notice', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); expect(wrapper.find(GenericModal).props().handleCancel).toEqual(undefined); }); test('Should not have previous button if there is only one notice', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(baseProps.currentTeamId, 'web', baseProps.version); expect(wrapper.find(GenericModal).props().handleCancel).toEqual(undefined); }); test('Should open url in a new window on click of handleConfirm for single notice', async () => { window.open = jest.fn(); const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); wrapper.setState({noticesData: [noticesData[1]]}); wrapper.find(GenericModal).prop('handleConfirm')?.(); expect(window.open).toHaveBeenCalledWith(noticesData[1].actionParam, '_blank'); }); test('Should call for getInProductNotices and updateNoticesAsViewed on mount', async () => { shallow(<ProductNoticesModal {...baseProps}/>); expect(baseProps.actions.getInProductNotices).toHaveBeenCalledWith(baseProps.currentTeamId, 'web', baseProps.version); await baseProps.actions.getInProductNotices(); expect(baseProps.actions.updateNoticesAsViewed).toHaveBeenCalledWith([noticesData[0].id]); }); test('Should call for updateNoticesAsViewed on click of next button', async () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); wrapper.find(GenericModal).prop('handleConfirm')?.(); expect(baseProps.actions.updateNoticesAsViewed).toHaveBeenCalledWith([noticesData[1].id]); }); test('Should clear state on onExited with a timer', async () => { jest.useFakeTimers(); const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); await baseProps.actions.getInProductNotices(); wrapper.find(GenericModal).prop('onExited')?.(); jest.runOnlyPendingTimers(); expect(wrapper.state('noticesData')).toEqual([]); expect(wrapper.state('presentNoticeIndex')).toEqual(0); }); test('Should call for getInProductNotices if socket reconnects for the first time in a day', () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); Date.now = jest.fn().mockReturnValue(1599807605628); wrapper.setProps({ socketStatus: { ...baseProps.socketStatus, connected: false, }, }); wrapper.setProps({ socketStatus: { ...baseProps.socketStatus, connected: true, }, }); expect(baseProps.actions.getInProductNotices).toHaveBeenCalledWith(baseProps.currentTeamId, 'web', baseProps.version); expect(baseProps.actions.getInProductNotices).toHaveBeenCalledTimes(2); }); test('Should call for getInProductNotices with desktop as client if isDesktopApp returns true', () => { (getDesktopVersion as any).mockReturnValue('4.5.0'); (isDesktopApp as any).mockReturnValue(true); shallow(<ProductNoticesModal {...baseProps}/>); expect(baseProps.actions.getInProductNotices).toHaveBeenCalledWith(baseProps.currentTeamId, 'desktop', '4.5.0'); }); test('Should not call for getInProductNotices if socket reconnects on the same day', () => { const wrapper = shallow(<ProductNoticesModal {...baseProps}/>); Date.now = jest.fn().mockReturnValue(1599760196593); wrapper.setProps({ socketStatus: { ...baseProps.socketStatus, connected: false, }, }); wrapper.setProps({ socketStatus: { ...baseProps.socketStatus, connected: true, }, }); expect(baseProps.actions.getInProductNotices).toHaveBeenCalledTimes(1); }); });
2,952
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/product_notices_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/product_notices_modal/__snapshots__/product_notices.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ProductNoticesModal Match snapshot for single notice 1`] = ` <GenericModal autoCloseOnCancelButton={false} autoCloseOnConfirmButton={true} bodyPadding={true} cancelButtonText={null} className="productNotices" confirmButtonText={ <span> Download </span> } enforceFocus={true} handleConfirm={[Function]} handleEnterKeyPress={[Function]} id="genericModal" keyboardEscape={true} modalHeaderText={ <span> title </span> } onExited={[Function]} show={true} > <span className="productNotices__helpText" > <Connect(Markdown) message="descr" /> </span> <div className="productNotices__imageDiv" /> <div className="productNotices__info" /> </GenericModal> `; exports[`ProductNoticesModal Match snapshot for user notice 1`] = ` <GenericModal autoCloseOnCancelButton={false} autoCloseOnConfirmButton={true} bodyPadding={true} cancelButtonText={ <React.Fragment> <Memo(PreviousIcon) /> <Memo(MemoizedFormattedMessage) defaultMessage="Previous" id="generic.previous" /> </React.Fragment> } className="productNotices" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Done" id="generic.done" /> } enforceFocus={true} handleCancel={[Function]} handleConfirm={[Function]} handleEnterKeyPress={[Function]} id="genericModal" keyboardEscape={true} modalHeaderText={ <span> title </span> } onExited={[Function]} show={true} > <span className="productNotices__helpText" > <Connect(Markdown) message="descr" /> </span> <ExternalLink className="GenericModal__button actionButton" href="http://download.com/path" id="actionButton" location="product_notices_modal" onClick={[Function]} > Download </ExternalLink> <div className="productNotices__imageDiv" /> <div className="productNotices__info" > <span className="tutorial__circles" > <span className="circle" data-screen={0} id="tutorialIntroCircle0" key="circle0" /> <span className="circle active" data-screen={1} id="tutorialIntroCircle1" key="circle1" /> </span> </div> </GenericModal> `; exports[`ProductNoticesModal Should match snapshot for system admin notice 1`] = ` <GenericModal autoCloseOnCancelButton={false} autoCloseOnConfirmButton={false} bodyPadding={true} cancelButtonText={null} className="productNotices" confirmButtonText={ <React.Fragment> <Memo(MemoizedFormattedMessage) defaultMessage="Next" id="generic.next" /> <Memo(NextIcon) /> </React.Fragment> } enforceFocus={true} handleConfirm={[Function]} handleEnterKeyPress={[Function]} id="genericModal" keyboardEscape={true} modalHeaderText={ <span> for sysadmin </span> } onExited={[Function]} show={true} > <span className="productNotices__helpText" > <Connect(Markdown) message="your eyes only! [test](https://test.com)" /> </span> <ExternalLink className="GenericModal__button actionButton" href="http://download.com/path" id="actionButton" location="product_notices_modal" onClick={[Function]} > Download </ExternalLink> <div className="productNotices__imageDiv" > <img className="productNotices__img" src="https://raw.githubusercontent.com/reflog/notices-experiment/master/images/2020-08-11_11-42.png" /> </div> <div className="productNotices__info" > <span className="tutorial__circles" > <span className="circle active" data-screen={0} id="tutorialIntroCircle0" key="circle0" /> <span className="circle" data-screen={1} id="tutorialIntroCircle1" key="circle1" /> </span> <AdminEyeIcon /> <MemoizedFormattedMessage defaultMessage="Visible to Admins only" id="inProduct_notices.adminOnlyMessage" /> </div> </GenericModal> `; exports[`ProductNoticesModal Should match snapshot when there are no notices 1`] = `""`;
2,955
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/profile_picture/profile_picture.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 ProfilePicture from 'components/profile_picture'; type Props = ComponentProps<typeof ProfilePicture>; describe('components/ProfilePicture', () => { const baseProps: Props = { src: 'http://example.com/image.png', status: 'away', isBusy: true, }; test('should match snapshot, no user specified, default props', () => { const props: Props = baseProps; const wrapper = shallow( <ProfilePicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, profile and src, default props', () => { const props: Props = { ...baseProps, profileSrc: baseProps.src, userId: 'uid', src: 'http://example.com/emoji.png', }; const wrapper = shallow( <ProfilePicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, no user specified, overridden props', () => { const props: Props = { ...baseProps, size: 'xl', hasMention: true, }; const wrapper = shallow( <ProfilePicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, user specified', () => { const props: Props = { ...baseProps, username: 'username', }; const wrapper = shallow( <ProfilePicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, user specified, overridden props', () => { const props: Props = { ...baseProps, username: 'username', size: 'xs', hasMention: true, }; const wrapper = shallow( <ProfilePicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
2,957
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/profile_picture
petrpan-code/mattermost/mattermost/webapp/channels/src/components/profile_picture/__snapshots__/profile_picture.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ProfilePicture should match snapshot, no user specified, default props 1`] = ` <span className="status-wrapper style--none " > <span className="profile-icon " > <Memo(Avatar) size="md" url="http://example.com/image.png" /> </span> <StatusIcon button={false} className="" status="away" /> </span> `; exports[`components/ProfilePicture should match snapshot, no user specified, overridden props 1`] = ` <span className="status-wrapper style--none " > <span className="profile-icon " > <Memo(Avatar) size="xl" url="http://example.com/image.png" /> </span> <StatusIcon button={false} className="" status="away" /> </span> `; exports[`components/ProfilePicture should match snapshot, profile and src, default props 1`] = ` <OverlayTrigger defaultOverlayShown={false} overlay={ <Memo(Connect(injectIntl(ProfilePopover))) className="user-profile-popover" hasMention={false} hide={[Function]} isBusy={true} src="http://example.com/image.png" userId="uid" /> } placement="right" rootClose={true} trigger={ Array [ "click", ] } > <span className="status-wrapper " > <RoundButton className="style--none" size="md" > <span className="profile-icon " > <Memo(Avatar) size="md" tabIndex={-1} url="http://example.com/emoji.png" /> </span> </RoundButton> <StatusIcon button={false} className="" status="away" /> </span> </OverlayTrigger> `; exports[`components/ProfilePicture should match snapshot, user specified 1`] = ` <span className="status-wrapper style--none " > <span className="profile-icon " > <Memo(Avatar) size="md" url="http://example.com/image.png" /> </span> <StatusIcon button={false} className="" status="away" /> </span> `; exports[`components/ProfilePicture should match snapshot, user specified, overridden props 1`] = ` <span className="status-wrapper style--none " > <span className="profile-icon " > <Memo(Avatar) size="xs" url="http://example.com/image.png" /> </span> <StatusIcon button={false} className="" status="away" /> </span> `;
2,961
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/profile_popover/profile_popover.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Provider} from 'react-redux'; import {CustomStatusDuration} from '@mattermost/types/users'; import {General} from 'mattermost-redux/constants'; import {checkUserInCall} from 'components/profile_popover'; import ProfilePopover from 'components/profile_popover/profile_popover'; import Pluggable from 'plugins/pluggable'; import {mountWithIntl, shallowWithIntl} from 'tests/helpers/intl-test-helper'; import {mockStore} from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; describe('components/ProfilePopover', () => { const baseProps = { userId: '0', user: TestHelper.getUserMock({ username: 'some_username', }), hide: jest.fn(), src: 'src', currentUserId: '', currentTeamId: 'team_id', isChannelAdmin: false, isTeamAdmin: false, isInCurrentTeam: true, teamUrl: '', canManageAnyChannelMembersInCurrentTeam: true, isCustomStatusEnabled: true, isCustomStatusExpired: false, isMobileView: false, actions: { getMembershipForEntities: jest.fn(), openDirectChannelToUserId: jest.fn(), openModal: jest.fn(), closeModal: jest.fn(), loadBot: jest.fn(), }, lastActivityTimestamp: 1632146562846, enableLastActiveTime: true, timestampUnits: [ 'now', 'minute', 'hour', ], isCallsEnabled: true, isCallsDefaultEnabledOnAllChannels: true, teammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, isAnyModalOpen: false, }; const initialState = { entities: { teams: {}, channels: { channels: {}, myMembers: {}, }, general: { config: {}, }, users: { currentUserId: '', profiles: { user1: { id: 'user1', roles: '', }, }, }, preferences: { myPreferences: {}, }, groups: { groups: {}, myGroups: [], }, emojis: { customEmoji: {}, }, }, plugins: { components: { CallButton: [], }, }, views: { rhs: { isSidebarOpen: false, }, }, }; test('should match snapshot', () => { const props = {...baseProps}; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for shared user', () => { const props = { ...baseProps, user: TestHelper.getUserMock({ username: 'shared_user', first_name: 'shared', remote_id: 'fakeuser', }), }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have bot description', () => { const props = { ...baseProps, user: TestHelper.getUserMock({ is_bot: true, bot_description: 'bot description', }), }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper.containsMatchingElement( <div key='bot-description' > {'bot description'} </div>, )).toEqual(true); }); test('should hide add-to-channel option if not on team', () => { const props = {...baseProps}; props.isInCurrentTeam = false; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match props passed into Pluggable component', () => { const hide = jest.fn(); const status = 'online'; const props = {...baseProps, hide, status}; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); const pluggableProps = { hide, status, user: props.user, }; expect(wrapper.find(Pluggable).first().props()).toEqual({...pluggableProps, pluggableName: 'PopoverUserAttributes'}); expect(wrapper.find(Pluggable).last().props()).toEqual({...pluggableProps, pluggableName: 'PopoverUserActions'}); }); test('should match snapshot with custom status', () => { const customStatus = { emoji: 'calendar', text: 'In a meeting', duration: CustomStatusDuration.TODAY, expires_at: '2021-05-03T23:59:59.000Z', }; const props = { ...baseProps, customStatus, }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with custom status not set but can set', () => { const props = { ...baseProps, user: { ...baseProps.user, id: '', }, }; const wrapper = shallowWithIntl( <ProfilePopover {...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, isCustomStatusExpired: true, customStatus, }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with last active display', () => { const props = { ...baseProps, status: 'offline', }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with no last active display because it is disabled', () => { const props = { ...baseProps, enableLastActiveTime: false, }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when calls are disabled', () => { const props = { ...baseProps, isCallsEnabled: false, }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should disable start call button when user is in another call', () => { const props = { ...baseProps, isUserInCall: true, }; const wrapper = shallowWithIntl( <ProfilePopover {...props}/>, ); expect(wrapper.find('#startCallButton').hasClass('icon-btn-disabled')).toBe(true); expect(wrapper).toMatchSnapshot(); }); test('should show the start call button when isCallsDefaultEnabledOnAllChannels, isCallsCanBeDisabledOnSpecificChannels is false and callsChannelState.enabled is true', () => { const mock = mockStore(initialState); const props = { ...baseProps, isCallsDefaultEnabledOnAllChannels: false, isCallsCanBeDisabledOnSpecificChannels: false, }; const wrapper = mountWithIntl( <Provider store={mock.store}> <ProfilePopover {...props}/> </Provider>, ); expect(wrapper.find('ProfilePopoverCallButton').exists()).toBe(true); expect(wrapper).toMatchSnapshot(); }); }); describe('checkUserInCall', () => { test('missing state', () => { expect(checkUserInCall({ 'plugins-com.mattermost.calls': {}, } as any, 'userA')).toBe(false); }); test('call state missing', () => { expect(checkUserInCall({ 'plugins-com.mattermost.calls': { profiles: { channelID: null, }, }, } as any, 'userA')).toBe(false); }); test('user not in call', () => { expect(checkUserInCall({ 'plugins-com.mattermost.calls': { profiles: { channelID: { sessionB: { id: 'userB', }, }, }, }, } as any, 'userA')).toBe(false); }); test('user in call', () => { expect(checkUserInCall({ 'plugins-com.mattermost.calls': { profiles: { channelID: { sessionB: { id: 'userB', }, sessionA: { id: 'userA', }, }, }, }, } as any, 'userA')).toBe(true); }); });
2,963
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/profile_popover
petrpan-code/mattermost/mattermost/webapp/channels/src/components/profile_popover/__snapshots__/profile_popover.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ProfilePopover should disable start call button when user is in another call 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} isUserInCall={true} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > some_username is in another call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-disabled={true} className="btn icon-btn icon-btn-disabled" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="some_username is in another call" size={18} /> </button> </OverlayTrigger> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should hide add-to-channel option if not on team 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={false} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot for shared user 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for shared_user" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_shared_user" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="shared_user" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1" data-testid="popover-fullname-shared_user" key="user-popover-fullname" > <span className="user-profile-popover__heading" > shared </span> <SharedUserIndicator className="shared-user-icon" withTooltip={true} /> </div> <div className="overflow--ellipsis pb-1" id="userPopoverUsername" key="user-popover-username" > @shared_user </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "shared", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "remote_id": "fakeuser", "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "shared_user", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "shared", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "remote_id": "fakeuser", "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "shared_user", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "shared", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "remote_id": "fakeuser", "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "shared_user", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot when calls are disabled 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={false} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot with custom status 1`] = ` <Popover customStatus={ Object { "duration": "today", "emoji": "calendar", "expires_at": "2021-05-03T23:59:59.000Z", "text": "In a meeting", } } enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="user-popover__time-status-container" id="user-popover-status" key="user-popover-status" > <span className="user-popover__subtitle" > <MemoizedFormattedMessage defaultMessage="Status" id="user_profile.custom_status" /> <Memo(ExpiryTime) className="ml-1" time="2021-05-03T23:59:59.000Z" withinBrackets={true} /> </span> <div className="d-flex align-items-center" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "marginRight": 4, "marginTop": 1, } } showTooltip={false} userID="user_id" /> <CustomStatusText className="user-popover__email" text="In a meeting" tooltipDirection="top" /> </div> </div> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot with custom status expired 1`] = ` <Popover customStatus={ Object { "duration": "today", "emoji": "calendar", "expires_at": "2021-05-03T23:59:59.000Z", "text": "In a meeting", } } enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={true} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot with custom status not set but can set 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="user-popover__time-status-container" id="user-popover-status" key="user-popover-status" > <span className="user-popover__subtitle" > <MemoizedFormattedMessage defaultMessage="Status" id="user_profile.custom_status" /> </span> <button className="user-popover__set-custom-status-btn" onClick={[Function]} > <EmoticonHappyOutlineIcon size={14} /> <MemoizedFormattedMessage defaultMessage="Set a status" id="user_profile.custom_status.set_status" /> </button> </div> <div className="popover__row first" data-toggle="tooltip" key="user-popover-settings" > <button className="btn" id="editProfileButton" onClick={[Function]} type="button" > <AccountOutlineIcon aria-label="Edit Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Edit Profile" id="user_profile.account.editProfile" /> </button> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="sendMessageTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Send yourself a message" id="user_profile.send.dm.yourself" /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={18} /> </button> </OverlayTrigger> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot with last active display 1`] = ` <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <MemoizedFormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should match snapshot with no last active display because it is disabled 1`] = ` <Popover customStatus={null} enableLastActiveTime={false} id="user-profile-popover" isAnyModalOpen={false} isCallsDefaultEnabledOnAllChannels={true} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <span onFocus={[Function]} tabIndex={0} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} /> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" /> <StatusIcon button={true} className="status user-popover-status" status="offline" /> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} /> <MemoizedFormattedMessage defaultMessage="Message" id="user_profile.send.dm" /> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div> <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} /> </ToggleModalButton> </div> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" /> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </Popover> `; exports[`components/ProfilePopover should show the start call button when isCallsDefaultEnabledOnAllChannels, isCallsCanBeDisabledOnSpecificChannels is false and callsChannelState.enabled is true 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <injectIntl(ProfilePopover) actions={ Object { "closeModal": [MockFunction], "getMembershipForEntities": [MockFunction] { "calls": Array [ Array [ "team_id", "0", undefined, ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, "loadBot": [MockFunction], "openDirectChannelToUserId": [MockFunction], "openModal": [MockFunction], } } canManageAnyChannelMembersInCurrentTeam={true} currentTeamId="team_id" currentUserId="" enableLastActiveTime={true} hide={[MockFunction]} isAnyModalOpen={false} isCallsCanBeDisabledOnSpecificChannels={false} isCallsDefaultEnabledOnAllChannels={false} isCallsEnabled={true} isChannelAdmin={false} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} isTeamAdmin={false} lastActivityTimestamp={1632146562846} src="src" teamUrl="" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } userId="0" > <ProfilePopover actions={ Object { "closeModal": [MockFunction], "getMembershipForEntities": [MockFunction] { "calls": Array [ Array [ "team_id", "0", undefined, ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, "loadBot": [MockFunction], "openDirectChannelToUserId": [MockFunction], "openModal": [MockFunction], } } canManageAnyChannelMembersInCurrentTeam={true} currentTeamId="team_id" currentUserId="" customStatus={null} enableLastActiveTime={true} hasMention={false} hide={[MockFunction]} 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, } } isAnyModalOpen={false} isCallsCanBeDisabledOnSpecificChannels={false} isCallsDefaultEnabledOnAllChannels={false} isCallsEnabled={true} isChannelAdmin={false} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} isTeamAdmin={false} lastActivityTimestamp={1632146562846} src="src" status="offline" teamUrl="" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } userId="0" > <Popover customStatus={null} enableLastActiveTime={true} id="user-profile-popover" isAnyModalOpen={false} isCallsCanBeDisabledOnSpecificChannels={false} isCallsDefaultEnabledOnAllChannels={false} isCallsEnabled={true} isCustomStatusEnabled={true} isCustomStatusExpired={false} isInCurrentTeam={true} isMobileView={false} lastActivityTimestamp={1632146562846} placement="right" popoverSize="sm" popoverStyle="info" teammateNameDisplay="username" timestampUnits={ Array [ "now", "minute", "hour", ] } > <Popover bsClass="popover" bsSize="small" bsStyle="info" id="user-profile-popover" placement="right" > <div className="popover popover-sm popover-info right" id="user-profile-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} /> <div aria-label="Profile for some_username" aria-modal={true} className="a11y__popup" onKeyDown={[Function]} role="dialog" > <div className="popover-title popover-title_height" > <span data-testid="profilePopoverTitle_some_username" > <button className="user-popover__close" onClick={[Function]} > <CloseIcon size={18} > <svg fill="currentColor" height={18} version="1.1" viewBox="0 0 24 24" width={18} xmlns="http://www.w3.org/2000/svg" > <path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" /> </svg> </CloseIcon> </button> </span> </div> <div className="user-profile-popover__content" > <div className="user-popover-image" key="user-popover-image" > <Memo(Avatar) id="userAvatar" size="xxl" tabIndex={-1} url="src" username="some_username" > <img alt="some_username profile image" className="Avatar Avatar-xxl" id="userAvatar" loading="lazy" onError={[Function]} src="src" tabIndex={-1} /> </Memo(Avatar)> <StatusIcon button={true} className="status user-popover-status" status="offline" > <StatusOfflineIcon className="status user-popover-status" > <span className="status user-popover-status" > <svg aria-label="Offline Icon" className="offline--icon" height="100%" role="img" style={ Object { "clipRule": "evenodd", "fillRule": "evenodd", "strokeLinejoin": "round", "strokeMiterlimit": 1.41421, } } viewBox="0 0 20 20" width="100%" > <path d="M10,0c5.519,0 10,4.481 10,10c0,5.519 -4.481,10 -10,10c-5.519,0 -10,-4.481 -10,-10c0,-5.519 4.481,-10 10,-10Zm0,2c4.415,0 8,3.585 8,8c0,4.415 -3.585,8 -8,8c-4.415,0 -8,-3.585 -8,-8c0,-4.415 3.585,-8 8,-8Z" /> </svg> </span> </StatusOfflineIcon> </StatusIcon> </div> <div className="user-popover-last-active" key="user-popover-last-active" > <FormattedMessage defaultMessage="Last online {timestamp}" id="channel_header.lastOnline" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } > <span> Last online <Connect(injectIntl(Timestamp)) key=".$.1" style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} > <injectIntl(Timestamp) dispatch={[Function]} hourCycle="h12" style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} > <Timestamp day="2-digit" 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="short" timeZoneName="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} weekday="long" year="numeric" > <Memo(SemanticTime) value={2021-09-20T14:02:42.846Z} > <time dateTime="2021-09-20T14:02:42.846" > September 20, 2021 </time> </Memo(SemanticTime)> </Timestamp> </injectIntl(Timestamp)> </Connect(injectIntl(Timestamp))> </span> </FormattedMessage> </div> <div className="overflow--ellipsis pb-1 user-profile-popover__heading" id="userPopoverUsername" key="user-popover-username" > @some_username </div> <hr className="divider divider--expanded" key="user-popover-hr" /> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable2" pluggableName="PopoverUserAttributes" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } > <Pluggable components={ Object { "CallButton": Array [], } } dispatch={[Function]} hide={[MockFunction]} pluggableName="PopoverUserAttributes" status="offline" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </Connect(Pluggable)> <div className="popover__row first" data-toggle="tooltip" key="user-popover-dm" > <button className="btn" id="messageButton" onClick={[Function]} type="button" > <SendIcon aria-label="Send Message Icon" size={16} > <svg aria-label="Send Message Icon" fill="currentColor" height={16} version="1.1" viewBox="0 0 24 24" width={16} xmlns="http://www.w3.org/2000/svg" > <path d="M2,21L23,12L2,3V10L17,12L2,14V21Z" /> </svg> </SendIcon> <FormattedMessage defaultMessage="Message" id="user_profile.send.dm" > <span> Message </span> </FormattedMessage> </button> <div className="popover_row-controlContainer" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="addToChannelTooltip" > Add to a Channel </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper id="addToChannelTooltip" 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, } } > Add to a Channel </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <div onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <ToggleModalButton ariaLabel="Add to a Channel" className="btn icon-btn" dialogProps={ Object { "onExited": [Function], "user": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addToChannelButton" modalId="add_user_to_channel" onClick={[Function]} > <button aria-label="Add to a Channel dialog" className="style--none btn icon-btn" id="addToChannelButton" onClick={[Function]} > <AccountPlusOutlineIcon aria-label="Add User to Channel Icon" size={18} > <svg aria-label="Add User to Channel Icon" fill="currentColor" height={18} version="1.1" viewBox="0 0 24 24" width={18} xmlns="http://www.w3.org/2000/svg" > <path d="M5.033,19C4.463,19,4,18.528,4,17.945c0-0.105,0.015-0.208,0.044-0.306c0.058-0.195,0.171-0.37,0.324-0.501c0.076-0.066,0.163-0.121,0.258-0.162l3.093-1.857C8.387,15.52,9.151,15.75,10,15.75s1.613-0.23,2.28-0.631l0.352,0.211 c0.302-0.606,0.701-1.156,1.181-1.624l-0.006-0.004c1.045-1.391,1.622-3.311,1.622-5.203C15.429,5.21,13.247,3,10,3 S4.571,5.21,4.571,8.5c0,1.891,0.577,3.812,1.622,5.203l-2.515,1.51C2.653,15.727,2,16.783,2,17.945C2,19.63,3.361,21,5.033,21 h7.776c-0.352-0.608-0.599-1.282-0.719-2H5.033z M10,5c1.894,0,3.429,1.084,3.429,3.5c0,1.482-0.485,3.117-1.353,4.163 c-0.548,0.66-1.247,1.087-2.076,1.087c-0.268,0-0.522-0.044-0.763-0.126c-0.12-0.041-0.237-0.092-0.35-0.151 c-0.226-0.119-0.437-0.272-0.633-0.453c-0.116-0.108-0.225-0.229-0.331-0.356c-0.072-0.086-0.143-0.174-0.209-0.268 C7.55,12.164,7.403,11.91,7.272,11.64c-0.194-0.406-0.351-0.846-0.466-1.3C6.729,10.037,6.67,9.728,6.631,9.419 c-0.04-0.308-0.06-0.617-0.06-0.919C6.571,6.084,8.106,5,10,5z M17,14h2v3h3v2h-3v3h-2v-3h-3v-2h3V14" /> </svg> </AccountPlusOutlineIcon> </button> </ToggleModalButton> </div> </OverlayTrigger> </OverlayTrigger> <Connect(ProfilePopoverCallButton) customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } userId="0" > <ProfilePopoverCallButton currentUserId="" customButton={ <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="startCallTooltip" > Start Call </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button className="btn icon-btn" id="startCallButton" type="button" > <PhoneInTalkIcon aria-label="Start Call" size={18} /> </button> </OverlayTrigger> } dispatch={[Function]} pluginCallComponents={Array []} sidebarOpen={false} userId="0" /> </Connect(ProfilePopoverCallButton)> </div> </div> <Connect(Pluggable) hide={[MockFunction]} key="profilePopoverPluggable3" pluggableName="PopoverUserActions" status="offline" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } > <Pluggable components={ Object { "CallButton": Array [], } } dispatch={[Function]} hide={[MockFunction]} pluggableName="PopoverUserActions" status="offline" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some_username", } } /> </Connect(Pluggable)> </div> </div> <span onFocus={[Function]} tabIndex={0} /> </div> </div> </Popover> </Popover> </ProfilePopover> </injectIntl(ProfilePopover)> </Provider> `;
2,967
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/purchase_in_progress_modal/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {DeepPartial} from '@mattermost/types/utilities'; import {Client4} from 'mattermost-redux/client'; import {STORAGE_KEY_PURCHASE_IN_PROGRESS} from 'components/self_hosted_purchases/constants'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {TestHelper as TH} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import PurchaseInProgressModal from './'; jest.mock('mattermost-redux/client', () => { const original = jest.requireActual('mattermost-redux/client'); return { __esModule: true, ...original, Client4: { ...original, bootstrapSelfHostedSignup: jest.fn(), }, }; }); const initialState: DeepPartial<GlobalState> = { entities: { preferences: { myPreferences: { theme: {}, }, }, users: { currentUserId: 'adminUserId', profiles: { adminUserId: TH.getUserMock({ id: 'adminUserId', username: 'UserAdmin', roles: 'admin', email: '[email protected]', }), otherUserId: TH.getUserMock({ id: 'otherUserId', username: 'UserOther', roles: '', email: '[email protected]', }), }, }, }, }; describe('PurchaseInProgressModal', () => { it('when purchaser and user emails are different, user is instructed to wait', () => { const stateOverride: DeepPartial<GlobalState> = JSON.parse(JSON.stringify(initialState)); stateOverride.entities!.users!.currentUserId = 'otherUserId'; renderWithContext( <div id='root-portal'> <PurchaseInProgressModal purchaserEmail={'[email protected]'} storageKey={STORAGE_KEY_PURCHASE_IN_PROGRESS} /> </div>, stateOverride, ); screen.getByText('@UserAdmin is currently attempting to purchase a paid license.'); }); it('when purchaser and user emails are same, allows user to reset purchase flow', () => { renderWithContext( <div id='root-portal'> <PurchaseInProgressModal purchaserEmail={'[email protected]'} storageKey={STORAGE_KEY_PURCHASE_IN_PROGRESS} /> </div>, initialState, ); expect(Client4.bootstrapSelfHostedSignup).not.toHaveBeenCalled(); screen.getByText('Reset purchase flow').click(); expect(Client4.bootstrapSelfHostedSignup).toHaveBeenCalled(); }); });
2,977
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_input/max_length_input.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 {MaxLengthInput} from 'components/quick_input/index'; describe('components/MaxLengthInput', () => { const requiredProps = { className: 'input', maxLength: 20, }; test.each([ [undefined], ['less than 20'], ['Where is Jessica Hyde?'], ])('should match snapshot', (defaultValue) => { const wrapper = shallow( <MaxLengthInput {...requiredProps} defaultValue={defaultValue} />, ); expect(wrapper).toMatchSnapshot(); }); test.each([ [undefined, false, false], ['less than 20', false, false], ['Where is Jessica Hyde?', true, true], ])('defaultValue: %s .has-error: %s, .MaxLengthInput__validation: %s', (defaultValue, hasError, maxLengthExists) => { const wrapper = shallow( <MaxLengthInput {...requiredProps} defaultValue={defaultValue} />, ); expect(wrapper.find('input').hasClass('has-error')).toBe(hasError); expect(wrapper.exists('.MaxLengthInput__validation')).toBe(maxLengthExists); }); test('should display the number of times value length exceeds maxLength', () => { const props = { defaultValue: 'Where is Jessica Hyde?', ...requiredProps, }; const wrapper = shallow( <MaxLengthInput {...props}/>, ); expect(wrapper.find('.MaxLengthInput__validation').text()).toBe('-2'); }); });
2,979
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_input/quick_input.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 {QuickInput} from './quick_input'; describe('components/QuickInput', () => { test.each([ ['in default state', {}], ['when not clearable', {value: 'value', clearable: false, onClear: () => {}}], ['when no onClear callback', {value: 'value', clearable: true}], ['when value undefined', {clearable: true, onClear: () => {}}], ['when value empty', {value: '', clearable: true, onClear: () => {}}], ])('should not render clear button', (description, props) => { const wrapper = mount( <QuickInput {...props}/>, ); expect(wrapper.find('.input-clear').exists()).toBe(false); }); describe('should render clear button', () => { test('with default tooltip text', () => { const wrapper = mount( <QuickInput value='mock' clearable={true} onClear={() => {}} />, ); expect(wrapper.find('.input-clear')).toMatchSnapshot(); }); test('with customized tooltip text', () => { const wrapper = mount( <QuickInput value='mock' clearable={true} clearableTooltipText='Custom' onClear={() => {}} />, ); expect(wrapper.find('.input-clear')).toMatchSnapshot(); }); test('with customized tooltip component', () => { const wrapper = mount( <QuickInput value='mock' clearable={true} clearableTooltipText={ <span>{'Custom'}</span> } onClear={() => {}} />, ); expect(wrapper.find('.input-clear')).toMatchSnapshot(); }); }); test('should dismiss clear button', () => { const focusFn = jest.fn(); class MockComp extends React.PureComponent { focus = focusFn; render() { return <div/>; } } const wrapper = mount( <QuickInput value='mock' clearable={true} onClear={() => {}} inputComponent={MockComp} />, ); wrapper.setProps({onClear: () => wrapper.setProps({value: ''})}); expect(wrapper.find('.input-clear').exists()).toBe(true); wrapper.find('.input-clear').simulate('mousedown'); expect(wrapper.find('.input-clear').exists()).toBe(false); expect(focusFn).toBeCalled(); }); });
2,981
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_input
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_input/__snapshots__/max_length_input.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/MaxLengthInput should match snapshot 1`] = ` <Fragment> <input className="MaxLengthInput input" /> </Fragment> `; exports[`components/MaxLengthInput should match snapshot 2`] = ` <Fragment> <input className="MaxLengthInput input" defaultValue="less than 20" /> </Fragment> `; exports[`components/MaxLengthInput should match snapshot 3`] = ` <Fragment> <input className="MaxLengthInput input has-error" defaultValue="Where is Jessica Hyde?" /> <span className="MaxLengthInput__validation" > - 2 </span> </Fragment> `;
2,982
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_input
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_input/__snapshots__/quick_input.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/QuickInput should render clear button with customized tooltip component 1`] = ` <div className="input-clear visible" onMouseDown={[Function]} onTouchEnd={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="InputClearTooltip" > <span> Custom </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper id="InputClearTooltip" intl={null} > <span> Custom </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <span aria-hidden="true" className="input-clear-x" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-close-circle" /> </span> </OverlayTrigger> </OverlayTrigger> </div> `; exports[`components/QuickInput should render clear button with customized tooltip text 1`] = ` <div className="input-clear visible" onMouseDown={[Function]} onTouchEnd={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="InputClearTooltip" > Custom </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper id="InputClearTooltip" intl={null} > Custom </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <span aria-hidden="true" className="input-clear-x" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-close-circle" /> </span> </OverlayTrigger> </OverlayTrigger> </div> `; exports[`components/QuickInput should render clear button with default tooltip text 1`] = ` <div className="input-clear visible" onMouseDown={[Function]} onTouchEnd={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="InputClearTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Clear" id="input.clear" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper id="InputClearTooltip" intl={null} > <Memo(MemoizedFormattedMessage) defaultMessage="Clear" id="input.clear" /> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <span aria-hidden="true" className="input-clear-x" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-close-circle" /> </span> </OverlayTrigger> </OverlayTrigger> </div> `;
2,984
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_switch_modal/quick_switch_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 QuickSwitchModal from 'components/quick_switch_modal/quick_switch_modal'; import Constants from 'utils/constants'; describe('components/QuickSwitchModal', () => { const baseProps = { onExited: jest.fn(), showTeamSwitcher: false, isMobileView: false, actions: { joinChannelById: jest.fn().mockResolvedValue({data: true}), switchToChannel: jest.fn().mockImplementation(() => { const error = { message: 'Failed', }; return Promise.resolve({error}); }), closeRightHandSide: jest.fn(), }, }; it('should match snapshot', () => { const wrapper = shallow( <QuickSwitchModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); describe('handleSubmit', () => { it('should do nothing if nothing selected', () => { const props = {...baseProps}; const wrapper = shallow<QuickSwitchModal>( <QuickSwitchModal {...props}/>, ); wrapper.instance().handleSubmit(); expect(baseProps.onExited).not.toBeCalled(); expect(props.actions.switchToChannel).not.toBeCalled(); }); it('should fail to switch to a channel', (done) => { const wrapper = shallow<QuickSwitchModal>( <QuickSwitchModal {...baseProps}/>, ); const channel = {id: 'channel_id', userId: 'user_id', type: Constants.DM_CHANNEL}; wrapper.instance().handleSubmit({channel}); expect(baseProps.actions.switchToChannel).toBeCalledWith(channel); process.nextTick(() => { expect(baseProps.onExited).not.toBeCalled(); done(); }); }); it('should switch to a channel', (done) => { const props = { ...baseProps, actions: { ...baseProps.actions, switchToChannel: jest.fn().mockImplementation(() => { const data = true; return Promise.resolve({data}); }), }, }; const wrapper = shallow<QuickSwitchModal>( <QuickSwitchModal {...props}/>, ); const channel = {id: 'channel_id', userId: 'user_id', type: Constants.DM_CHANNEL}; wrapper.instance().handleSubmit({channel}); expect(props.actions.switchToChannel).toBeCalledWith(channel); process.nextTick(() => { expect(baseProps.onExited).toBeCalled(); done(); }); }); it('should join the channel before switching', (done) => { const props = { ...baseProps, actions: { ...baseProps.actions, switchToChannel: jest.fn().mockImplementation(() => { const data = true; return Promise.resolve({data}); }), }, }; const wrapper = shallow<QuickSwitchModal>( <QuickSwitchModal {...props}/>, ); const channel = {id: 'channel_id', name: 'test', type: Constants.OPEN_CHANNEL}; const selected = { type: Constants.MENTION_MORE_CHANNELS, channel, }; wrapper.instance().handleSubmit(selected); expect(props.actions.joinChannelById).toBeCalledWith(channel.id); process.nextTick(() => { expect(props.actions.switchToChannel).toBeCalledWith(channel); done(); }); }); it('should not join the channel before switching if channel is DM', (done) => { const props = { ...baseProps, actions: { ...baseProps.actions, switchToChannel: jest.fn().mockImplementation(() => { const data = true; return Promise.resolve({data}); }), }, }; const wrapper = shallow<QuickSwitchModal>( <QuickSwitchModal {...props}/>, ); const channel = {id: 'channel_id', name: 'test', type: Constants.DM_CHANNEL}; const selected = { type: Constants.MENTION_MORE_CHANNELS, channel, }; wrapper.instance().handleSubmit(selected); expect(props.actions.joinChannelById).not.toHaveBeenCalled(); expect(props.actions.switchToChannel).toBeCalledWith(channel); process.nextTick(() => { expect(baseProps.onExited).toBeCalled(); done(); }); }); }); });
2,986
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_switch_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/quick_switch_modal/__snapshots__/quick_switch_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/QuickSwitchModal should match snapshot 1`] = ` <Modal animation={false} aria-describedby="quickSwitchHeaderWithHint" aria-labelledby="quickSwitchHeader" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal channel-switcher" dialogComponentClass={[Function]} enforceFocus={false} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onHide={[Function]} renderBackdrop={[Function]} restoreFocus={false} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" id="quickSwitchModalLabel" /> <ModalBody bsClass="modal-body" componentClass="div" > <div className="channel-switcher__header" id="quickSwitchHeaderWithHint" > <h1 id="quickSwitchHeader" > <MemoizedFormattedMessage defaultMessage="Find Channels" id="quick_switch_modal.switchChannels" /> </h1> <div className="channel-switcher__hint" id="quickSwitchHint" > <FormattedMarkdownMessage defaultMessage="Type to find a channel. Use **UP/DOWN** to browse, **ENTER** to select, **ESC** to dismiss." id="quick_switch_modal.help_no_team" /> </div> </div> <div className="channel-switcher__suggestion-box" > <i className="icon icon-magnify icon-16" /> <Connect(SuggestionBox) aria-label="quick switch input" className="form-control focused" completeOnTab={false} delayInputUpdate={true} forceSuggestionsWhenBlur={true} id="quickSwitchInput" listComponent={[Function]} listPosition="bottom" maxLength="64" onChange={[Function]} onItemSelected={[Function]} onSuggestionsReceived={[Function]} openWhenEmpty={true} providers={ Array [ SwitchChannelProvider { "disableDispatches": false, "forceDispatch": false, "latestComplete": true, "latestPrefix": "", "requestStarted": false, }, ] } renderDividers={ Array [ "mention.unread", "mention.recent.channels", ] } shouldSearchCompleteText={true} spellCheck="false" value="" /> </div> </ModalBody> </Modal> `;
2,988
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/removed_from_channel_modal/removed_from_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 RemovedFromChannelModal from 'components/removed_from_channel_modal/removed_from_channel_modal'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; describe('components/RemoveFromChannelModal', () => { const baseProps = { currentUserId: 'current_user_id', channelName: 'test-channel', remover: 'Administrator', onExited: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <RemovedFromChannelModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have state "show" equals true on mount', () => { const wrapper = shallow( <RemovedFromChannelModal {...baseProps}/>, ); expect(wrapper.state('show')).toBe(true); }); test('should display correct props on Modal.Title and Modal.Body', () => { const wrapper = mountWithIntl( <RemovedFromChannelModal {...baseProps}/>, ); expect(wrapper.find('.modal-title').text()).toBe('Removed from test-channel'); expect(wrapper.find('.modal-body').text()).toBe('Administrator removed you from test-channel'); }); test('should fallback to default text on Modal.Body', () => { baseProps.channelName = ''; baseProps.remover = ''; const wrapper = mountWithIntl( <RemovedFromChannelModal {...baseProps}/>, ); expect(wrapper.find('.modal-title').text()).toBe('Removed from the channel'); expect(wrapper.find('.modal-body').text()).toBe('Someone removed you from the channel'); }); });
2,990
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/removed_from_channel_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/removed_from_channel_modal/__snapshots__/removed_from_channel_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/RemoveFromChannelModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="removeFromChannelModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__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={[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="removeFromChannelModalLabel" > <MemoizedFormattedMessage defaultMessage="Removed from " id="removed_channel.from" /> <span className="name" > test-channel </span> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <p> <MemoizedFormattedMessage defaultMessage="{remover} removed you from {channel}" id="removed_channel.remover" values={ Object { "channel": "test-channel", "remover": "Administrator", } } /> </p> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-primary" id="removedChannelBtn" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Okay" id="removed_channel.okay" /> </button> </ModalFooter> </Modal> `;
2,992
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rename_channel_modal/rename_channel_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {Channel} from '@mattermost/types/channels'; import type {Team} from '@mattermost/types/teams'; import {RequestStatus} from 'mattermost-redux/constants'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; import RenameChannelModal from './rename_channel_modal'; import type {RenameChannelModal as RenameChannelModalClass} from './rename_channel_modal'; describe('components/RenameChannelModal', () => { const channel: Channel = TestHelper.getChannelMock({ id: 'fake-id', name: 'fake-channel', display_name: 'Fake Channel', }); const team: Team = TestHelper.getTeamMock({ name: 'Fake Team', display_name: 'fake-team', }); const baseProps = { show: true, onExited: jest.fn(), channel: {...channel}, requestStatus: RequestStatus.NOT_STARTED, team: {...team}, currentTeamUrl: 'fake-channel', actions: {patchChannel: jest.fn().mockResolvedValue({data: true})}, }; test('should match snapshot', () => { const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should submit form', () => { const {actions: {patchChannel}} = baseProps; const props = {...baseProps, requestStatus: RequestStatus.STARTED}; const wrapper = shallowWithIntl( <RenameChannelModal {...props}/>, ); wrapper.find('#display_name').simulate( 'change', {preventDefault: jest.fn(), target: {value: 'valid name'}}, ); wrapper.find('#save-button').simulate('click'); expect(patchChannel).toHaveBeenCalled(); }); describe('should validate channel url (name)', () => { const testCases: Array<[{name: string; value: string}, boolean]> = [ [{name: 'must be one or more characters', value: ''}, false], [{name: 'must start with a letter or number', value: '_channel'}, false], [{name: 'must end with a letter or number', value: 'channel_'}, false], [{name: 'can contain two underscores in a row', value: 'channel__two'}, true], [{name: 'can not resemble direct message channel url', value: 'uzsfmtmniifsjgesce4u7yznyh__uzsfmtmniifsjgesce4u7yznyh'}, false], [{name: 'valid channel url', value: 'a_valid_channel'}, true], ]; testCases.forEach(([testCaseProps, patchShouldHaveBeenCalled]) => { it(testCaseProps.name, () => { const {actions: {patchChannel}} = baseProps; const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); wrapper.setState({channelName: testCaseProps.value}); wrapper.find('#save-button').simulate('click'); if (patchShouldHaveBeenCalled) { expect(patchChannel).toHaveBeenCalled(); } else { expect(patchChannel).not.toHaveBeenCalled(); } }); }); }); test('should not call patchChannel as channel.name.length > Constants.MAX_CHANNELNAME_LENGTH (64)', () => { const {actions: {patchChannel}} = baseProps; const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); wrapper.find('#display_name').simulate( 'change', {preventDefault: jest.fn(), target: {value: 'string-above-sixtyfour-characters-to-test-the-channel-maxlength-limit-properly-in-the-component'}}, ); wrapper.find('#save-button').simulate('click'); expect(patchChannel).not.toHaveBeenCalled(); }); test('should change state when display_name is edited', () => { const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); wrapper.find('#display_name').simulate( 'change', {preventDefault: jest.fn(), target: {value: 'New Fake Channel'}}, ); expect(wrapper.state('displayName')).toBe('New Fake Channel'); }); test('should call setError function', () => { const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); const instance = wrapper.instance() as RenameChannelModalClass; instance.setError({message: 'This is an error message'}); expect(wrapper.state('serverError')).toBe('This is an error message'); }); test('should call unsetError function', () => { const props = {...baseProps, serverError: {message: 'This is an error message'}}; const wrapper = shallowWithIntl( <RenameChannelModal {...props}/>, ); wrapper.setState({serverError: props.serverError.message}); expect(wrapper.state('serverError')).toBe('This is an error message'); wrapper.find('#save-button').simulate('click'); expect(wrapper.state('serverError')).toBe(''); }); test('should call handleSubmit function', async () => { const patchChannel = jest.fn(). mockResolvedValueOnce({error: true}). mockResolvedValue({data: true}); const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps} actions={{patchChannel}} />, ); wrapper.setState({displayName: 'Changed Name', channelName: 'changed-name'}); const instance = wrapper.instance() as RenameChannelModalClass; instance.onSaveSuccess = jest.fn(); instance.setError = jest.fn(); await instance.handleSubmit(); expect(patchChannel).toHaveBeenCalledTimes(1); expect(wrapper.state('displayName')).toBe('Changed Name'); expect(wrapper.state('channelName')).toBe('changed-name'); expect(instance.onSaveSuccess).not.toBeCalled(); expect(instance.setError).toBeCalledTimes(1); expect(instance.setError).toBeCalledWith(true); await instance.handleSubmit(); expect(patchChannel).toHaveBeenCalledTimes(2); expect(wrapper.state('displayName')).toBe('Changed Name'); expect(wrapper.state('channelName')).toBe('changed-name'); expect(instance.onSaveSuccess).toBeCalledTimes(1); expect(instance.setError).toBeCalledTimes(1); }); test('should call handleCancel', () => { const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); const instance = wrapper.instance() as RenameChannelModalClass; instance.handleCancel(); expect(wrapper.state('show')).toBeFalsy(); }); test('should call handleHide function', () => { const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); const instance = wrapper.instance() as RenameChannelModalClass; instance.handleHide(); expect(wrapper.state('show')).toBeFalsy(); }); test('should call onNameChange function', () => { const changedName = {target: {value: 'changed-name'}}; const wrapper = shallowWithIntl( <RenameChannelModal {...baseProps}/>, ); const instance = wrapper.instance() as RenameChannelModalClass; instance.onNameChange(changedName); expect(wrapper.state('channelName')).toBe('changed-name'); }); });
2,994
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rename_channel_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rename_channel_modal/__snapshots__/rename_channel_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/RenameChannelModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="renameChannelModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__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], } } onEntering={[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="renameChannelModalLabel" > <MemoizedFormattedMessage defaultMessage="Rename Channel" id="rename_channel.title" /> </ModalTitle> </ModalHeader> <form role="form" > <ModalBody bsClass="modal-body" componentClass="div" > <div className="form-group" > <label className="control-label" > <MemoizedFormattedMessage defaultMessage="Display Name" id="rename_channel.displayName" /> </label> <input aria-label="display name" className="form-control" id="display_name" maxLength={64} onChange={[Function]} placeholder="Enter display name" type="text" value="Fake Channel" /> </div> <div className="form-group" > <label className="control-label" > URL </label> <div className="input-group input-group--limit" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="urlTooltip" > fake-channel/channels </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <span className="input-group-addon" > fake-channel/channels/ </span> </OverlayTrigger> <input aria-label="rename channel" className="form-control" id="channel_name" maxLength={64} onChange={[Function]} readOnly={false} type="text" value="fake-channel" /> </div> <p className="input__help" > <MemoizedFormattedMessage defaultMessage="You can use lowercase letters, numbers, dashes, and underscores." id="change_url.helpText" /> </p> </div> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-tertiary" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Cancel" id="rename_channel.cancel" /> </button> <button className="btn btn-primary" id="save-button" onClick={[Function]} type="submit" > <MemoizedFormattedMessage defaultMessage="Save" id="rename_channel.save" /> </button> </ModalFooter> </form> </Modal> `;
2,996
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/reset_status_modal/reset_status_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 ResetStatusModal from 'components/reset_status_modal/reset_status_modal'; describe('components/ResetStatusModal', () => { const autoResetStatus = jest.fn().mockImplementation( () => { return new Promise((resolve) => { process.nextTick(() => resolve({data: {status: 'away'}})); }); }, ); const baseProps = { autoResetPref: '', actions: { autoResetStatus, setStatus: jest.fn(), savePreferences: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <ResetStatusModal onHide={jest.fn()} {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should have match state when onConfirm is called', () => { const newSetStatus = jest.fn(); const newSavePreferences = jest.fn(); const props = { ...baseProps, actions: { autoResetStatus, setStatus: newSetStatus, savePreferences: newSavePreferences, }, }; const wrapper = shallow( <ResetStatusModal onHide={jest.fn()} {...props} />, ); const currentUserStatus = { status: 'away', user_id: 'user_id_1', }; const expectedUserStatus = { status: 'online', user_id: 'user_id_1', }; wrapper.setState({ show: true, currentUserStatus, }); const instance = wrapper.instance() as ResetStatusModal; instance.onConfirm(false); expect(wrapper.state('show')).toEqual(false); expect(newSetStatus).toHaveBeenCalledTimes(1); expect(newSetStatus).toHaveBeenCalledWith(expectedUserStatus); expect(newSavePreferences).not.toHaveBeenCalled(); wrapper.setState({ show: true, currentUserStatus, }); instance.onConfirm(true); expect(wrapper.state('show')).toEqual(false); expect(newSetStatus).toHaveBeenCalledTimes(2); expect(newSetStatus).toHaveBeenCalledWith(expectedUserStatus); expect(newSavePreferences).toHaveBeenCalledTimes(1); expect(newSavePreferences).toHaveBeenCalledWith( 'user_id_1', [{category: 'auto_reset_manual_status', name: 'user_id_1', user_id: 'user_id_1', value: 'true'}], ); }); test('should have match state when onCancel is called', () => { const newSavePreferences = jest.fn(); const props = { ...baseProps, actions: { autoResetStatus, setStatus: jest.fn(), savePreferences: newSavePreferences, }, }; const wrapper = shallow( <ResetStatusModal onHide={jest.fn()} {...props} />, ); const currentUserStatus = { status: 'away', user_id: 'user_id_1', }; wrapper.setState({ show: true, currentUserStatus, }); const instance = wrapper.instance() as ResetStatusModal; instance.onCancel(false); expect(wrapper.state('show')).toEqual(false); expect(newSavePreferences).not.toHaveBeenCalled(); wrapper.setState({ show: true, currentUserStatus, }); instance.onCancel(true); expect(wrapper.state('show')).toEqual(false); expect(newSavePreferences).toHaveBeenCalledTimes(1); expect(newSavePreferences).toHaveBeenCalledWith( 'user_id_1', [{category: 'auto_reset_manual_status', name: 'user_id_1', user_id: 'user_id_1', value: 'false'}], ); }); test('should match snapshot, render modal for OOF status', () => { const props = {...baseProps, currentUserStatus: 'ooo'}; const wrapper = shallow( <ResetStatusModal onHide={jest.fn()} {...props} />, ); expect(wrapper).toMatchSnapshot(); }); });
2,998
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/reset_status_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/reset_status_modal/__snapshots__/reset_status_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ResetStatusModal should match snapshot 1`] = ` <ConfirmModal cancelButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="No, keep it as \\"{status}\\"" id="modal.manual_status.cancel_" values={ Object { "status": "", } } /> } checkboxText={ <Memo(MemoizedFormattedMessage) defaultMessage="Do not ask me again" id="modal.manual_status.ask" /> } confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Yes, set my status to \\"{status}\\"" id="modal.manual_status.button_online" values={ Object { "status": "Online", } } /> } message={ <Memo(MemoizedFormattedMessage) defaultMessage="Would you like to switch your status to \\"{status}\\"?" id="modal.manual_status.message_online" values={ Object { "status": "Online", } } /> } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={false} showCheckbox={true} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Your Status is Set to \\"{status}\\"" id="modal.manual_status.title_" values={ Object { "status": "", } } /> } /> `; exports[`components/ResetStatusModal should match snapshot, render modal for OOF status 1`] = ` <ConfirmModal cancelButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="No, keep it as \\"{status}\\"" id="modal.manual_status.cancel_" values={ Object { "status": "", } } /> } checkboxText={ <Memo(MemoizedFormattedMessage) defaultMessage="Do not ask me again" id="modal.manual_status.ask" /> } confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Yes, set my status to \\"{status}\\"" id="modal.manual_status.button_online" values={ Object { "status": "Online", } } /> } message={ <Memo(MemoizedFormattedMessage) defaultMessage="Would you like to switch your status to \\"{status}\\" and disable Automatic Replies?" id="modal.manual_status.auto_responder.message_online" values={ Object { "status": "Online", } } /> } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={false} showCheckbox={false} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Your Status is Set to \\"{status}\\"" id="modal.manual_status.title_" values={ Object { "status": "", } } /> } /> `;
3,005
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rhs_card/rhs_card.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 {TestHelper} from 'utils/test_helper'; import type {PostPluginComponent} from 'types/store/plugins'; import type {RhsState} from 'types/store/rhs'; import RhsCard from './rhs_card'; describe('comoponents/rhs_card/RhsCard', () => { const post = TestHelper.getPostMock({ id: '123', message: 'test', create_at: 1542994995740, props: {}, }); const baseProps: ComponentProps<typeof RhsCard> = { isMobileView: false, pluginPostCardTypes: {postType: {} as PostPluginComponent}, teamUrl: 'test-team-url', enablePostUsernameOverride: false, previousRhsState: {} as RhsState, }; it('should match when no post is selected', () => { const wrapper = shallow( <RhsCard {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); it('should match on post when no plugin defining card types', () => { const wrapper = shallow( <RhsCard {...baseProps} selected={post} />, ); expect(wrapper).toMatchSnapshot(); }); it('should match on post when plugin defining card types don\'t match with the post type', () => { const wrapper = shallow( <RhsCard {...baseProps} selected={post} pluginPostCardTypes={{notMatchingType: {component: () => <i/>} as unknown as PostPluginComponent}} />, ); expect(wrapper).toMatchSnapshot(); }); it('should match on post when plugin defining card types match with the post type', () => { const wrapper = shallow( <RhsCard {...baseProps} selected={post} pluginPostCardTypes={{test: {component: () => <i/>} as unknown as PostPluginComponent}} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,007
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rhs_card
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rhs_card/__snapshots__/rhs_card.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`comoponents/rhs_card/RhsCard should match on post when no plugin defining card types 1`] = ` <div className="sidebar-right__body sidebar-right__card" > <Connect(injectIntl(RhsCardHeader)) previousRhsState={Object {}} /> <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]} tagName="div" thumbMinSize={30} universal={false} > <div className="post-right__scroll" > <div className="info-card" > <Connect(Markdown) /> </div> <div className="d-flex post-card--info" > <div className="post-card--post-by overflow--ellipsis" > <MemoizedFormattedMessage defaultMessage="Message by {avatar} {user}" id="rhs_card.message_by" values={ Object { "avatar": <Memo(Connect(PostProfilePicture)) compactDisplay={false} post={ Object { "channel_id": "", "create_at": 1542994995740, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "123", "is_pinned": false, "message": "test", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } userId="user_id" />, "user": <Memo(Connect(UserProfile)) disablePopover={true} hideStatus={true} userId="user_id" />, } } /> </div> <div className="post-card--view-post" > <Link className="post__permalink" onClick={[Function]} to="test-team-url/pl/123" > <MemoizedFormattedMessage defaultMessage="Jump" id="rhs_card.jump" /> </Link> </div> </div> </div> </Scrollbars> </div> `; exports[`comoponents/rhs_card/RhsCard should match on post when plugin defining card types don't match with the post type 1`] = ` <div className="sidebar-right__body sidebar-right__card" > <Connect(injectIntl(RhsCardHeader)) previousRhsState={Object {}} /> <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]} tagName="div" thumbMinSize={30} universal={false} > <div className="post-right__scroll" > <div className="info-card" > <Connect(Markdown) /> </div> <div className="d-flex post-card--info" > <div className="post-card--post-by overflow--ellipsis" > <MemoizedFormattedMessage defaultMessage="Message by {avatar} {user}" id="rhs_card.message_by" values={ Object { "avatar": <Memo(Connect(PostProfilePicture)) compactDisplay={false} post={ Object { "channel_id": "", "create_at": 1542994995740, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "123", "is_pinned": false, "message": "test", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } userId="user_id" />, "user": <Memo(Connect(UserProfile)) disablePopover={true} hideStatus={true} userId="user_id" />, } } /> </div> <div className="post-card--view-post" > <Link className="post__permalink" onClick={[Function]} to="test-team-url/pl/123" > <MemoizedFormattedMessage defaultMessage="Jump" id="rhs_card.jump" /> </Link> </div> </div> </div> </Scrollbars> </div> `; exports[`comoponents/rhs_card/RhsCard should match on post when plugin defining card types match with the post type 1`] = ` <div className="sidebar-right__body sidebar-right__card" > <Connect(injectIntl(RhsCardHeader)) previousRhsState={Object {}} /> <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]} tagName="div" thumbMinSize={30} universal={false} > <div className="post-right__scroll" > <div className="info-card" > <Connect(Markdown) /> </div> <div className="d-flex post-card--info" > <div className="post-card--post-by overflow--ellipsis" > <MemoizedFormattedMessage defaultMessage="Message by {avatar} {user}" id="rhs_card.message_by" values={ Object { "avatar": <Memo(Connect(PostProfilePicture)) compactDisplay={false} post={ Object { "channel_id": "", "create_at": 1542994995740, "delete_at": 0, "edit_at": 0, "hashtags": "", "id": "123", "is_pinned": false, "message": "test", "metadata": Object { "embeds": Array [], "emojis": Array [], "files": Array [], "images": Object {}, "reactions": Array [], }, "original_id": "", "pending_post_id": "", "props": Object {}, "reply_count": 0, "root_id": "", "type": "system_add_remove", "update_at": 0, "user_id": "user_id", } } userId="user_id" />, "user": <Memo(Connect(UserProfile)) disablePopover={true} hideStatus={true} userId="user_id" />, } } /> </div> <div className="post-card--view-post" > <Link className="post__permalink" onClick={[Function]} to="test-team-url/pl/123" > <MemoizedFormattedMessage defaultMessage="Jump" id="rhs_card.jump" /> </Link> </div> </div> </div> </Scrollbars> </div> `; exports[`comoponents/rhs_card/RhsCard should match when no post is selected 1`] = `<div />`;
3,014
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rhs_thread/rhs_thread.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 RhsThread from './rhs_thread'; 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/RhsThread', () => { const post: Post = TestHelper.getPostMock({ channel_id: 'channel_id', create_at: 1502715365009, update_at: 1502715372443, }); 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(), }; const directTeammate: UserProfile = TestHelper.getUserMock(); const currentTeam = TestHelper.getTeamMock(); const baseProps = { posts: [post], selected: post, channel, currentUserId: 'user_id', previewCollapsed: 'false', previewEnabled: true, socketConnectionStatus: true, actions, directTeammate, currentTeam, }; test('should match snapshot', () => { const wrapper = shallow( <RhsThread {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,016
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rhs_thread
petrpan-code/mattermost/mattermost/webapp/channels/src/components/rhs_thread/__snapshots__/rhs_thread.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/RhsThread should match snapshot 1`] = ` <div className="sidebar-right__body" id="rhsContainer" > <Connect(injectIntl(RhsHeaderPost)) 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, } } rootPostId="id" /> <Connect(ThreadViewer) isThreadView={false} rootPostId="id" useRelativeTimestamp={false} /> </div> `;
3,019
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/root/root.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 {RouteComponentProps} from 'react-router-dom'; import rudderAnalytics from 'rudder-sdk-js'; import {ServiceEnvironment} from '@mattermost/types/config'; import {GeneralTypes} from 'mattermost-redux/action_types'; import {Client4} from 'mattermost-redux/client'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import * as GlobalActions from 'actions/global_actions'; import store from 'stores/redux_store'; import Root from 'components/root/root'; import {StoragePrefixes} from 'utils/constants'; import type {ProductComponent} from 'types/store/plugins'; jest.mock('rudder-sdk-js', () => ({ identify: jest.fn(), load: jest.fn(), page: jest.fn(), ready: jest.fn((callback) => callback()), track: jest.fn(), })); jest.mock('actions/telemetry_actions'); jest.mock('actions/global_actions', () => ({ redirectUserToDefaultTeam: jest.fn(), })); jest.mock('utils/utils', () => { const original = jest.requireActual('utils/utils'); return { ...original, localizeMessage: () => {}, applyTheme: jest.fn(), makeIsEligibleForClick: jest.fn(), }; }); jest.mock('mattermost-redux/actions/general', () => ({ setUrl: () => {}, })); describe('components/Root', () => { const baseProps = { telemetryEnabled: true, telemetryId: '1234ab', noAccounts: false, showTermsOfService: false, theme: {} as Theme, actions: { loadConfigAndMe: jest.fn().mockImplementation(() => { return Promise.resolve({ data: false, }); }), getFirstAdminSetupComplete: jest.fn(() => Promise.resolve({ type: GeneralTypes.FIRST_ADMIN_COMPLETE_SETUP_RECEIVED, data: true, })), getProfiles: jest.fn(), migrateRecentEmojis: jest.fn(), savePreferences: jest.fn(), registerCustomPostRenderer: jest.fn(), initializeProducts: jest.fn(), }, permalinkRedirectTeamName: 'myTeam', showLaunchingWorkspace: false, plugins: [], products: [], ...{ location: { pathname: '/', }, } as RouteComponentProps, isCloud: false, rhsIsExpanded: false, rhsIsOpen: false, shouldShowAppBar: false, }; test('should load config and license on mount and redirect to sign-up page', () => { const props = { ...baseProps, noAccounts: true, history: { push: jest.fn(), } as unknown as RouteComponentProps['history'], }; const wrapper = shallow(<Root {...props}/>); (wrapper.instance() as any).onConfigLoaded(); expect(props.history.push).toHaveBeenCalledWith('/signup_user_complete'); wrapper.unmount(); }); test('should load user, config, and license on mount and redirect to defaultTeam on success', (done) => { document.cookie = 'MMUSERID=userid'; localStorage.setItem('was_logged_in', 'true'); const props = { ...baseProps, actions: { ...baseProps.actions, loadConfigAndMe: jest.fn().mockImplementation(() => { return Promise.resolve({data: true}); }), }, }; // Mock the method by extending the class because we don't have a chance to do it before shallow mounts the component class MockedRoot extends Root { onConfigLoaded = jest.fn(() => { expect(this.onConfigLoaded).toHaveBeenCalledTimes(1); expect(GlobalActions.redirectUserToDefaultTeam).toHaveBeenCalledTimes(1); expect(props.actions.loadConfigAndMe).toHaveBeenCalledTimes(1); done(); }); } const wrapper = shallow(<MockedRoot {...props}/>); wrapper.unmount(); }); test('should load user, config, and license on mount and should not redirect to defaultTeam id pathname is not root', (done) => { document.cookie = 'MMUSERID=userid'; localStorage.setItem('was_logged_in', 'true'); const props = { ...baseProps, location: { pathname: '/admin_console', } as RouteComponentProps['location'], actions: { ...baseProps.actions, loadConfigAndMe: jest.fn().mockImplementation(() => { return Promise.resolve({data: true}); }), }, }; // Mock the method by extending the class because we don't have a chance to do it before shallow mounts the component class MockedRoot extends Root { onConfigLoaded = jest.fn(() => { expect(this.onConfigLoaded).toHaveBeenCalledTimes(1); expect(GlobalActions.redirectUserToDefaultTeam).not.toHaveBeenCalled(); expect(props.actions.loadConfigAndMe).toHaveBeenCalledTimes(1); done(); }); } const wrapper = shallow(<MockedRoot {...props}/>); wrapper.unmount(); }); test('should call history on props change', () => { const props = { ...baseProps, noAccounts: false, history: { push: jest.fn(), } as unknown as RouteComponentProps['history'], }; const wrapper = shallow(<Root {...props}/>); expect(props.history.push).not.toHaveBeenCalled(); const props2 = { noAccounts: true, }; wrapper.setProps(props2); expect(props.history.push).toHaveBeenLastCalledWith('/signup_user_complete'); wrapper.unmount(); }); test('should reload on focus after getting signal login event from another tab', () => { Object.defineProperty(window.location, 'reload', { configurable: true, writable: true, }); window.location.reload = jest.fn(); const wrapper = shallow(<Root {...baseProps}/>); const loginSignal = new StorageEvent('storage', { key: StoragePrefixes.LOGIN, newValue: String(Math.random()), storageArea: localStorage, }); window.dispatchEvent(loginSignal); window.dispatchEvent(new Event('focus')); expect(window.location.reload).toBeCalledTimes(1); wrapper.unmount(); }); describe('onConfigLoaded', () => { afterEach(() => { Client4.telemetryHandler = undefined; }); test('should not set a TelemetryHandler when onConfigLoaded is called if Rudder is not configured', () => { store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RECEIVED, data: { ServiceEnvironment: ServiceEnvironment.DEV, }, }); const wrapper = shallow(<Root {...baseProps}/>); Client4.trackEvent('category', 'event'); expect(Client4.telemetryHandler).not.toBeDefined(); wrapper.unmount(); }); test('should set a TelemetryHandler when onConfigLoaded is called if Rudder is configured', () => { store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RECEIVED, data: { ServiceEnvironment: ServiceEnvironment.TEST, }, }); const wrapper = shallow(<Root {...baseProps}/>); (wrapper.instance() as any).onConfigLoaded(); Client4.trackEvent('category', 'event'); expect(Client4.telemetryHandler).toBeDefined(); wrapper.unmount(); }); test('should not set a TelemetryHandler when onConfigLoaded is called but Rudder has been blocked', () => { (rudderAnalytics.ready as any).mockImplementation(() => { // Simulate an error occurring and the callback not getting called }); store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RECEIVED, data: { ServiceEnvironment: ServiceEnvironment.TEST, }, }); const wrapper = shallow(<Root {...baseProps}/>); (wrapper.instance() as any).onConfigLoaded(); Client4.trackEvent('category', 'event'); expect(Client4.telemetryHandler).not.toBeDefined(); wrapper.unmount(); }); }); describe('Routes', () => { test('Should mount public product routes', () => { const mainComponent = () => (<p>{'TestMainComponent'}</p>); const publicComponent = () => (<p>{'TestPublicProduct'}</p>); const props = { ...baseProps, products: [{ id: 'productwithpublic', baseURL: '/productwithpublic', mainComponent, publicComponent, } as unknown as ProductComponent, { id: 'productwithoutpublic', baseURL: '/productwithoutpublic', mainComponent, publicComponent: null, } as unknown as ProductComponent], }; const wrapper = shallow(<Root {...props}/>); (wrapper.instance() as any).setState({configLoaded: true}); expect(wrapper).toMatchSnapshot(); wrapper.unmount(); }); }); });
3,022
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/root
petrpan-code/mattermost/mattermost/webapp/channels/src/components/root/__snapshots__/root.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/Root Routes Should mount public product routes 1`] = ` <RootProvider> <Connect(MobileViewWatcher) /> <Switch> <Route component={[Function]} path="/error" /> <HFRoute component={[Function]} path="/login" /> <HFRoute component={[Function]} path="/access_problem" /> <HFTRoute component={[Function]} path="/reset_password" /> <HFTRoute component={[Function]} path="/reset_password_complete" /> <HFRoute component={[Function]} path="/signup_user_complete" /> <HFRoute component={[Function]} path="/should_verify_email" /> <HFRoute component={[Function]} path="/do_verify_email" /> <HFTRoute component={[Function]} path="/claim" /> <LoggedInRoute component={[Function]} path="/terms_of_service" /> <Route component={[Function]} path="/landing" /> <Route path="/admin_console" > <Switch> <LoggedInRoute component={[Function]} path="/admin_console" theme={Object {}} /> <Connect(RootRedirect) /> </Switch> </Route> <LoggedInHFTRoute component={[Function]} path="/select_team" /> <LoggedInHFTRoute component={[Function]} path="/oauth/authorize" /> <LoggedInHFTRoute component={[Function]} path="/create_team" /> <LoggedInRoute component={[Function]} path="/mfa" /> <LoggedInRoute component={[Function]} path="/preparing-workspace" /> <Redirect from="/_redirect/integrations/:subpath*" to="/myTeam/integrations/:subpath*" /> <Redirect from="/_redirect/pl/:postid" to="/myTeam/pl/:postid" /> <CompassThemeProvider theme={Object {}} > <WindowSizeObserver /> <Connect(ModalController) /> <Connect(Component) /> <Connect(injectIntl(SystemNotice)) /> <GlobalHeader /> <CloudEffectsWrapper /> <withRouter(Connect(TeamSidebar)) /> <DelinquencyModalController /> <Switch> <Route key="productwithpublic-public" path="/productwithpublic/public" render={[Function]} /> <Route key="productwithpublic" path="/productwithpublic" render={[Function]} /> <Route key="productwithoutpublic" path="/productwithoutpublic" render={[Function]} /> <LoggedInRoute component={[Function]} path="/:team([a-z0-9\\\\-_]+)" theme={Object {}} /> <Connect(RootRedirect) /> </Switch> <Connect(Pluggable) pluggableName="Global" /> <withRouter(Connect(SidebarRight)) /> <AppBar /> <Connect(SidebarRightMenu) /> </CompassThemeProvider> </Switch> </RootProvider> `;
3,026
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/screening_in_progress_modal/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as controlModalHooks from 'components/common/hooks/useControlModal'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import ScreeningInProgressModal from './'; describe('ScreeningInProgressModal', () => { it('informs customer that the subscription is under review', () => { renderWithContext(<ScreeningInProgressModal/>); screen.getByText('Your transaction is being reviewed'); }); it('closes the modal on click', () => { const mockClose = jest.fn(); jest.spyOn(controlModalHooks, 'useControlScreeningInProgressModal').mockImplementation(() => ({close: mockClose, open: jest.fn()})); renderWithContext(<ScreeningInProgressModal/>); screen.getAllByText('Close')[1].click(); expect(mockClose).toHaveBeenCalled(); }); });
3,030
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/scroll_to_bottom_toast/scroll_to_bottom_toast.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 ScrollToBottomToast from './scroll_to_bottom_toast'; describe('ScrollToBottomToast Component', () => { const mockOnDismiss = jest.fn(); const mockOnClick = jest.fn(); const mockOnClickEvent = { preventDefault: jest.fn(), stopPropagation: jest.fn(), }; it('should render ScrollToBottomToast component', () => { const wrapper = shallow( <ScrollToBottomToast onDismiss={mockOnDismiss} onClick={mockOnClick} />, ); // Assertions expect(wrapper.find('.scroll-to-bottom-toast')).toHaveLength(1); expect(wrapper.find('UnreadBelowIcon')).toHaveLength(1); expect(wrapper.text()).toContain('Jump to recents'); expect(wrapper.find('.scroll-to-bottom-toast__dismiss')).toHaveLength(1); expect(wrapper.find('.close-btn')).toHaveLength(1); }); it('should call onClick when clicked', () => { const wrapper = shallow( <ScrollToBottomToast onDismiss={mockOnDismiss} onClick={mockOnClick} />, ); // Simulate click wrapper.simulate('click', mockOnClickEvent); // Expect the onClick function to be called expect(mockOnClick).toHaveBeenCalled(); }); it('should call onDismiss when close button is clicked', () => { const wrapper = shallow( <ScrollToBottomToast onDismiss={mockOnDismiss} onClick={mockOnClick} />, ); // Simulate click on the close button wrapper.find('.scroll-to-bottom-toast__dismiss').simulate('click', mockOnClickEvent); // Expect the onDismiss function to be called expect(mockOnDismiss).toHaveBeenCalled(); // Expect to stop propagation to avoid scrolling down on dismissing expect(mockOnClickEvent.stopPropagation).toHaveBeenCalled(); }); });
3,036
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search/user_guide_dropdown/user_guide_dropdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {trackEvent} from 'actions/telemetry_actions.jsx'; import Menu from 'components/widgets/menu/menu'; import MenuWrapper from 'components/widgets/menu/menu_wrapper'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import UserGuideDropdown from './user_guide_dropdown'; jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); describe('UserGuideDropdown', () => { const baseProps = { helpLink: 'helpLink', reportAProblemLink: 'reportAProblemLink', enableAskCommunityLink: 'true', actions: { openModal: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallowWithIntl( <UserGuideDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for false of enableAskCommunityLink', () => { const props = { ...baseProps, enableAskCommunityLink: 'false', }; const wrapper = shallowWithIntl( <UserGuideDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('Should set state buttonActive on toggle of MenuWrapper', () => { const wrapper = shallowWithIntl( <UserGuideDropdown {...baseProps}/>, ); expect(wrapper.state('buttonActive')).toBe(false); wrapper.find(MenuWrapper).prop('onToggle')!(true); expect(wrapper.state('buttonActive')).toBe(true); }); test('Should set state buttonActive on toggle of MenuWrapper', () => { const wrapper = shallowWithIntl( <UserGuideDropdown {...baseProps}/>, ); wrapper.find(Menu.ItemAction).prop('onClick')({preventDefault: jest.fn()}); expect(baseProps.actions.openModal).toHaveBeenCalled(); }); test('Should call for track event on click of askTheCommunityLink', () => { const wrapper = shallowWithIntl( <UserGuideDropdown {...baseProps}/>, ); wrapper.find(Menu.ItemExternalLink).find('#askTheCommunityLink').prop('onClick')!({} as unknown as React.MouseEvent); expect(trackEvent).toBeCalledWith('ui', 'help_ask_the_community'); }); });
3,038
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search/user_guide_dropdown
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search/user_guide_dropdown/__snapshots__/user_guide_dropdown.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`UserGuideDropdown should match snapshot 1`] = ` <MenuWrapper animationComponent={[Function]} className="userGuideHelp" onToggle={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="userGuideHelpTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Help" id="channel_header.userHelpGuide" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-expanded="true" className="channel-header__icon" id="channelHeaderUserGuideButton" type="button" > <UserGuideIcon className="icon" /> </button> </OverlayTrigger> <Menu ariaLabel="Add Channel Dropdown" id="AddChannelDropdown" openLeft={true} openUp={false} > <Memo(MenuGroup)> <MenuItemExternalLink id="askTheCommunityLink" onClick={[Function]} show={true} text="Ask the community" url="https://mattermost.com/pl/default-ask-mattermost-community/" /> <MenuItemExternalLink id="helpResourcesLink" show={true} text="Help resources" url="helpLink" /> <MenuItemExternalLink id="reportAProblemLink" show={true} text="Report a problem" url="reportAProblemLink" /> <MenuItemAction id="keyboardShortcuts" onClick={[Function]} show={true} text="Keyboard shortcuts" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`UserGuideDropdown should match snapshot for false of enableAskCommunityLink 1`] = ` <MenuWrapper animationComponent={[Function]} className="userGuideHelp" onToggle={[Function]} > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="userGuideHelpTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Help" id="channel_header.userHelpGuide" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-expanded="true" className="channel-header__icon" id="channelHeaderUserGuideButton" type="button" > <UserGuideIcon className="icon" /> </button> </OverlayTrigger> <Menu ariaLabel="Add Channel Dropdown" id="AddChannelDropdown" openLeft={true} openUp={false} > <Memo(MenuGroup)> <MenuItemExternalLink id="helpResourcesLink" show={true} text="Help resources" url="helpLink" /> <MenuItemExternalLink id="reportAProblemLink" show={true} text="Report a problem" url="reportAProblemLink" /> <MenuItemAction id="keyboardShortcuts" onClick={[Function]} show={true} text="Keyboard shortcuts" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `;
3,039
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_bar/search_bar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ComponentProps} from 'react'; import SearchChannelProvider from 'components/suggestion/search_channel_provider'; import SearchDateProvider from 'components/suggestion/search_date_provider'; import SearchUserProvider from 'components/suggestion/search_user_provider'; import {renderWithContext} from 'tests/react_testing_utils'; import SearchBar from './search_bar'; const suggestionProviders = [ new SearchDateProvider(), new SearchChannelProvider(jest.fn()), new SearchUserProvider(jest.fn()), ]; describe('components/search_bar/SearchBar', () => { const baseProps: ComponentProps<typeof SearchBar> = { suggestionProviders, searchTerms: '', keepFocused: false, setKeepFocused: jest.fn(), isFocused: false, isSideBarRight: false, isSearchingTerm: false, searchType: '', clearSearchType: jest.fn(), children: null, updateHighlightedSearchHint: jest.fn(), handleChange: jest.fn(), handleSubmit: jest.fn(), handleEnterKey: jest.fn(), handleClear: jest.fn(), handleFocus: jest.fn(), handleBlur: jest.fn(), }; it('should match snapshot without search', () => { const {container} = renderWithContext( <SearchBar {...baseProps}/>, ); expect(container).toMatchSnapshot(); }); it('should match snapshot without search, without searchType', () => { const {container} = renderWithContext( <SearchBar {...baseProps}/>, ); expect(container).toMatchSnapshot(); }); it('should match snapshot without search, with searchType', () => { const {container} = renderWithContext( <SearchBar {...baseProps} searchType='files' />, ); expect(container).toMatchSnapshot(); }); it('should match snapshot with search, with searchType', () => { const {container} = renderWithContext( <SearchBar {...baseProps} searchTerms={'test'} searchType='files' />, ); expect(container).toMatchSnapshot(); }); it('should match snapshot with search', () => { const {container} = renderWithContext( <SearchBar {...baseProps} searchTerms={'test'} />, ); expect(container).toMatchSnapshot(); }); });
3,041
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_bar/__snapshots__/search_bar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/search_bar/SearchBar should match snapshot with search 1`] = ` <div> <div class="search-form__container" id="searchFormContainer" > <form aria-labelledby="searchBox" autocomplete="off" class="search__form" role="search" style="overflow: visible;" > <div class="search__font-icon" > <i class="icon icon-magnify icon-16" /> </div> <div class="w-full" > <div aria-live="polite" class="sr-only" role="alert" /> <div> <input aria-describedby="searchbar-help-popup" aria-label="Search" autocomplete="off" class="search-bar form-control a11y__region" data-a11y-sort-order="9" id="searchBox" placeholder="Search" tabindex="0" type="search" value="test" /> <div class="input-clear visible" > <span aria-hidden="true" class="input-clear-x" > <i class="icon icon-close-circle" /> </span> </div> </div> </div> </form> </div> </div> `; exports[`components/search_bar/SearchBar should match snapshot with search, with searchType 1`] = ` <div> <div class="search-form__container" id="searchFormContainer" > <form aria-labelledby="searchBox" autocomplete="off" class="search__form" role="search" style="overflow: visible;" > <div class="search__font-icon" > <i class="icon icon-magnify icon-16" /> </div> <div class="searchTypeBadge" > FILES <i class="icon icon-close icon-12" /> </div> <div class="w-full" > <div aria-live="polite" class="sr-only" role="alert" /> <div> <input aria-describedby="searchbar-help-popup" aria-label="Search" autocomplete="off" class="search-bar form-control a11y__region" data-a11y-sort-order="9" id="searchBox" placeholder="Search" tabindex="0" type="search" value="test" /> <div class="input-clear visible" > <span aria-hidden="true" class="input-clear-x" > <i class="icon icon-close-circle" /> </span> </div> </div> </div> </form> </div> </div> `; exports[`components/search_bar/SearchBar should match snapshot without search 1`] = ` <div> <div class="search-form__container" id="searchFormContainer" > <form aria-labelledby="searchBox" autocomplete="off" class="search__form" role="search" style="overflow: visible;" > <div class="search__font-icon" > <i class="icon icon-magnify icon-16" /> </div> <div class="w-full" > <div aria-live="polite" class="sr-only" role="alert" /> <div> <input aria-describedby="searchbar-help-popup" aria-label="Search" autocomplete="off" class="search-bar form-control a11y__region" data-a11y-sort-order="9" id="searchBox" placeholder="Search" tabindex="0" type="search" value="" /> </div> </div> </form> </div> </div> `; exports[`components/search_bar/SearchBar should match snapshot without search, with searchType 1`] = ` <div> <div class="search-form__container" id="searchFormContainer" > <form aria-labelledby="searchBox" autocomplete="off" class="search__form" role="search" style="overflow: visible;" > <div class="search__font-icon" > <i class="icon icon-magnify icon-16" /> </div> <div class="searchTypeBadge" > FILES <i class="icon icon-close icon-12" /> </div> <div class="w-full" > <div aria-live="polite" class="sr-only" role="alert" /> <div> <input aria-describedby="searchbar-help-popup" aria-label="Search" autocomplete="off" class="search-bar form-control a11y__region" data-a11y-sort-order="9" id="searchBox" placeholder="Search" tabindex="0" type="search" value="" /> </div> </div> </form> </div> </div> `; exports[`components/search_bar/SearchBar should match snapshot without search, without searchType 1`] = ` <div> <div class="search-form__container" id="searchFormContainer" > <form aria-labelledby="searchBox" autocomplete="off" class="search__form" role="search" style="overflow: visible;" > <div class="search__font-icon" > <i class="icon icon-magnify icon-16" /> </div> <div class="w-full" > <div aria-live="polite" class="sr-only" role="alert" /> <div> <input aria-describedby="searchbar-help-popup" aria-label="Search" autocomplete="off" class="search-bar form-control a11y__region" data-a11y-sort-order="9" id="searchBox" placeholder="Search" tabindex="0" type="search" value="" /> </div> </div> </form> </div> </div> `;
3,042
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_hint/search_hint.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 SearchHint from 'components/search_hint/search_hint'; import {searchHintOptions} from 'utils/constants'; let mockState: any; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), })); describe('components/SearchHint', () => { const baseProps = { withTitle: false, onOptionSelected: jest.fn(), options: searchHintOptions, }; beforeEach(() => { mockState = { entities: { general: { config: { EnableFileAttachments: 'true', }, }, }, }; }); test('should match snapshot, with title', () => { const props = { ...baseProps, withTitle: true, }; const wrapper = shallow( <SearchHint {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, without title', () => { const wrapper = shallow( <SearchHint {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, without searchType', () => { const props = { ...baseProps, withTitle: true, onSearchTypeSelected: jest.fn(), searchType: '' as 'files' | 'messages' | '', }; const wrapper = shallow( <SearchHint {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, with searchType', () => { const props = { ...baseProps, onSearchTypeSelected: jest.fn(), searchType: 'files' as 'files' | 'messages' | '', }; const wrapper = shallow( <SearchHint {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,044
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_hint
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_hint/__snapshots__/search_hint.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SearchHint should match snapshot, with searchType 1`] = ` <Fragment> <ul className="search-hint__suggestions-list" role="list" > <li className="search-hint__suggestions-list__option" key="From:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > From: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages from a user" id="search_list_option.from" /> </div> </li> <li className="search-hint__suggestions-list__option" key="In:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > In: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages in a channel" id="search_list_option.in" /> </div> </li> <li className="search-hint__suggestions-list__option" key="On:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > On: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages on a date" id="search_list_option.on" /> </div> </li> <li className="search-hint__suggestions-list__option" key="Before:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > Before: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages before a date" id="search_list_option.before" /> </div> </li> <li className="search-hint__suggestions-list__option" key="After:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > After: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages after a date" id="search_list_option.after" /> </div> </li> <li className="search-hint__suggestions-list__option" key="-" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > — </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Exclude search terms" id="search_list_option.exclude" /> </div> </li> <li className="search-hint__suggestions-list__option" key="\\"\\"" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > "" </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages with phrases" id="search_list_option.phrases" /> </div> </li> </ul> </Fragment> `; exports[`components/SearchHint should match snapshot, with title 1`] = ` <Fragment> <h4 className="search-hint__title" > <MemoizedFormattedMessage defaultMessage="Search options" id="search_bar.usage.title" /> </h4> <ul className="search-hint__suggestions-list" role="list" > <li className="search-hint__suggestions-list__option" key="From:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > From: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages from a user" id="search_list_option.from" /> </div> </li> <li className="search-hint__suggestions-list__option" key="In:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > In: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages in a channel" id="search_list_option.in" /> </div> </li> <li className="search-hint__suggestions-list__option" key="On:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > On: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages on a date" id="search_list_option.on" /> </div> </li> <li className="search-hint__suggestions-list__option" key="Before:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > Before: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages before a date" id="search_list_option.before" /> </div> </li> <li className="search-hint__suggestions-list__option" key="After:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > After: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages after a date" id="search_list_option.after" /> </div> </li> <li className="search-hint__suggestions-list__option" key="-" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > — </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Exclude search terms" id="search_list_option.exclude" /> </div> </li> <li className="search-hint__suggestions-list__option" key="\\"\\"" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > "" </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages with phrases" id="search_list_option.phrases" /> </div> </li> </ul> </Fragment> `; exports[`components/SearchHint should match snapshot, without searchType 1`] = ` <div className="search-hint__search-type-selector" > <div> <MemoizedFormattedMessage defaultMessage="What are you searching for?" id="search_bar.usage.search_type_question" /> </div> <div className="button-container" > <button className="" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} > <i className="icon icon-message-text-outline" /> <MemoizedFormattedMessage defaultMessage="Messages" id="search_bar.usage.search_type_messages" /> </button> <button className="" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} > <i className="icon icon-file-text-outline" /> <MemoizedFormattedMessage defaultMessage="Files" id="search_bar.usage.search_type_files" /> </button> </div> </div> `; exports[`components/SearchHint should match snapshot, without title 1`] = ` <Fragment> <ul className="search-hint__suggestions-list" role="list" > <li className="search-hint__suggestions-list__option" key="From:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > From: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages from a user" id="search_list_option.from" /> </div> </li> <li className="search-hint__suggestions-list__option" key="In:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > In: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages in a channel" id="search_list_option.in" /> </div> </li> <li className="search-hint__suggestions-list__option" key="On:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > On: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages on a date" id="search_list_option.on" /> </div> </li> <li className="search-hint__suggestions-list__option" key="Before:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > Before: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages before a date" id="search_list_option.before" /> </div> </li> <li className="search-hint__suggestions-list__option" key="After:" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > After: </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages after a date" id="search_list_option.after" /> </div> </li> <li className="search-hint__suggestions-list__option" key="-" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > — </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Exclude search terms" id="search_list_option.exclude" /> </div> </li> <li className="search-hint__suggestions-list__option" key="\\"\\"" onMouseDown={[Function]} onMouseOver={[Function]} onTouchEnd={[Function]} > <div className="search-hint__suggestion-list__flex-wrap" > <span className="search-hint__suggestion-list__label" > "" </span> </div> <div className="search-hint__suggestion-list__value" > <MemoizedFormattedMessage defaultMessage="Messages with phrases" id="search_list_option.phrases" /> </div> </li> </ul> </Fragment> `;
3,046
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results/files_filter_menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import type {ShallowWrapper} from 'enzyme'; import React from 'react'; import FilesFilterMenu from 'components/search_results/files_filter_menu'; describe('components/search_results/FilesFilterMenu', () => { const filters = ['all', 'documents', 'spreadsheets', 'presentations', 'code', 'images', 'audio', 'video']; for (const filter of filters) { test(`should match snapshot, on ${filter} filter selected`, () => { const wrapper: ShallowWrapper<any, any, any> = shallow( <FilesFilterMenu selectedFilter={filter} onFilter={jest.fn()} />, ); expect(wrapper).toMatchSnapshot(); }); } });
3,050
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results/messages_or_files_selector.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import type {ShallowWrapper} from 'enzyme'; import React from 'react'; import MessagesOrFilesSelector from 'components/search_results/messages_or_files_selector'; describe('components/search_results/MessagesOrFilesSelector', () => { test('should match snapshot, on messages selected', () => { const wrapper: ShallowWrapper<any, any, any> = shallow( <MessagesOrFilesSelector selected='messages' selectedFilter='code' messagesCounter='5' filesCounter='10' isFileAttachmentsEnabled={true} onChange={jest.fn()} onFilter={jest.fn()} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on files selected', () => { const wrapper: ShallowWrapper<any, any, any> = shallow( <MessagesOrFilesSelector selected='files' selectedFilter='code' messagesCounter='5' filesCounter='10' isFileAttachmentsEnabled={true} onChange={jest.fn()} onFilter={jest.fn()} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, without files tab', () => { const wrapper: ShallowWrapper<any, any, any> = shallow( <MessagesOrFilesSelector selected='files' selectedFilter='code' messagesCounter='5' filesCounter='10' isFileAttachmentsEnabled={false} onChange={jest.fn()} onFilter={jest.fn()} />, ); expect(wrapper).toMatchSnapshot(); }); });
3,053
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results/search_limits_banner.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Provider} from 'react-redux'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {CloudProducts} from 'utils/constants'; import {FileSizes} from 'utils/file_utils'; import {makeEmptyUsage} from 'utils/limits_test'; import SearchLimitsBanner from './search_limits_banner'; const usage = makeEmptyUsage(); const limits = { limitsLoaded: true, limits: { integrations: { enabled: 5, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, teamsLoaded: true, }, boards: { cards: 500, views: 5, }, }, }; const products = { prod_1: { id: 'prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, name: 'Cloud Free', }, prod_2: { id: 'prod_2', sku: CloudProducts.PROFESSIONAL, price_per_seat: 10, name: 'Cloud Professional', }, prod_3: { id: 'prod_3', sku: CloudProducts.ENTERPRISE, price_per_seat: 30, name: 'Cloud Enterprise', }, }; describe('components/select_results/SearchLimitsBanner', () => { test('should NOT show banner for non cloud when doing messages search', () => { const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'false', // not cloud }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: null, products: null, limits: { limits: {}, limitsLoaded: false, }, }, usage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='messages'/></Provider>); expect(wrapper.find('#messages_search_limits_banner').exists()).toEqual(false); }); test('should NOT show banner for non cloud when doing files search', () => { const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'false', // not cloud }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: null, products: null, limits: { limits: {}, limitsLoaded: false, }, }, usage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='files'/></Provider>); expect(wrapper.find('#files_search_limits_banner').exists()).toEqual(false); }); test('should NOT show banner for cloud when doing cloud messages search for product without limits', () => { const aboveMessagesLimitUsage = JSON.parse(JSON.stringify(usage)); aboveMessagesLimitUsage.messages.history = 15000; // above limit of 10k const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: { is_free_trial: 'false', product_id: 'prod_3', // enterprise }, products, limits: { limits: {}, limitsLoaded: false, }, }, usage: aboveMessagesLimitUsage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='messages'/></Provider>); expect(wrapper.find('#messages_search_limits_banner').exists()).toEqual(false); }); test('should NOT show banner for cloud when doing cloud files search for product without limits', () => { const aboveMessagesLimitUsage = JSON.parse(JSON.stringify(usage)); aboveMessagesLimitUsage.messages.history = 15000; // above limit of 10k const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: { is_free_trial: 'false', product_id: 'prod_3', // enterprise }, products, limits: { limits: {}, limitsLoaded: false, }, }, usage: aboveMessagesLimitUsage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='files'/></Provider>); expect(wrapper.find('#files_search_limits_banner').exists()).toEqual(false); }); test('should show banner for CLOUD when doing cloud messages search above the limit in Free product', () => { const aboveMessagesLimitUsage = JSON.parse(JSON.stringify(usage)); aboveMessagesLimitUsage.messages.history = 15000; // above limit of 10K const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', // cloud }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: { is_free_trial: 'true', product_id: 'prod_1', // free }, products, limits, }, usage: aboveMessagesLimitUsage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='messages'/></Provider>); expect(wrapper.find('#messages_search_limits_banner').exists()).toEqual(true); }); test('should show banner for CLOUD when doing cloud files search above the limit in Free product', () => { const aboveFilesLimitUsage = JSON.parse(JSON.stringify(usage)); aboveFilesLimitUsage.files.totalStorage = 1.1 * FileSizes.Gigabyte; // above limit of 1GB const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', // cloud }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: { is_free_trial: 'true', product_id: 'prod_1', // free }, products, limits, }, usage: aboveFilesLimitUsage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='files'/></Provider>); expect(wrapper.find('#files_search_limits_banner').exists()).toEqual(true); }); test('should not show banner for CLOUD when doing cloud files search above the limit in PROFESSIONAL product', () => { const aboveFilesLimitUsage = JSON.parse(JSON.stringify(usage)); aboveFilesLimitUsage.files.totalStorage = 1.1 * FileSizes.Gigabyte; // above limit of 1GB. This limit is higher in professional const state = { entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', // cloud }, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, }, cloud: { subscription: { is_free_trial: 'true', product_id: 'prod_2', // professional }, products, limits: { limits: {}, limitsLoaded: false, }, }, usage: aboveFilesLimitUsage, }, }; const store = mockStore(state); const wrapper = mountWithIntl(<Provider store={store}><SearchLimitsBanner searchType='files'/></Provider>); expect(wrapper.find('#files_search_limits_banner').exists()).toEqual(false); }); });
3,056
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results/search_results.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {arePropsEqual} from 'components/search_results/search_results'; describe('components/SearchResults', () => { describe('shouldRenderFromProps', () => { const result1 = {test: 'test'}; const result2 = {test: 'test'}; const fileResult1 = {test: 'test'}; const fileResult2 = {test: 'test'}; const results = [result1, result2]; const fileResults = [fileResult1, fileResult2]; const props = { prop1: 'someprop', somearray: [1, 2, 3], results, fileResults, }; // Using a lot of anys here since the function is only used by SearchResults so the parameters are bound to its props // But the tests are written using arbitrary props test('should not render', () => { expect(arePropsEqual(props as any, {...props} as any)).toBeTruthy(); expect(arePropsEqual(props as any, {...props, results: [result1, result2]} as any)).toBeTruthy(); expect(arePropsEqual(props as any, {...props, fileResults: [fileResult1, fileResult2]} as any)).toBeTruthy(); }); test('should render', () => { expect(!arePropsEqual(props as any, {...props, prop1: 'newprop'} as any)).toBeTruthy(); expect(!arePropsEqual(props as any, {...props, results: [result2, result1]} as any)).toBeTruthy(); expect(!arePropsEqual(props as any, {...props, results: [result1, result2, {test: 'test'}]} as any)).toBeTruthy(); expect(!arePropsEqual(props as any, {...props, fileResults: [fileResult2, fileResult1]} as any)).toBeTruthy(); expect(!arePropsEqual(props as any, {...props, fileResults: [fileResult1, fileResult2, {test: 'test'}]} as any)).toBeTruthy(); expect(!arePropsEqual(props as any, {...props, somearray: [1, 2, 3]} as any)).toBeTruthy(); }); }); });
3,059
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results/__snapshots__/files_filter_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/search_results/FilesFilterMenu should match snapshot, on all filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on audio filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on code filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on documents filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on images filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on presentations filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on spreadsheets filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={null} onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `; exports[`components/search_results/FilesFilterMenu should match snapshot, on video filter selected 1`] = ` <div className="FilesFilterMenu" > <MenuWrapper animationComponent={[Function]} className="" > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="files-filter-tooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Filter" id="channel_info_rhs.menu.files.filter" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <IconContainer className="action-icon dots-icon" id="filesFilterButton" type="button" > <i className="icon-dot" /> <FilterVariantIcon color="currentColor" size={18} /> </IconContainer> </OverlayTrigger> <Menu ariaLabel="file menu" openLeft={true} > <MenuItemAction ariaLabel="All file types" icon={null} onClick={[Function]} show={true} text="All file types" /> <MenuItemAction ariaLabel="Documents" icon={null} onClick={[Function]} show={true} text="Documents" /> <MenuItemAction ariaLabel="Spreadsheets" icon={null} onClick={[Function]} show={true} text="Spreadsheets" /> <MenuItemAction ariaLabel="Presentations" icon={null} onClick={[Function]} show={true} text="Presentations" /> <MenuItemAction ariaLabel="Code" icon={null} onClick={[Function]} show={true} text="Code" /> <MenuItemAction ariaLabel="Images" icon={null} onClick={[Function]} show={true} text="Images" /> <MenuItemAction ariaLabel="Audio" icon={null} onClick={[Function]} show={true} text="Audio" /> <MenuItemAction ariaLabel="Videos" icon={ <i className="icon icon-check" /> } onClick={[Function]} show={true} text="Videos" /> </Menu> </MenuWrapper> </div> `;
3,060
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results/__snapshots__/messages_or_files_selector.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/search_results/MessagesOrFilesSelector should match snapshot, on files selected 1`] = ` <div className="MessagesOrFilesSelector" > <div className="buttons-container" > <button className="tab messages-tab" onClick={[Function]} onKeyDown={[Function]} > <MemoizedFormattedMessage defaultMessage="Messages" id="search_bar.messages_tab" /> <span className="counter" > 5 </span> </button> <button className="active tab files-tab" onClick={[Function]} onKeyDown={[Function]} > <MemoizedFormattedMessage defaultMessage="Files" id="search_bar.files_tab" /> <span className="counter" > 10 </span> </button> </div> <FilesFilterMenu onFilter={[MockFunction]} selectedFilter="code" /> </div> `; exports[`components/search_results/MessagesOrFilesSelector should match snapshot, on messages selected 1`] = ` <div className="MessagesOrFilesSelector" > <div className="buttons-container" > <button className="active tab messages-tab" onClick={[Function]} onKeyDown={[Function]} > <MemoizedFormattedMessage defaultMessage="Messages" id="search_bar.messages_tab" /> <span className="counter" > 5 </span> </button> <button className="tab files-tab" onClick={[Function]} onKeyDown={[Function]} > <MemoizedFormattedMessage defaultMessage="Files" id="search_bar.files_tab" /> <span className="counter" > 10 </span> </button> </div> </div> `; exports[`components/search_results/MessagesOrFilesSelector should match snapshot, without files tab 1`] = ` <div className="MessagesOrFilesSelector" > <div className="buttons-container" > <button className="tab messages-tab" onClick={[Function]} onKeyDown={[Function]} > <MemoizedFormattedMessage defaultMessage="Messages" id="search_bar.messages_tab" /> <span className="counter" > 5 </span> </button> </div> <FilesFilterMenu onFilter={[MockFunction]} selectedFilter="code" /> </div> `;
3,062
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_results_header/search_results_header.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {RHSStates} from 'utils/constants'; import type {RhsState} from 'types/store/rhs'; import Header from './search_results_header'; describe('search_results_header', () => { test('should display back button when the parent is channel info', () => { renderWithContext( <Header previousRhsState={RHSStates.CHANNEL_INFO as RhsState} canGoBack={true} isExpanded={false} actions={{ closeRightHandSide: jest.fn(), toggleRhsExpanded: jest.fn(), goBack: jest.fn(), }} > {'Title'} </Header>, ); expect(screen.getByLabelText('Back Icon')).toBeInTheDocument(); }); test('should NOT diplay expand when the parent is channel info', () => { renderWithContext( <Header previousRhsState={RHSStates.CHANNEL_INFO as RhsState} canGoBack={true} isExpanded={false} actions={{ closeRightHandSide: jest.fn(), toggleRhsExpanded: jest.fn(), goBack: jest.fn(), }} > {'Title'} </Header>, ); expect(screen.queryByLabelText('Expand Sidebar Icon')).not.toBeInTheDocument(); }); test('should diplay expand when the parent is NOT channel info', () => { renderWithContext( <Header previousRhsState={RHSStates.FLAG as RhsState} canGoBack={true} isExpanded={false} actions={{ closeRightHandSide: jest.fn(), toggleRhsExpanded: jest.fn(), goBack: jest.fn(), }} > {'Title'} </Header>, ); expect(screen.getByLabelText('Expand Sidebar Icon')).toBeInTheDocument(); }); });
3,066
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_shortcut/search_shortcut.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 {SearchShortcut} from 'components/search_shortcut'; describe('components/SearchShortcut', () => { test('should match snapshot on Windows webapp', () => { jest.mock('utils/user_agent', () => { const original = jest.requireActual('utils/user_agent'); return { ...original, isDesktopApp: jest.fn(() => false), isMac: jest.fn(() => false), }; }); const wrapper = shallow(<SearchShortcut/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on Mac webapp', () => { jest.mock('utils/user_agent', () => { const original = jest.requireActual('utils/user_agent'); return { ...original, isDesktopApp: jest.fn(() => false), isMac: jest.fn(() => true), }; }); const wrapper = shallow(<SearchShortcut/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on Windows desktop', () => { jest.mock('utils/user_agent', () => { const original = jest.requireActual('utils/user_agent'); return { ...original, isDesktopApp: jest.fn(() => true), isMac: jest.fn(() => true), }; }); const wrapper = shallow(<SearchShortcut/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on Mac desktop', () => { jest.mock('utils/user_agent', () => { const original = jest.requireActual('utils/user_agent'); return { ...original, isDesktopApp: jest.fn(() => true), isMac: jest.fn(() => true), }; }); const wrapper = shallow(<SearchShortcut/>); expect(wrapper).toMatchSnapshot(); }); });
3,068
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_shortcut
petrpan-code/mattermost/mattermost/webapp/channels/src/components/search_shortcut/__snapshots__/search_shortcut.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SearchShortcut should match snapshot on Mac desktop 1`] = ` <span className="search-shortcut" > <ShortcutKey variant="contrast" > Ctrl </ShortcutKey> <ShortcutKey variant="contrast" > Shift </ShortcutKey> <ShortcutKey variant="contrast" > F </ShortcutKey> </span> `; exports[`components/SearchShortcut should match snapshot on Mac webapp 1`] = ` <span className="search-shortcut" > <ShortcutKey variant="contrast" > Ctrl </ShortcutKey> <ShortcutKey variant="contrast" > Shift </ShortcutKey> <ShortcutKey variant="contrast" > F </ShortcutKey> </span> `; exports[`components/SearchShortcut should match snapshot on Windows desktop 1`] = ` <span className="search-shortcut" > <ShortcutKey variant="contrast" > Ctrl </ShortcutKey> <ShortcutKey variant="contrast" > Shift </ShortcutKey> <ShortcutKey variant="contrast" > F </ShortcutKey> </span> `; exports[`components/SearchShortcut should match snapshot on Windows webapp 1`] = ` <span className="search-shortcut" > <ShortcutKey variant="contrast" > Ctrl </ShortcutKey> <ShortcutKey variant="contrast" > Shift </ShortcutKey> <ShortcutKey variant="contrast" > F </ShortcutKey> </span> `;
3,076
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team/select_team.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 {CloudUsage} from '@mattermost/types/cloud'; import type {Team} from '@mattermost/types/teams'; import {emitUserLoggedOutEvent} from 'actions/global_actions'; import SelectTeam, {TEAMS_PER_PAGE} from 'components/select_team/select_team'; jest.mock('actions/global_actions', () => ({ emitUserLoggedOutEvent: jest.fn(), })); jest.mock('utils/policy_roles_adapter', () => ({ mappingValueFromRoles: jest.fn(), })); describe('components/select_team/SelectTeam', () => { const baseProps = { currentUserRoles: 'system_admin', currentUserId: 'test', isMemberOfTeam: true, listableTeams: [ {id: 'team_id_1', delete_at: 0, name: 'team-a', display_name: 'Team A', allow_open_invite: true} as Team, {id: 'team_id_2', delete_at: 0, name: 'b-team', display_name: 'B Team', allow_open_invite: true} as Team, ], siteName: 'Mattermost', canCreateTeams: false, canManageSystem: true, canJoinPublicTeams: true, canJoinPrivateTeams: false, history: {push: jest.fn()}, actions: { getTeams: jest.fn().mockResolvedValue({}), loadRolesIfNeeded: jest.fn(), addUserToTeam: jest.fn().mockResolvedValue({data: true}), }, totalTeamsCount: 15, isCloud: false, isFreeTrial: false, usageDeltas: { teams: { active: Number.MAX_VALUE, }, } as CloudUsage, }; test('should match snapshot', () => { const props = {...baseProps}; const wrapper = shallow(<SelectTeam {...props}/>); expect(wrapper).toMatchSnapshot(); // on componentDidMount expect(props.actions.getTeams).toHaveBeenCalledTimes(1); expect(props.actions.getTeams).toHaveBeenCalledWith(0, TEAMS_PER_PAGE, true); expect(props.actions.loadRolesIfNeeded).toHaveBeenCalledWith(baseProps.currentUserRoles.split(' ')); }); test('should match snapshot, on loading', () => { const wrapper = shallow<SelectTeam>( <SelectTeam {...baseProps}/>, ); wrapper.setState({loadingTeamId: 'loading_team_id'}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on error', () => { const wrapper = shallow<SelectTeam>( <SelectTeam {...baseProps}/>, ); wrapper.setState({error: {message: 'error message'}}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on no joinable team but can create team', () => { const props = {...baseProps, listableTeams: []}; const wrapper = shallow<SelectTeam>( <SelectTeam {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on no joinable team and is not system admin nor can create team', () => { const props = {...baseProps, listableTeams: [], currentUserRoles: '', canManageSystem: false, canCreateTeams: false}; const wrapper = shallow<SelectTeam>( <SelectTeam {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on no joinable team and user is guest', () => { const props = {...baseProps, listableTeams: [], currentUserRoles: '', currentUserIsGuest: true, canManageSystem: false, canCreateTeams: false}; const wrapper = shallow<SelectTeam>( <SelectTeam {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match state and call addUserToTeam on handleTeamClick', async () => { const wrapper = shallow<SelectTeam>( <SelectTeam {...baseProps}/>, ); await wrapper.instance().handleTeamClick({id: 'team_id'} as any); expect(wrapper.state('loadingTeamId')).toEqual('team_id'); expect(baseProps.actions.addUserToTeam).toHaveBeenCalledTimes(1); }); test('should call emitUserLoggedOutEvent on handleLogoutClick', () => { const wrapper = shallow<SelectTeam>( <SelectTeam {...baseProps}/>, ); wrapper.instance().handleLogoutClick({preventDefault: jest.fn()} as any); expect(emitUserLoggedOutEvent).toHaveBeenCalledTimes(1); expect(emitUserLoggedOutEvent).toHaveBeenCalledWith('/login'); }); test('should match state on clearError', () => { const wrapper = shallow<SelectTeam>( <SelectTeam {...baseProps}/>, ); wrapper.setState({error: {message: 'error message'}}); wrapper.instance().clearError({preventDefault: jest.fn()} as any); expect(wrapper.state('error')).toBeNull(); }); test('should match snapshot, on create team restricted', () => { const props = { ...baseProps, isCloud: true, isFreeTrial: false, usageDeltas: { teams: { active: 0, }, } as CloudUsage, }; const wrapper = shallow<SelectTeam>( <SelectTeam {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,078
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team/__snapshots__/select_team.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/select_team/SelectTeam should match snapshot 1`] = ` <div> <Connect(Component) /> <BackButton url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <div className="signup__content" id="teamsYouCanJoinContent" > <div className="SelectTeam__sub-header" > <h4> <MemoizedFormattedMessage defaultMessage="Teams you can join: " id="signup_team.join_open" /> </h4> <LearnAboutTeamsLink /> </div> <InfiniteScroll bufferValue={280} callBack={[Function]} endOfDataMessage="" itemsPerPage={30} loaderStyle={ Object { "height": "40px", "padding": "0px", } } pageNumber={0} styleClass="signup-team-all" totalItems={15} > <div className="signup-team-dir-err" > <div> <MemoizedFormattedMessage defaultMessage="No teams are available to join. Please create a new team or ask your administrator for an invite." id="signup_team.no_open_teams_canCreate" /> </div> </div> </InfiniteScroll> </div> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <div className="margin--extra" style={ Object { "marginTop": "0.5em", } } > <Link className="signup-team-login" id="createNewTeamLink" onClick={[Function]} to="/create_team" > <MemoizedFormattedMessage defaultMessage="Create a team" id="login.createTeam" /> </Link> </div> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `; exports[`components/select_team/SelectTeam should match snapshot, on create team restricted 1`] = ` <div> <Connect(Component) /> <BackButton url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <div className="signup__content" id="teamsYouCanJoinContent" > <div className="SelectTeam__sub-header" > <h4> <MemoizedFormattedMessage defaultMessage="Teams you can join: " id="signup_team.join_open" /> </h4> <LearnAboutTeamsLink /> </div> <InfiniteScroll bufferValue={280} callBack={[Function]} endOfDataMessage="" itemsPerPage={30} loaderStyle={ Object { "height": "40px", "padding": "0px", } } pageNumber={0} styleClass="signup-team-all" totalItems={15} > <div className="signup-team-dir-err" > <div> <MemoizedFormattedMessage defaultMessage="No teams are available to join. Please ask your administrator for an invite." id="signup_team.no_open_teams" /> </div> </div> </InfiniteScroll> </div> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `; exports[`components/select_team/SelectTeam should match snapshot, on error 1`] = ` <div> <Connect(Component) /> <BackButton onClick={[Function]} url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <div className="signup__content" > <div className="form-group has-error" > <label className="control-label" > <Component /> </label> </div> </div> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <div className="margin--extra" style={ Object { "marginTop": "0.5em", } } > <Link className="signup-team-login" id="createNewTeamLink" onClick={[Function]} to="/create_team" > <MemoizedFormattedMessage defaultMessage="Create a team" id="login.createTeam" /> </Link> </div> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `; exports[`components/select_team/SelectTeam should match snapshot, on loading 1`] = ` <div> <Connect(Component) /> <BackButton url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <LoadingScreen /> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <div className="margin--extra" style={ Object { "marginTop": "0.5em", } } > <Link className="signup-team-login" id="createNewTeamLink" onClick={[Function]} to="/create_team" > <MemoizedFormattedMessage defaultMessage="Create a team" id="login.createTeam" /> </Link> </div> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `; exports[`components/select_team/SelectTeam should match snapshot, on no joinable team and is not system admin nor can create team 1`] = ` <div> <Connect(Component) /> <BackButton url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <div className="signup__content" id="teamsYouCanJoinContent" > <div className="SelectTeam__sub-header" > <h4> <MemoizedFormattedMessage defaultMessage="Teams you can join: " id="signup_team.join_open" /> </h4> <LearnAboutTeamsLink /> </div> <InfiniteScroll bufferValue={280} callBack={[Function]} endOfDataMessage="" itemsPerPage={30} loaderStyle={ Object { "height": "40px", "padding": "0px", } } pageNumber={0} styleClass="signup-team-all" totalItems={15} > <div className="signup-team-dir-err" > <div> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MemoizedFormattedMessage defaultMessage="No teams are available to join. Please create a new team or ask your administrator for an invite." id="signup_team.no_open_teams_canCreate" /> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) invert={true} permissions={ Array [ "create_team", ] } > <MemoizedFormattedMessage defaultMessage="No teams are available to join. Please ask your administrator for an invite." id="signup_team.no_open_teams" /> </Connect(SystemPermissionGate)> </div> </div> </InfiniteScroll> </div> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <div className="margin--extra" style={ Object { "marginTop": "0.5em", } } > <Link className="signup-team-login" id="createNewTeamLink" onClick={[Function]} to="/create_team" > <MemoizedFormattedMessage defaultMessage="Create a team" id="login.createTeam" /> </Link> </div> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `; exports[`components/select_team/SelectTeam should match snapshot, on no joinable team and user is guest 1`] = ` <div> <Connect(Component) /> <BackButton url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <div className="signup__content" > <div className="form-group has-error" > <label className="control-label" > <MemoizedFormattedMessage defaultMessage="Your guest account has no channels assigned. Please contact an administrator." id="signup_team.guest_without_channels" /> </label> </div> </div> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <div className="margin--extra" style={ Object { "marginTop": "0.5em", } } > <Link className="signup-team-login" id="createNewTeamLink" onClick={[Function]} to="/create_team" > <MemoizedFormattedMessage defaultMessage="Create a team" id="login.createTeam" /> </Link> </div> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `; exports[`components/select_team/SelectTeam should match snapshot, on no joinable team but can create team 1`] = ` <div> <Connect(Component) /> <BackButton url="/" /> <div className="col-sm-12" > <div className="select-team__container signup-team__container" > <img alt="signup team logo" className="signup-team-logo" src={null} /> <Memo(SiteNameAndDescription) siteName="Mattermost" /> <div className="signup__content" id="teamsYouCanJoinContent" > <div className="SelectTeam__sub-header" > <h4> <MemoizedFormattedMessage defaultMessage="Teams you can join: " id="signup_team.join_open" /> </h4> <LearnAboutTeamsLink /> </div> <InfiniteScroll bufferValue={280} callBack={[Function]} endOfDataMessage="" itemsPerPage={30} loaderStyle={ Object { "height": "40px", "padding": "0px", } } pageNumber={0} styleClass="signup-team-all" totalItems={15} > <div className="signup-team-dir-err" > <div> <MemoizedFormattedMessage defaultMessage="No teams are available to join. Please create a new team or ask your administrator for an invite." id="signup_team.no_open_teams_canCreate" /> </div> </div> </InfiniteScroll> </div> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <div className="margin--extra" style={ Object { "marginTop": "0.5em", } } > <Link className="signup-team-login" id="createNewTeamLink" onClick={[Function]} to="/create_team" > <MemoizedFormattedMessage defaultMessage="Create a team" id="login.createTeam" /> </Link> </div> </Connect(SystemPermissionGate)> <Connect(SystemPermissionGate) permissions={ Array [ "manage_system", ] } > <div className="mt-8 hidden-xs" > <Link className="signup-team-login" onClick={[Function]} to="/admin_console" > <MemoizedFormattedMessage defaultMessage="Go to System Console" id="signup_team_system_console" /> </Link> </div> </Connect(SystemPermissionGate)> </div> </div> </div> `;
3,079
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team/components/select_team_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 {Team} from '@mattermost/types/teams'; import type {MockIntl} from 'tests/helpers/intl-test-helper'; import {SelectTeamItem} from './select_team_item'; describe('components/select_team/components/SelectTeamItem', () => { const baseProps = { team: {display_name: 'team_display_name', allow_open_invite: true} as Team, onTeamClick: jest.fn(), loading: false, canJoinPublicTeams: true, canJoinPrivateTeams: false, intl: { formatMessage: jest.fn(), } as MockIntl, }; test('should match snapshot, on public joinable', () => { const wrapper = shallow<SelectTeamItem>(<SelectTeamItem {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on public not joinable', () => { const props = {...baseProps, canJoinPublicTeams: false}; const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on private joinable', () => { const props = {...baseProps, team: {...baseProps.team, allow_open_invite: false}, canJoinPrivateTeams: true}; const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on private not joinable', () => { const props = {...baseProps, team: {...baseProps.team, allow_open_invite: false}}; const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on loading', () => { const props = {...baseProps, loading: true}; const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, with description', () => { const props = {...baseProps, team: {...baseProps.team, description: 'description'}}; const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should call props.onTeamClick on handleTeamClick', () => { const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...baseProps}/>, ); wrapper.instance().handleTeamClick({preventDefault: jest.fn()} as any); expect(baseProps.onTeamClick).toHaveBeenCalledTimes(1); expect(baseProps.onTeamClick).toHaveBeenCalledWith(baseProps.team); }); test('should not call props.onTeamClick on handleTeamClick when you cant join the team', () => { const props = {...baseProps, canJoinPublicTeams: false}; const wrapper = shallow<SelectTeamItem>( <SelectTeamItem {...props}/>, ); wrapper.instance().handleTeamClick({preventDefault: jest.fn()} as any); expect(baseProps.onTeamClick).toHaveBeenCalledTimes(1); expect(baseProps.onTeamClick).toHaveBeenCalledWith(baseProps.team); }); });
3,081
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/select_team/components/__snapshots__/select_team_item.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/select_team/components/SelectTeamItem should match snapshot, on loading 1`] = ` <div className="signup-team-dir" > <a className="" href="#" id="team_display_name" onClick={[Function]} > <span className="signup-team-dir__name" > team_display_name </span> <span className="fa fa-refresh fa-spin right signup-team__icon" /> </a> </div> `; exports[`components/select_team/components/SelectTeamItem should match snapshot, on private joinable 1`] = ` <div className="signup-team-dir" > <a className="" href="#" id="team_display_name" onClick={[Function]} > <span className="signup-team-dir__name" > team_display_name </span> <i className="fa fa-lock light" /> <span className="fa fa-angle-right right signup-team__icon" /> </a> </div> `; exports[`components/select_team/components/SelectTeamItem should match snapshot, on private not joinable 1`] = ` <div className="signup-team-dir" > <a className="disabled" href="#" id="team_display_name" > <span className="signup-team-dir__name" > team_display_name </span> <i className="fa fa-lock light" /> </a> </div> `; exports[`components/select_team/components/SelectTeamItem should match snapshot, on public joinable 1`] = ` <div className="signup-team-dir" > <a className="" href="#" id="team_display_name" onClick={[Function]} > <span className="signup-team-dir__name" > team_display_name </span> <span className="fa fa-angle-right right signup-team__icon" /> </a> </div> `; exports[`components/select_team/components/SelectTeamItem should match snapshot, on public not joinable 1`] = ` <div className="signup-team-dir" > <a className="disabled" href="#" id="team_display_name" > <span className="signup-team-dir__name" > team_display_name </span> </a> </div> `; exports[`components/select_team/components/SelectTeamItem should match snapshot, with description 1`] = ` <div className="signup-team-dir" > <OverlayTrigger container={ SelectTeamItem { "context": Object {}, "handleTeamClick": [Function], "props": Object { "canJoinPrivateTeams": false, "canJoinPublicTeams": true, "intl": Object { "formatMessage": [MockFunction] { "calls": Array [ Array [ Object { "defaultMessage": "Join Team Icon", "id": "select_team.join.icon", }, ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, }, "loading": false, "onTeamClick": [MockFunction], "team": Object { "allow_open_invite": true, "description": "description", "display_name": "team_display_name", }, }, "refs": Object {}, "renderDescriptionTooltip": [Function], "setState": [Function], "state": null, "updater": Updater { "_callbacks": Array [], "_renderer": ReactShallowRenderer { "_context": Object {}, "_didScheduleRenderPhaseUpdate": false, "_dispatcher": Object { "readContext": [Function], "useCallback": [Function], "useContext": [Function], "useDebugValue": [Function], "useDeferredValue": [Function], "useEffect": [Function], "useId": [Function], "useImperativeHandle": [Function], "useInsertionEffect": [Function], "useLayoutEffect": [Function], "useMemo": [Function], "useReducer": [Function], "useRef": [Function], "useResponder": [Function], "useState": [Function], "useSyncExternalStore": [Function], "useTransition": [Function], }, "_element": <SelectTeamItem canJoinPrivateTeams={false} canJoinPublicTeams={true} intl={ Object { "formatMessage": [MockFunction] { "calls": Array [ Array [ Object { "defaultMessage": "Join Team Icon", "id": "select_team.join.icon", }, ], ], "results": Array [ Object { "type": "return", "value": undefined, }, ], }, } } loading={false} onTeamClick={[MockFunction]} team={ Object { "allow_open_invite": true, "description": "description", "display_name": "team_display_name", } } />, "_firstWorkInProgressHook": null, "_forcedUpdate": false, "_idCounter": 0, "_instance": [Circular], "_isReRender": false, "_newState": null, "_numberOfReRenders": 0, "_renderPhaseUpdates": null, "_rendered": <div className="signup-team-dir" > <OverlayTrigger container={[Circular]} defaultOverlayShown={false} delayShow={1000} overlay={ <Tooltip id="team-description__tooltip" > description </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <TeamInfoIcon className="icon icon--info" /> </OverlayTrigger> <a className="" href="#" id="team_display_name" onClick={[Function]} > <span className="signup-team-dir__name" > team_display_name </span> <span className="fa fa-angle-right right signup-team__icon" /> </a> </div>, "_rendering": false, "_updater": [Circular], "_workInProgressHook": null, }, }, } } defaultOverlayShown={false} delayShow={1000} overlay={ <Tooltip id="team-description__tooltip" > description </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <TeamInfoIcon className="icon icon--info" /> </OverlayTrigger> <a className="" href="#" id="team_display_name" onClick={[Function]} > <span className="signup-team-dir__name" > team_display_name </span> <span className="fa fa-angle-right right signup-team__icon" /> </a> </div> `;
3,090
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/self_hosted_purchases
petrpan-code/mattermost/mattermost/webapp/channels/src/components/self_hosted_purchases/self_hosted_expansion_modal/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import moment from 'moment-timezone'; import React from 'react'; import {SelfHostedSignupProgress} from '@mattermost/types/hosted_customer'; import type {SelfHostedSignupForm} from '@mattermost/types/hosted_customer'; import type {DeepPartial} from '@mattermost/types/utilities'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import { fireEvent, renderWithContext, screen, waitFor, } from 'tests/react_testing_utils'; import {SelfHostedProducts, ModalIdentifiers, RecurringIntervals} from 'utils/constants'; import {TestHelper as TH} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import SelfHostedExpansionModal, {makeInitialState, canSubmit} from './'; import type {FormState} from './'; interface MockCardInputProps { onCardInputChange: (event: {complete: boolean}) => void; forwardedRef: React.MutableRefObject<any>; } // number borrowed from stripe const successCardNumber = '4242424242424242'; function MockCardInput(props: MockCardInputProps) { props.forwardedRef.current = { getCard: () => ({}), }; return ( <input placeholder='Card number' type='text' onChange={(e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.value === successCardNumber) { props.onCardInputChange({complete: true}); } }} /> ); } jest.mock('components/payment_form/card_input', () => { const original = jest.requireActual('components/payment_form/card_input'); return { ...original, __esModule: true, default: MockCardInput, }; }); jest.mock('components/self_hosted_purchases/stripe_provider', () => { return function(props: {children: React.ReactNode | React.ReactNodeArray}) { return props.children; }; }); jest.mock('components/common/hooks/useLoadStripe', () => { return function() { return {current: { stripe: {}, }}; }; }); const mockCreatedIntent = SelfHostedSignupProgress.CREATED_INTENT; const mockCreatedLicense = SelfHostedSignupProgress.CREATED_LICENSE; const failOrg = 'failorg'; const existingUsers = 10; const mockProfessionalProduct = TH.getProductMock({ id: 'prod_professional', name: 'Professional', sku: SelfHostedProducts.PROFESSIONAL, price_per_seat: 7.5, recurring_interval: RecurringIntervals.MONTH, }); jest.mock('mattermost-redux/client', () => { const original = jest.requireActual('mattermost-redux/client'); return { __esModule: true, ...original, Client4: { ...original.Client4, pageVisited: jest.fn(), setAcceptLanguage: jest.fn(), trackEvent: jest.fn(), createCustomerSelfHostedSignup: (form: SelfHostedSignupForm) => { if (form.organization === failOrg) { throw new Error('error creating customer'); } return Promise.resolve({ progress: mockCreatedIntent, }); }, confirmSelfHostedExpansion: () => Promise.resolve({ progress: mockCreatedLicense, license: {Users: existingUsers * 2}, }), }, }; }); jest.mock('components/payment_form/stripe', () => { const original = jest.requireActual('components/payment_form/stripe'); return { __esModule: true, ...original, getConfirmCardSetup: () => () => () => ({setupIntent: {status: 'succeeded'}, error: null}), }; }); jest.mock('utils/hosted_customer', () => { const original = jest.requireActual('utils/hosted_customer'); return { __esModule: true, ...original, findSelfHostedProductBySku: () => { return mockProfessionalProduct; }, }; }); const productName = SelfHostedProducts.PROFESSIONAL; // Licensed expiry set as 3 months from the current date (rolls over to new years). let licenseExpiry = moment(); const monthsUntilLicenseExpiry = 3; licenseExpiry = licenseExpiry.add(monthsUntilLicenseExpiry, 'months'); const initialState: DeepPartial<GlobalState> = { views: { modals: { modalState: { [ModalIdentifiers.SELF_HOSTED_EXPANSION]: { open: true, }, }, }, }, storage: { storage: {}, }, entities: { teams: { currentTeamId: '', }, preferences: { myPreferences: { theme: {}, }, }, general: { config: { EnableDeveloper: 'false', }, license: { SkuName: productName, Sku: productName, Users: '50', ExpiresAt: licenseExpiry.valueOf().toString(), }, }, cloud: { subscription: {}, }, users: { currentUserId: 'adminUserId', profiles: { adminUserId: TH.getUserMock({ id: 'adminUserId', roles: 'admin', first_name: 'first', last_name: 'admin', }), otherUserId: TH.getUserMock({ id: 'otherUserId', roles: '', first_name: '', last_name: '', }), }, filteredStats: { total_users_count: 100, }, }, hostedCustomer: { products: { productsLoaded: true, products: { prod_professional: mockProfessionalProduct, }, }, signupProgress: SelfHostedSignupProgress.START, }, }, }; const valueEvent = (value: any) => ({target: {value}}); function changeByPlaceholder(sel: string, val: any) { fireEvent.change(screen.getByPlaceholderText(sel), valueEvent(val)); } function selectDropdownValue(testId: string, value: string) { fireEvent.change(screen.getByTestId(testId).querySelector('input') as any, valueEvent(value)); fireEvent.click(screen.getByTestId(testId).querySelector('.DropDown__option--is-focused') as any); } function changeByTestId(testId: string, value: string) { fireEvent.change(screen.getByTestId(testId).querySelector('input') as any, valueEvent(value)); } interface PurchaseForm { card: string; org: string; name: string; country: string; address: string; city: string; state: string; zip: string; seats: string; agree: boolean; } const defaultSuccessForm: PurchaseForm = { card: successCardNumber, org: 'My org', name: 'The Cardholder', country: 'United States of America', address: '123 Main Street', city: 'Minneapolis', state: 'MN', zip: '55423', seats: '50', agree: true, }; function fillForm(form: PurchaseForm) { changeByPlaceholder('Card number', form.card); changeByPlaceholder('Organization Name', form.org); changeByPlaceholder('Name on Card', form.name); selectDropdownValue('selfHostedExpansionCountrySelector', form.country); changeByPlaceholder('Address', form.address); changeByPlaceholder('City', form.city); selectDropdownValue('selfHostedExpansionStateSelector', form.state); changeByPlaceholder('Zip/Postal Code', form.zip); if (form.agree) { fireEvent.click(screen.getByText('I have read and agree', {exact: false})); } const completeButton = screen.getByText('Complete purchase'); if (form === defaultSuccessForm) { expect(completeButton).toBeEnabled(); } return completeButton; } describe('SelfHostedExpansionModal Open', () => { it('renders the form', () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); screen.getByText('Provide your payment details'); screen.getByText('Add new seats'); screen.getByText('Contact Sales'); screen.getByText('Cost per user', {exact: false}); // screen.getByText(productName, {normalizer: (val) => {return val.charAt(0).toUpperCase() + val.slice(1)}}); screen.getByText('Your credit card will be charged today.'); screen.getByText('See how billing works', {exact: false}); }); it('filling the form enables expansion', () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); expect(screen.getByText('Complete purchase')).toBeDisabled(); fillForm(defaultSuccessForm); }); it('happy path submit shows success screen when confirmation succeeds', async () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); expect(screen.getByText('Complete purchase')).toBeDisabled(); const upgradeButton = fillForm(defaultSuccessForm); upgradeButton.click(); expect(screen.findByText('The license has been automatically applied')).toBeTruthy(); }); it('happy path submit shows submitting screen while requesting confirmation', async () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); expect(screen.getByText('Complete purchase')).toBeDisabled(); const upgradeButton = fillForm(defaultSuccessForm); upgradeButton.click(); await waitFor(() => expect(document.getElementsByClassName('submitting')[0]).toBeTruthy(), {timeout: 1234}); }); it('sad path submit shows error screen', async () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); expect(screen.getByText('Complete purchase')).toBeDisabled(); fillForm(defaultSuccessForm); changeByPlaceholder('Organization Name', failOrg); const upgradeButton = screen.getByText('Complete purchase'); expect(upgradeButton).toBeEnabled(); upgradeButton.click(); await waitFor(() => expect(screen.getByText('Sorry, the payment verification failed')).toBeTruthy(), {timeout: 1234}); }); }); describe('SelfHostedExpansionModal RHS Card', () => { it('New seats input should be pre-populated with the difference from the active users and licensed seats', () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); const expectedPrePopulatedSeats = (initialState.entities?.users?.filteredStats?.total_users_count || 1) - parseInt(initialState.entities?.general?.license?.Users || '1', 10); const seatsField = screen.getByTestId('seatsInput').querySelector('input'); expect(seatsField).toBeInTheDocument(); expect(seatsField?.value).toBe(expectedPrePopulatedSeats.toString()); }); it('Seat input only allows users to fill input with the licensed seats and active users difference if it is not 0', () => { const expectedUserOverage = '50'; renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); fillForm(defaultSuccessForm); // The seat input should already have the expected value. expect(screen.getByTestId('seatsInput').querySelector('input')?.value).toContain(expectedUserOverage); // Try to set an undefined value. fireEvent.change(screen.getByTestId('seatsInput').querySelector('input') as HTMLElement, undefined); // Expecting the seats input to now contain the difference between active users and licensed seats. expect(screen.getByTestId('seatsInput').querySelector('input')?.value).toContain(expectedUserOverage); expect(screen.getByText('Complete purchase')).toBeEnabled(); }); it('New seats input cannot be less than 1', () => { const state = mergeObjects(initialState, { entities: { users: { filteredStats: { total_users_count: 50, }, }, }, }); const expectedAddNewSeats = '1'; renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, state); fillForm(defaultSuccessForm); // Try to set a negative value. fireEvent.change(screen.getByTestId('seatsInput').querySelector('input') as HTMLElement, -10); expect(screen.getByTestId('seatsInput').querySelector('input')?.value).toContain(expectedAddNewSeats); // Try to set a 0 value. fireEvent.change(screen.getByTestId('seatsInput').querySelector('input') as HTMLElement, 0); expect(screen.getByTestId('seatsInput').querySelector('input')?.value).toContain(expectedAddNewSeats); }); it('Cost per User should be represented as the current subscription price multiplied by the remaining months', () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); const expectedCostPerUser = monthsUntilLicenseExpiry * mockProfessionalProduct.price_per_seat; const costPerUser = document.getElementsByClassName('costPerUser')[0]; expect(costPerUser).toBeInTheDocument(); expect(costPerUser.innerHTML).toContain('Cost per user<br>$' + mockProfessionalProduct.price_per_seat.toFixed(2) + ' x ' + monthsUntilLicenseExpiry + ' months'); const costAmount = document.getElementsByClassName('costAmount')[0]; expect(costAmount).toBeInTheDocument(); expect(costAmount.innerHTML).toContain('$' + expectedCostPerUser); }); it('Total cost User should be represented as the current subscription price multiplied by the remaining months multiplied by the number of users', () => { renderWithContext(<div id='root-portal'><SelfHostedExpansionModal/></div>, initialState); const seatsInputValue = 100; changeByTestId('seatsInput', seatsInputValue.toString()); const expectedTotalCost = monthsUntilLicenseExpiry * mockProfessionalProduct.price_per_seat * seatsInputValue; const costAmount = document.getElementsByClassName('totalCostAmount')[0]; expect(costAmount).toBeInTheDocument(); expect(costAmount).toHaveTextContent(Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(expectedTotalCost)); }); }); describe('SelfHostedExpansionModal Submit', () => { function makeHappyPathState(): FormState { return { address: 'string', address2: 'string', city: 'string', state: 'string', country: 'string', postalCode: '12345', shippingAddress: 'string', shippingAddress2: 'string', shippingCity: 'string', shippingState: 'string', shippingCountry: 'string', shippingPostalCode: '12345', shippingSame: false, agreedTerms: true, cardName: 'string', organization: 'string', cardFilled: true, seats: 1, submitting: false, succeeded: false, progressBar: 0, error: '', }; } it('if submitting, can not submit again', () => { const state = makeHappyPathState(); state.submitting = true; expect(canSubmit(state, SelfHostedSignupProgress.CREATED_LICENSE)).toBe(false); }); it('if created license, can submit', () => { const state = makeInitialState(1); state.submitting = false; expect(canSubmit(state, SelfHostedSignupProgress.CREATED_LICENSE)).toBe(true); }); it('if paid, can submit', () => { const state = makeInitialState(1); state.submitting = false; expect(canSubmit(state, SelfHostedSignupProgress.PAID)).toBe(true); }); it('if created subscription, can submit', () => { const state = makeInitialState(1); state.submitting = false; expect(canSubmit(state, SelfHostedSignupProgress.CREATED_SUBSCRIPTION)).toBe(true); }); it('if all details filled and card has not been confirmed, can submit', () => { const state = makeHappyPathState(); expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(true); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(true); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(true); }); it('if card name missing and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.cardName = ''; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if card number missing and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.cardFilled = false; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if address not filled and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.address = ''; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if seats not valid and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.seats = 0; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if card confirmed, card not required for submission', () => { const state = makeHappyPathState(); state.cardFilled = false; state.cardName = ''; expect(canSubmit(state, SelfHostedSignupProgress.CONFIRMED_INTENT)).toBe(true); }); it('if passed unknown progress status, can not submit', () => { const state = makeHappyPathState(); expect(canSubmit(state, 'unknown status' as any)).toBe(false); }); });
3,098
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/self_hosted_purchases
petrpan-code/mattermost/mattermost/webapp/channels/src/components/self_hosted_purchases/self_hosted_purchase_modal/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {SelfHostedSignupProgress} from '@mattermost/types/hosted_customer'; import type {SelfHostedSignupForm} from '@mattermost/types/hosted_customer'; import type {DeepPartial} from '@mattermost/types/utilities'; import { fireEvent, renderWithContext, screen, waitFor, } from 'tests/react_testing_utils'; import {SelfHostedProducts, ModalIdentifiers} from 'utils/constants'; import {TestHelper as TH} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import SelfHostedPurchaseModal, {makeInitialState, canSubmit} from '.'; import type {State} from '.'; interface MockCardInputProps { onCardInputChange: (event: {complete: boolean}) => void; forwardedRef: React.MutableRefObject<any>; } // number borrowed from stripe const successCardNumber = '4242424242424242'; function MockCardInput(props: MockCardInputProps) { props.forwardedRef.current = { getCard: () => ({}), }; return ( <input placeholder='Card number' type='text' onChange={(e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.value === successCardNumber) { props.onCardInputChange({complete: true}); } }} /> ); } jest.mock('components/payment_form/card_input', () => { const original = jest.requireActual('components/payment_form/card_input'); return { ...original, __esModule: true, default: MockCardInput, }; }); jest.mock('components/self_hosted_purchases/stripe_provider', () => { return function(props: {children: React.ReactNode | React.ReactNodeArray}) { return props.children; }; }); jest.mock('components/common/hooks/useLoadStripe', () => { return function() { return {current: { stripe: {}, }}; }; }); const mockCreatedIntent = SelfHostedSignupProgress.CREATED_INTENT; const mockCreatedLicense = SelfHostedSignupProgress.CREATED_LICENSE; const failOrg = 'failorg'; const existingUsers = 11; jest.mock('mattermost-redux/client', () => { const original = jest.requireActual('mattermost-redux/client'); return { __esModule: true, ...original, Client4: { ...original.Client4, pageVisited: jest.fn(), setAcceptLanguage: jest.fn(), trackEvent: jest.fn(), createCustomerSelfHostedSignup: (form: SelfHostedSignupForm) => { if (form.organization === failOrg) { throw new Error('error creating customer'); } return Promise.resolve({ progress: mockCreatedIntent, }); }, confirmSelfHostedSignup: () => Promise.resolve({ progress: mockCreatedLicense, license: {Users: existingUsers * 2}, }), getClientLicenseOld: () => Promise.resolve({ data: {Sku: 'Enterprise'}, }), }, }; }); jest.mock('components/payment_form/stripe', () => { const original = jest.requireActual('components/payment_form/stripe'); return { __esModule: true, ...original, getConfirmCardSetup: () => () => () => ({setupIntent: {status: 'succeeded'}, error: null}), }; }); const productName = 'Professional'; const initialState: DeepPartial<GlobalState> = { views: { modals: { modalState: { [ModalIdentifiers.SELF_HOSTED_PURCHASE]: { open: true, }, }, }, }, storage: { storage: {}, }, entities: { admin: { analytics: { TOTAL_USERS: existingUsers, }, }, teams: { currentTeamId: '', }, preferences: { myPreferences: { theme: {}, }, }, general: { config: { EnableDeveloper: 'false', }, license: { Sku: 'Enterprise', }, }, cloud: { subscription: {}, }, users: { currentUserId: 'adminUserId', profiles: { adminUserId: TH.getUserMock({ id: 'adminUserId', roles: 'admin', first_name: 'first', last_name: 'admin', }), otherUserId: TH.getUserMock({ id: 'otherUserId', roles: '', first_name: '', last_name: '', }), }, }, hostedCustomer: { products: { productsLoaded: true, products: { prod_professional: TH.getProductMock({ id: 'prod_professional', name: 'Professional', sku: SelfHostedProducts.PROFESSIONAL, price_per_seat: 7.5, }), }, }, signupProgress: SelfHostedSignupProgress.START, }, }, }; const valueEvent = (value: any) => ({target: {value}}); function changeByPlaceholder(sel: string, val: any) { fireEvent.change(screen.getByPlaceholderText(sel), valueEvent(val)); } // having issues with normal selection of texts and clicks. function selectDropdownValue(testId: string, value: string) { fireEvent.change(screen.getByTestId(testId).querySelector('input') as any, valueEvent(value)); fireEvent.click(screen.getByTestId(testId).querySelector('.DropDown__option--is-focused') as any); } interface PurchaseForm { card: string; org: string; name: string; country: string; address: string; city: string; state: string; zip: string; agree: boolean; } const defaultSuccessForm: PurchaseForm = { card: successCardNumber, org: 'My org', name: 'The Cardholder', country: 'United States of America', address: '123 Main Street', city: 'Minneapolis', state: 'MN', zip: '55423', agree: true, }; function fillForm(form: PurchaseForm) { changeByPlaceholder('Card number', form.card); changeByPlaceholder('Organization Name', form.org); changeByPlaceholder('Name on Card', form.name); selectDropdownValue('selfHostedPurchaseCountrySelector', form.country); changeByPlaceholder('Address', form.address); changeByPlaceholder('City', form.city); selectDropdownValue('selfHostedPurchaseStateSelector', form.state); changeByPlaceholder('Zip/Postal Code', form.zip); if (form.agree) { fireEvent.click(screen.getByText('I have read and agree', {exact: false})); } // not changing the license seats number, // because it is expected to be pre-filled with the correct number of seats. const upgradeButton = screen.getByText('Upgrade'); // while this will will not if the caller passes in an object // that has member equality but not reference equality, this is // good enough for the limited usage this function has if (form === defaultSuccessForm) { expect(upgradeButton).toBeEnabled(); } return upgradeButton; } describe('SelfHostedPurchaseModal', () => { it('renders the form', () => { renderWithContext(<div id='root-portal'><SelfHostedPurchaseModal productId={'prod_professional'}/></div>, initialState); // check title, and some of the most prominent details and secondary actions screen.getByText('Provide your payment details'); screen.getByText('Contact Sales'); screen.getByText('USD per seat/month', {exact: false}); screen.getByText('billed annually', {exact: false}); screen.getByText(productName); screen.getByText('You will be billed today. Your license will be applied automatically', {exact: false}); screen.getByText('See how billing works', {exact: false}); }); it('filling the form enables signup', () => { renderWithContext(<div id='root-portal'><SelfHostedPurchaseModal productId={'prod_professional'}/></div>, initialState); expect(screen.getByText('Upgrade')).toBeDisabled(); fillForm(defaultSuccessForm); }); it('disables signup if too few seats chosen', () => { renderWithContext(<div id='root-portal'><SelfHostedPurchaseModal productId={'prod_professional'}/></div>, initialState); fillForm(defaultSuccessForm); const tooFewSeats = existingUsers - 1; fireEvent.change(screen.getByTestId('selfHostedPurchaseSeatsInput'), valueEvent(tooFewSeats.toString())); expect(screen.getByText('Upgrade')).toBeDisabled(); screen.getByText('Your workspace currently has 11 users', {exact: false}); }); it('Minimum of 10 seats is required for sign up', () => { renderWithContext(<div id='root-portal'><SelfHostedPurchaseModal productId={'prod_professional'}/></div>, initialState); fillForm(defaultSuccessForm); const tooFewSeats = 9; fireEvent.change(screen.getByTestId('selfHostedPurchaseSeatsInput'), valueEvent(tooFewSeats.toString())); expect(screen.getByText('Upgrade')).toBeDisabled(); screen.getByText('Minimum of 10 seats required', {exact: false}); }); it('happy path submit shows success screen', async () => { renderWithContext(<div id='root-portal'><SelfHostedPurchaseModal productId={'prod_professional'}/></div>, initialState); expect(screen.getByText('Upgrade')).toBeDisabled(); const upgradeButton = fillForm(defaultSuccessForm); upgradeButton.click(); await waitFor(() => expect(screen.getByText(`You're now subscribed to ${productName}`)).toBeTruthy(), {timeout: 1234}); }); it('sad path submit shows error screen', async () => { renderWithContext(<div id='root-portal'><SelfHostedPurchaseModal productId={'prod_professional'}/></div>, initialState); expect(screen.getByText('Upgrade')).toBeDisabled(); fillForm(defaultSuccessForm); changeByPlaceholder('Organization Name', failOrg); const upgradeButton = screen.getByText('Upgrade'); expect(upgradeButton).toBeEnabled(); upgradeButton.click(); await waitFor(() => expect(screen.getByText('Sorry, the payment verification failed')).toBeTruthy(), {timeout: 1234}); }); }); describe('SelfHostedPurchaseModal :: canSubmit', () => { function makeHappyPathState(): State { return { address: 'string', address2: 'string', city: 'string', state: 'string', country: 'string', postalCode: '12345', shippingSame: true, shippingAddress: '', shippingAddress2: '', shippingCity: '', shippingState: '', shippingCountry: '', shippingPostalCode: '', cardName: 'string', organization: 'string', agreedTerms: true, cardFilled: true, seats: { quantity: '12', error: null, }, submitting: false, succeeded: false, progressBar: 0, error: '', }; } it('if submitting, can not submit', () => { const state = makeHappyPathState(); state.submitting = true; expect(canSubmit(state, SelfHostedSignupProgress.CREATED_LICENSE)).toBe(false); }); it('if created license, can submit', () => { const state = makeInitialState(); state.submitting = false; expect(canSubmit(state, SelfHostedSignupProgress.CREATED_LICENSE)).toBe(true); }); it('if paid, can submit', () => { const state = makeInitialState(); state.submitting = false; expect(canSubmit(state, SelfHostedSignupProgress.PAID)).toBe(true); }); it('if created subscription, can submit', () => { const state = makeInitialState(); state.submitting = false; expect(canSubmit(state, SelfHostedSignupProgress.CREATED_SUBSCRIPTION)).toBe(true); }); it('if all details filled and card has not been confirmed, can submit', () => { const state = makeHappyPathState(); expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(true); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(true); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(true); }); it('if card name missing and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.cardName = ''; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if shipping address different and is not filled, can not submit', () => { const state = makeHappyPathState(); state.shippingSame = false; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); state.shippingAddress = 'more shipping info'; state.shippingAddress2 = 'more shipping info'; state.shippingCity = 'more shipping info'; state.shippingState = 'more shipping info'; state.shippingCountry = 'more shipping info'; state.shippingPostalCode = 'more shipping info'; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(true); }); it('if card number missing and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.cardFilled = false; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if address not filled and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.address = ''; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if seats not valid and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.seats.error = 'some seats error'; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if did not agree to terms and card has not been confirmed, can not submit', () => { const state = makeHappyPathState(); state.agreedTerms = false; expect(canSubmit(state, SelfHostedSignupProgress.START)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_CUSTOMER)).toBe(false); expect(canSubmit(state, SelfHostedSignupProgress.CREATED_INTENT)).toBe(false); }); it('if card confirmed, card not required for submission', () => { const state = makeHappyPathState(); state.cardFilled = false; state.cardName = ''; expect(canSubmit(state, SelfHostedSignupProgress.CONFIRMED_INTENT)).toBe(true); }); it('if passed unknown progress status, can not submit', () => { const state = makeHappyPathState(); expect(canSubmit(state, 'unknown status' as any)).toBe(false); }); });
3,112
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/shortcut_key/shortcut_key.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 {ShortcutKey, ShortcutKeyVariant} from './shortcut_key'; describe('components/ShortcutKey', () => { test('should match snapshot for regular key', () => { const wrapper = shallow(<ShortcutKey>{'Shift'}</ShortcutKey>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for contrast key', () => { const wrapper = shallow(<ShortcutKey variant={ShortcutKeyVariant.Contrast}>{'Shift'}</ShortcutKey>); expect(wrapper).toMatchSnapshot(); }); });
3,114
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/shortcut_key
petrpan-code/mattermost/mattermost/webapp/channels/src/components/shortcut_key/__snapshots__/shortcut_key.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ShortcutKey should match snapshot for contrast key 1`] = ` <mark className="shortcut-key shortcut-key--contrast" > Shift </mark> `; exports[`components/ShortcutKey should match snapshot for regular key 1`] = ` <mark className="shortcut-key" > Shift </mark> `;
3,118
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/add_channels_cta_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 type {UsersState} from '@mattermost/types/users'; import Permissions from 'mattermost-redux/constants/permissions'; import {trackEvent} from 'actions/telemetry_actions.jsx'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import type {GlobalState} from 'types/store'; import AddChannelsCtaButton from './add_channels_cta_button'; jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); const mockDispatch = jest.fn(); let mockState: GlobalState; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); describe('components/new_channel_modal', () => { beforeEach(() => { mockState = { entities: { general: { config: {}, }, channels: { currentChannelId: 'current_channel_id', channels: {}, roles: { current_channel_id: [ 'channel_user', 'channel_admin', ], }, }, teams: { currentTeamId: 'current_team_id', myMembers: { current_team_id: { roles: 'team_user team_admin', }, }, teams: { current_team_id: { id: 'current_team_id', description: 'Curent team description', name: 'current-team', }, }, }, preferences: { myPreferences: {}, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_user'}, }, }, roles: { roles: { guest_user: { permissions: [], }, system_user: { permissions: [Permissions.JOIN_PUBLIC_CHANNELS, Permissions.CREATE_PRIVATE_CHANNEL, Permissions.CREATE_PUBLIC_CHANNEL], }, system_user_join_permissions: { permissions: [Permissions.JOIN_PUBLIC_CHANNELS], }, system_user_create_public_permissions: { permissions: [Permissions.JOIN_PUBLIC_CHANNELS, Permissions.CREATE_PUBLIC_CHANNEL], }, }, }, }, views: { addChannelCtaDropdown: { isOpen: false, }, }, } as unknown as GlobalState; }); test('should match snapshot', () => { expect( shallow( <AddChannelsCtaButton/>, ), ).toMatchSnapshot(); }); test('should match snapshot when user has only join channel permissions', () => { const userWithJoinChannelsPermission = { currentUserId: 'current_user_id', profiles: { current_user_id: { id: 'current_user_id', roles: 'system_user_join_permissions', }, }, } as unknown as UsersState; mockState = {...mockState, entities: {...mockState.entities, users: userWithJoinChannelsPermission}}; expect( shallow( <AddChannelsCtaButton/>, ), ).toMatchSnapshot(); }); test('should find the add channels button when user has permissions', () => { const wrapper = mountWithIntl( <AddChannelsCtaButton/>, ); expect(wrapper.find('.AddChannelsCtaDropdown').exists()).toBeTruthy(); }); test('should return nothing when user does not have permissions', () => { const guestUser = { currentUserId: 'guest_user_id', profiles: { user_id: { id: 'guest_user_id', roles: 'team_role', }, }, } as unknown as UsersState; mockState = {...mockState, entities: {...mockState.entities, users: guestUser}}; const wrapper = mountWithIntl( <AddChannelsCtaButton/>, ); expect(wrapper.find('.AddChannelsCtaDropdown').exists()).toBeFalsy(); }); test('should fire dispatch to save preferences when button is clicked', () => { const wrapper = mountWithIntl( <AddChannelsCtaButton/>, ); const button = wrapper.find('.AddChannelsCtaDropdown button'); expect(mockDispatch).not.toHaveBeenCalled(); button.simulate('click'); expect(mockDispatch).toHaveBeenCalled(); }); test('should fire trackEvent to send telemetry when button is clicked', () => { const wrapper = mountWithIntl( <AddChannelsCtaButton/>, ); const button = wrapper.find('.AddChannelsCtaDropdown button'); expect(mockDispatch).not.toHaveBeenCalled(); button.simulate('click'); expect(trackEvent).toHaveBeenCalledWith('ui', 'add_channels_cta_button_clicked'); }); test('should not display as a Cta Dropdown when user only has permissions to join channels ', () => { const userWithJoinChannelsPermission = { currentUserId: 'current_user_id', profiles: { current_user_id: { id: 'current_user_id', roles: 'system_user_join_permissions', }, }, } as unknown as UsersState; mockState = {...mockState, entities: {...mockState.entities, users: userWithJoinChannelsPermission}}; const wrapper = mountWithIntl( <AddChannelsCtaButton/>, ); // do not find the menu expect(wrapper.find('.AddChannelsCtaDropdown').exists()).toBeFalsy(); // only find the button const button = wrapper.find('button#addChannelsCta'); expect(button.exists()).toBeTruthy(); button.simulate('click'); // when clicked show the browse channels modal expect(trackEvent).toHaveBeenCalledWith('ui', 'browse_channels_button_is_clicked'); }); test('should still display as a Cta Dropdown when user has permissions to create at least one form of channel', () => { const userWithJoinChannelsPermission = { currentUserId: 'current_user_id', profiles: { current_user_id: { id: 'current_user_id', roles: 'system_user_create_public_permissions', }, }, } as unknown as UsersState; mockState = {...mockState, entities: {...mockState.entities, users: userWithJoinChannelsPermission}}; const wrapper = mountWithIntl( <AddChannelsCtaButton/>, ); expect(wrapper.find('.AddChannelsCtaDropdown').exists()).toBeTruthy(); }); });
3,121
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/invite_members_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Provider} from 'react-redux'; import * as teams from 'mattermost-redux/selectors/entities/teams'; import InviteMembersButton from 'components/sidebar/invite_members_button'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; describe('components/sidebar/invite_members_button', () => { // required state to mount using the provider const state = { entities: { general: { config: { FeatureFlagInviteMembersButton: 'user_icon', }, }, teams: { teams: { team_id: {id: 'team_id', delete_at: 0}, team_id2: {id: 'team_id2', delete_at: 0}, }, myMembers: { team_id: {team_id: 'team_id', roles: 'team_role'}, team_id2: {team_id: 'team_id2', roles: 'team_role2'}, }, }, users: { currentUserId: 'user_id', profiles: { user_id: { id: 'user_id', roles: 'system_role', }, }, stats: { total_users_count: 10, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission', 'add_user_to_team', 'invite_guest']}, team_role: {permissions: ['test_team_no_permission']}, }, }, }, }; const props = { isAdmin: false, }; const store = mockStore(state); jest.spyOn(teams, 'getCurrentTeamId').mockReturnValue('team_id2sss'); test('should match snapshot', () => { const wrapper = mountWithIntl( <Provider store={store}> <InviteMembersButton {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should return nothing when user does not have permissions', () => { const guestUser = { currentUserId: 'guest_user_id', profiles: { user_id: { id: 'guest_user_id', roles: 'team_role', }, }, }; const noPermissionsState = {...state, entities: {...state.entities, users: guestUser}}; const store = mockStore(noPermissionsState); const wrapper = mountWithIntl( <Provider store={store}> <InviteMembersButton {...props}/> </Provider>, ); expect(wrapper.find('i').exists()).toBeFalsy(); }); });
3,123
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar.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 {DeepPartial} from '@mattermost/types/utilities'; import {Preferences} from 'mattermost-redux/constants'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import Constants, {ModalIdentifiers} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import Sidebar from './sidebar'; describe('components/sidebar', () => { const currentTeamId = 'fake_team_id'; const baseProps = { canCreatePublicChannel: true, canCreatePrivateChannel: true, canJoinPublicChannel: true, isOpen: false, teamId: currentTeamId, hasSeenModal: true, isCloud: false, unreadFilterEnabled: false, isMobileView: false, isKeyBoardShortcutModalOpen: false, userGroupsEnabled: false, canCreateCustomGroups: true, actions: { createCategory: jest.fn(), fetchMyCategories: jest.fn(), openModal: jest.fn(), closeModal: jest.fn(), clearChannelSelection: jest.fn(), closeRightHandSide: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <Sidebar {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when direct channels modal is open', () => { const wrapper = shallow( <Sidebar {...baseProps}/>, ); wrapper.instance().setState({showDirectChannelsModal: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when more channels modal is open', () => { const wrapper = shallow( <Sidebar {...baseProps}/>, ); wrapper.instance().setState({showMoreChannelsModal: true}); expect(wrapper).toMatchSnapshot(); }); test('Should call Shortcut modal on FORWARD_SLASH+ctrl/meta', () => { const wrapper = shallow<Sidebar>( <Sidebar {...baseProps}/>, ); const instance = wrapper.instance(); let key = Constants.KeyCodes.BACK_SLASH[0] as string; let keyCode = Constants.KeyCodes.BACK_SLASH[1] as number; instance.handleKeyDownEvent({ctrlKey: true, preventDefault: jest.fn(), key, keyCode} as any); expect(wrapper.instance().props.actions.openModal).not.toHaveBeenCalled(); key = 'ù'; keyCode = Constants.KeyCodes.FORWARD_SLASH[1] as number; instance.handleKeyDownEvent({ctrlKey: true, preventDefault: jest.fn(), key, keyCode} as any); expect(wrapper.instance().props.actions.openModal).toHaveBeenCalledWith(expect.objectContaining({modalId: ModalIdentifiers.KEYBOARD_SHORTCUTS_MODAL})); key = '/'; keyCode = Constants.KeyCodes.SEVEN[1] as number; instance.handleKeyDownEvent({ctrlKey: true, preventDefault: jest.fn(), key, keyCode} as any); expect(wrapper.instance().props.actions.openModal).toHaveBeenCalledWith(expect.objectContaining({modalId: ModalIdentifiers.KEYBOARD_SHORTCUTS_MODAL})); key = Constants.KeyCodes.FORWARD_SLASH[0] as string; keyCode = Constants.KeyCodes.FORWARD_SLASH[1] as number; instance.handleKeyDownEvent({ctrlKey: true, preventDefault: jest.fn(), key, keyCode} as any); expect(wrapper.instance().props.actions.openModal).toHaveBeenCalledWith(expect.objectContaining({modalId: ModalIdentifiers.KEYBOARD_SHORTCUTS_MODAL})); }); test('should toggle direct messages modal correctly', () => { const wrapper = shallow<Sidebar>( <Sidebar {...baseProps}/>, ); const instance = wrapper.instance(); const mockEvent: Partial<Event> = {preventDefault: jest.fn()}; instance.hideMoreDirectChannelsModal = jest.fn(); instance.showMoreDirectChannelsModal = jest.fn(); instance.handleOpenMoreDirectChannelsModal(mockEvent as any); expect(instance.showMoreDirectChannelsModal).toHaveBeenCalled(); instance.setState({showDirectChannelsModal: true}); instance.handleOpenMoreDirectChannelsModal(mockEvent as any); expect(instance.hideMoreDirectChannelsModal).toHaveBeenCalled(); }); test('should match empty div snapshot when teamId is missing', () => { const props = { ...baseProps, teamId: '', }; const wrapper = shallow( <Sidebar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); describe('unreads category', () => { const currentUserId = 'current_user_id'; const channel1 = TestHelper.getChannelMock({id: 'channel1', team_id: currentTeamId}); const channel2 = TestHelper.getChannelMock({id: 'channel2', team_id: currentTeamId}); const baseState: DeepPartial<GlobalState> = { entities: { channels: { currentChannelId: channel1.id, channels: { channel1, channel2, }, channelsInTeam: { [currentTeamId]: [channel1.id, channel2.id], }, messageCounts: { channel1: {total: 10}, channel2: {total: 10}, }, myMembers: { channel1: TestHelper.getChannelMembershipMock({channel_id: channel1.id, user_id: currentUserId, msg_count: 10}), channel2: TestHelper.getChannelMembershipMock({channel_id: channel2.id, user_id: currentUserId, msg_count: 10}), }, }, teams: { currentTeamId, teams: { [currentTeamId]: TestHelper.getTeamMock({id: currentTeamId}), }, }, users: { currentUserId, }, }, }; test('should not render unreads category when disabled by user preference', () => { const testState = mergeObjects(baseState, { entities: { channels: { messageCounts: { [channel2.id]: {total: 15}, }, }, preferences: { myPreferences: TestHelper.getPreferencesMock([ {category: Preferences.CATEGORY_SIDEBAR_SETTINGS, name: Preferences.SHOW_UNREAD_SECTION, value: 'false'}, ]), }, }, }); renderWithContext( <Sidebar {...baseProps}/>, mergeObjects(baseState, testState), ); expect(screen.queryByText('UNREADS')).not.toBeInTheDocument(); }); test('should render unreads category when there are unread channels', () => { const testState: DeepPartial<GlobalState> = { entities: { channels: { messageCounts: { [channel2.id]: {total: 15}, }, }, preferences: { myPreferences: TestHelper.getPreferencesMock([ {category: Preferences.CATEGORY_SIDEBAR_SETTINGS, name: Preferences.SHOW_UNREAD_SECTION, value: 'true'}, ]), }, }, }; renderWithContext( <Sidebar {...baseProps}/>, mergeObjects(baseState, testState), ); expect(screen.queryByText('UNREADS')).toBeInTheDocument(); }); test('should not render unreads category when there are no unread channels', () => { const testState: DeepPartial<GlobalState> = { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ {category: Preferences.CATEGORY_SIDEBAR_SETTINGS, name: Preferences.SHOW_UNREAD_SECTION, value: 'true'}, ]), }, }, }; renderWithContext( <Sidebar {...baseProps}/>, mergeObjects(baseState, testState), ); expect(screen.queryByText('UNREADS')).not.toBeInTheDocument(); }); test('should render unreads category when there are no unread channels but the current channel was previously unread', () => { const testState: DeepPartial<GlobalState> = { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ {category: Preferences.CATEGORY_SIDEBAR_SETTINGS, name: Preferences.SHOW_UNREAD_SECTION, value: 'true'}, ]), }, }, views: { channel: { lastUnreadChannel: {id: channel1.id} as any, }, }, }; renderWithContext( <Sidebar {...baseProps}/>, mergeObjects(baseState, testState), ); expect(screen.queryByText('UNREADS')).toBeInTheDocument(); }); }); });
3,127
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/__snapshots__/add_channels_cta_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/new_channel_modal should match snapshot 1`] = ` <MenuWrapper animationComponent={[Function]} className="AddChannelsCtaDropdown" onToggle={[Function]} open={false} > <button aria-label="Add Channel Dropdown" className="SidebarChannelNavigator__addChannelsCtaLhsButton SidebarChannelNavigator__addChannelsCtaLhsButton--untouched" id="addChannelsCta" onClick={[Function]} > <div aria-label="Add channels" > <i className="icon-plus-box" /> <span> Add Channels </span> </div> </button> <Menu ariaLabel="Add Channels Dropdown" id="AddChannelCtaDropdown" > <Memo(MenuGroup)> <MenuItemAction icon={ <i className="icon-plus" /> } id="showNewChannel" onClick={[Function]} show={true} text="Create new channel" /> <MenuItemAction icon={ <i className="icon-globe" /> } id="showMoreChannels" onClick={[Function]} show={true} text="Browse channels" /> </Memo(MenuGroup)> </Menu> </MenuWrapper> `; exports[`components/new_channel_modal should match snapshot when user has only join channel permissions 1`] = ` <button aria-label="Add Channel Dropdown" className="SidebarChannelNavigator__addChannelsCtaLhsButton SidebarChannelNavigator__addChannelsCtaLhsButton--untouched" id="addChannelsCta" onClick={[Function]} > <div aria-label="Add channels" > <i className="icon-plus-box" /> <span> Add Channels </span> </div> </button> `;
3,128
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/__snapshots__/invite_members_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/invite_members_button should match snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <InviteMembersButton isAdmin={false} > <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team_id2sss" > <TeamPermissionGate dispatch={[Function]} hasPermission={true} invert={false} permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="team_id2sss" > <ToggleModalButton ariaLabel="Invite Members" className="intro-links color--link cursor--pointer" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="inviteMembersButton" modalId="invitation" onClick={[Function]} > <button aria-label="Invite Members dialog" className="style--none intro-links color--link cursor--pointer" id="inviteMembersButton" onClick={[Function]} > <div aria-label="Invite Members" className="SidebarChannelNavigator__inviteMembersLhsButton" > <i className="icon-plus-box" /> <FormattedMessage defaultMessage="Invite Members" id="sidebar_left.inviteMembers" > <span> Invite Members </span> </FormattedMessage> </div> </button> </ToggleModalButton> </TeamPermissionGate> </Connect(TeamPermissionGate)> </InviteMembersButton> </Provider> `;
3,129
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/__snapshots__/sidebar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar should match empty div snapshot when teamId is missing 1`] = `<div />`; exports[`components/sidebar should match snapshot 1`] = ` <ResizableLhs className="" id="SidebarContainer" > <SidebarHeader canCreateChannel={true} canCreateCustomGroups={true} canJoinPublicChannel={true} handleOpenDirectMessagesModal={[Function]} invitePeopleModal={[Function]} showCreateCategoryModal={[Function]} showCreateUserGroupModal={[Function]} showMoreChannelsModal={[Function]} showNewChannelModal={[Function]} unreadFilterEnabled={false} userGroupsEnabled={false} /> <div aria-label="channel navigator region" className="a11y__region" data-a11y-sort-order="6" id="lhsNavigator" role="application" > <Connect(ChannelNavigator) /> </div> <div className="sidebar--left__icons" > <Connect(Pluggable) pluggableName="LeftSidebarHeader" /> </div> <Connect(SidebarList) handleOpenMoreDirectChannelsModal={[Function]} onDragEnd={[Function]} onDragStart={[Function]} /> <Connect(DataPrefetch) /> </ResizableLhs> `; exports[`components/sidebar should match snapshot when direct channels modal is open 1`] = ` <ResizableLhs className="" id="SidebarContainer" > <SidebarHeader canCreateChannel={true} canCreateCustomGroups={true} canJoinPublicChannel={true} handleOpenDirectMessagesModal={[Function]} invitePeopleModal={[Function]} showCreateCategoryModal={[Function]} showCreateUserGroupModal={[Function]} showMoreChannelsModal={[Function]} showNewChannelModal={[Function]} unreadFilterEnabled={false} userGroupsEnabled={false} /> <div aria-label="channel navigator region" className="a11y__region" data-a11y-sort-order="6" id="lhsNavigator" role="application" > <Connect(ChannelNavigator) /> </div> <div className="sidebar--left__icons" > <Connect(Pluggable) pluggableName="LeftSidebarHeader" /> </div> <Connect(SidebarList) handleOpenMoreDirectChannelsModal={[Function]} onDragEnd={[Function]} onDragStart={[Function]} /> <Connect(DataPrefetch) /> <Connect(MoreDirectChannels) isExistingChannel={false} onModalDismissed={[Function]} /> </ResizableLhs> `; exports[`components/sidebar should match snapshot when more channels modal is open 1`] = ` <ResizableLhs className="" id="SidebarContainer" > <SidebarHeader canCreateChannel={true} canCreateCustomGroups={true} canJoinPublicChannel={true} handleOpenDirectMessagesModal={[Function]} invitePeopleModal={[Function]} showCreateCategoryModal={[Function]} showCreateUserGroupModal={[Function]} showMoreChannelsModal={[Function]} showNewChannelModal={[Function]} unreadFilterEnabled={false} userGroupsEnabled={false} /> <div aria-label="channel navigator region" className="a11y__region" data-a11y-sort-order="6" id="lhsNavigator" role="application" > <Connect(ChannelNavigator) /> </div> <div className="sidebar--left__icons" > <Connect(Pluggable) pluggableName="LeftSidebarHeader" /> </div> <Connect(SidebarList) handleOpenMoreDirectChannelsModal={[Function]} onDragEnd={[Function]} onDragStart={[Function]} /> <Connect(DataPrefetch) /> </ResizableLhs> `;
3,130
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/channel_filter/channel_filter.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import ChannelFilterIntl from 'components/sidebar/channel_filter/channel_filter'; import type {ChannelFilter as ChannelFilterClass} from 'components/sidebar/channel_filter/channel_filter'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; describe('components/sidebar/channel_filter', () => { const baseProps = { unreadFilterEnabled: false, hasMultipleTeams: false, actions: { setUnreadFilterEnabled: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallowWithIntl( <ChannelFilterIntl {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot if the unread filter is enabled', () => { const props = { ...baseProps, unreadFilterEnabled: true, }; const wrapper = shallowWithIntl( <ChannelFilterIntl {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should enable the unread filter on toggle when it is disabled', () => { const wrapper = shallowWithIntl( <ChannelFilterIntl {...baseProps}/>, ); const instance = wrapper.instance() as ChannelFilterClass; instance.toggleUnreadFilter(); expect(baseProps.actions.setUnreadFilterEnabled).toHaveBeenCalledWith(true); }); test('should disable the unread filter on toggle when it is enabled', () => { const props = { ...baseProps, unreadFilterEnabled: true, }; const wrapper = shallowWithIntl( <ChannelFilterIntl {...props}/>, ); const instance = wrapper.instance() as ChannelFilterClass; instance.toggleUnreadFilter(); expect(baseProps.actions.setUnreadFilterEnabled).toHaveBeenCalledWith(false); }); });
3,133
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/channel_filter
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/channel_filter/__snapshots__/channel_filter.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/channel_filter should match snapshot 1`] = ` <div className="SidebarFilters" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="new-group-tooltip" > Filter by unread <Memo(KeyboardShortcutSequence) hideDescription={true} isInsideTooltip={true} shortcut={ Object { "default": Object { "defaultMessage": "Toggle unread/all channels: Ctrl|Shift|U", "id": "shortcuts.nav.toggle_unreads", }, "mac": Object { "defaultMessage": "Toggle unread/all channels: ⌘|Shift|U", "id": "shortcuts.nav.toggle_unreads.mac", }, } } /> </Tooltip> } placement="right" trigger={ Array [ "hover", "focus", ] } > <a aria-label="unreads filter" className="SidebarFilters_filterButton" href="#" onClick={[Function]} > <i className="icon icon-filter-variant" /> </a> </OverlayTrigger> </div> `; exports[`components/sidebar/channel_filter should match snapshot if the unread filter is enabled 1`] = ` <div className="SidebarFilters" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="new-group-tooltip" > Show all channels <Memo(KeyboardShortcutSequence) hideDescription={true} isInsideTooltip={true} shortcut={ Object { "default": Object { "defaultMessage": "Toggle unread/all channels: Ctrl|Shift|U", "id": "shortcuts.nav.toggle_unreads", }, "mac": Object { "defaultMessage": "Toggle unread/all channels: ⌘|Shift|U", "id": "shortcuts.nav.toggle_unreads.mac", }, } } /> </Tooltip> } placement="right" trigger={ Array [ "hover", "focus", ] } > <a aria-label="unreads filter" className="SidebarFilters_filterButton active" href="#" onClick={[Function]} > <i className="icon icon-filter-variant" /> </a> </OverlayTrigger> </div> `;
3,134
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/channel_navigator/channel_navigator.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 ChannelNavigator from './channel_navigator'; import type {Props} from './channel_navigator'; import AddChannelDropdown from '../add_channel_dropdown'; let props: Props; describe('Components/ChannelNavigator', () => { beforeEach(() => { props = { showUnreadsCategory: true, isQuickSwitcherOpen: false, actions: { openModal: jest.fn(), closeModal: jest.fn(), }, }; }); it('should not show AddChannelDropdown', () => { const wrapper = shallow(<ChannelNavigator {...props}/>); expect(wrapper.find(AddChannelDropdown).length).toBe(0); }); });
3,142
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/sidebar_category.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 {CategorySorting} from '@mattermost/types/channel_categories'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import SidebarCategory from 'components/sidebar/sidebar_category/sidebar_category'; describe('components/sidebar/sidebar_category', () => { const baseProps = { category: { id: 'category1', team_id: 'team1', user_id: '', type: CategoryTypes.CUSTOM, display_name: 'custom_category_1', channel_ids: ['channel_id'], sorting: CategorySorting.Alphabetical, muted: false, collapsed: false, }, channelIds: ['channel_id'], categoryIndex: 0, draggingState: {}, setChannelRef: jest.fn(), handleOpenMoreDirectChannelsModal: jest.fn(), isNewCategory: false, isDisabled: false, limitVisibleDMsGMs: 10000, touchedInviteMembersButton: false, currentUserId: '', isAdmin: false, actions: { setCategoryCollapsed: jest.fn(), setCategorySorting: jest.fn(), savePreferences: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <SidebarCategory {...baseProps}/>, ); const draggable = wrapper.dive().find('PrivateDraggable').first(); const children: any = draggable.prop('children')!; const inner = shallow( children({}, {}), ); expect(inner).toMatchSnapshot(); const droppable = inner.find('Connect(Droppable)').first(); const droppableChildren: any = droppable.prop('children')!; const droppableInner = shallow( droppableChildren({}, {}), ); expect(droppableInner).toMatchSnapshot(); }); test('should match snapshot when isNewCategory', () => { const props = { ...baseProps, isNewCategory: true, category: { ...baseProps.category, channel_ids: [], }, channelIds: [], }; const wrapper = shallow( <SidebarCategory {...props}/>, ); const draggable = wrapper.dive().find('PrivateDraggable').first(); const children: any = draggable.prop('children')!; const inner = shallow( children({}, {}), ); expect(inner).toMatchSnapshot(); const droppable = inner.find('Connect(Droppable)').first(); const droppableChildren: any = droppable.prop('children')!; const droppableInner = shallow( droppableChildren({}, {}), ); expect(droppableInner).toMatchSnapshot(); expect(droppableInner.find('.SidebarCategory_newLabel')).toHaveLength(1); expect(droppableInner.find('.SidebarCategory_newDropBox')).toHaveLength(1); }); test('should match snapshot when collapsed', () => { const props = { ...baseProps, category: { ...baseProps.category, collapsed: true, }, }; const wrapper = shallow( <SidebarCategory {...props}/>, ); const draggable = wrapper.dive().find('PrivateDraggable').first(); const children: any = draggable.prop('children')!; const inner = shallow( children({}, {}), ); expect(inner).toMatchSnapshot(); const droppable = inner.find('Connect(Droppable)').first(); const droppableChildren: any = droppable.prop('children')!; const droppableInner = shallow( droppableChildren({}, {}), ); expect(droppableInner).toMatchSnapshot(); }); test('should match snapshot when the category is DM and there are no DMs to display', () => { const props = { ...baseProps, category: { ...baseProps.category, type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Recency, }, channelIds: [], }; const wrapper = shallow( <SidebarCategory {...props}/>, ); const draggable = wrapper.dive().find('PrivateDraggable').first(); const children: any = draggable.prop('children')!; const inner = shallow( children({}, {}), ); expect(inner).toMatchSnapshot(); const droppable = inner.find('Connect(Droppable)').first(); const droppableChildren: any = droppable.prop('children')!; const droppableInner = shallow( droppableChildren({}, {}), ); expect(droppableInner).toMatchSnapshot(); }); test('should match snapshot when there are no channels to display', () => { const props = { ...baseProps, channelIds: [], }; const wrapper = shallow( <SidebarCategory {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when sorting is set to by recency', () => { const props = { ...baseProps, category: { ...baseProps.category, type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Recency, }, }; const wrapper = shallow( <SidebarCategory {...props}/>, ); const draggable = wrapper.dive().find('PrivateDraggable').first(); const children: any = draggable.prop('children')!; const inner = shallow( children({}, {}), ); expect(inner).toMatchSnapshot(); const droppable = inner.find('Connect(Droppable)').first(); const droppableChildren: any = droppable.prop('children')!; const droppableInner = shallow( droppableChildren({}, {}), ); expect(droppableInner).toMatchSnapshot(); }); test('should collapse the channel on toggle when it is not collapsed', () => { const wrapper = shallow<SidebarCategory>( <SidebarCategory {...baseProps}/>, ); wrapper.instance().handleCollapse(); expect(baseProps.actions.setCategoryCollapsed).toHaveBeenCalledWith(baseProps.category.id, true); }); test('should un-collapse the channel on toggle when it is collapsed', () => { const props = { ...baseProps, category: { ...baseProps.category, collapsed: true, }, }; const wrapper = shallow<SidebarCategory>( <SidebarCategory {...props}/>, ); wrapper.instance().handleCollapse(); expect(baseProps.actions.setCategoryCollapsed).toHaveBeenCalledWith(props.category.id, false); }); });
3,144
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/sidebar_category_sorting_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 * as redux from 'react-redux'; import {TestHelper} from 'utils/test_helper'; import SidebarCategorySortingMenu from './sidebar_category_sorting_menu'; const initialState = { entities: { users: { currentUserId: 'user_id', }, preferences: { myPreferences: { 'sidebar_settings--limit_visible_dms_gms': { value: '10', }, }, }, }, }; jest.spyOn(redux, 'useSelector').mockImplementation((cb) => cb(initialState)); jest.spyOn(redux, 'useDispatch').mockReturnValue((t) => t); describe('components/sidebar/sidebar_category/sidebar_category_sorting_menu', () => { const baseProps = { category: TestHelper.getCategoryMock(), handleOpenDirectMessagesModal: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <SidebarCategorySortingMenu {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
3,146
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/__snapshots__/sidebar_category.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_category should match snapshot 1`] = ` <div className="SidebarChannelGroup a11y__section" > <Connect(Droppable) direction="vertical" droppableId="category1" getContainerForClone={[Function]} ignoreContainerClipping={false} isCombineEnabled={false} isDropDisabled={false} mode="standard" renderClone={null} type="SIDEBAR_CHANNEL" > <Component /> </Connect(Droppable)> </div> `; exports[`components/sidebar/sidebar_category should match snapshot 2`] = ` <div className="" > <SidebarCategoryHeader displayName="custom_category_1" isCollapsed={false} isCollapsible={true} isDragging={false} isDraggingOver={false} muted={false} onClick={[Function]} > <Memo(SidebarCategoryMenu) category={ Object { "channel_ids": Array [ "channel_id", ], "collapsed": false, "display_name": "custom_category_1", "id": "category1", "muted": false, "sorting": "alpha", "team_id": "team1", "type": "custom", "user_id": "", } } /> </SidebarCategoryHeader> <div className="SidebarChannelGroup_content" > <ul className="NavGroupContent" role="list" > <Connect(SidebarChannel) channelId="channel_id" channelIndex={0} isAutoSortedCategory={true} isCategoryCollapsed={false} isCategoryDragged={false} isDraggable={true} key="channel_id" setChannelRef={[MockFunction]} /> </ul> </div> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when collapsed 1`] = ` <div className="SidebarChannelGroup a11y__section isCollapsed" > <Connect(Droppable) direction="vertical" droppableId="category1" getContainerForClone={[Function]} ignoreContainerClipping={false} isCombineEnabled={false} isDropDisabled={false} mode="standard" renderClone={null} type="SIDEBAR_CHANNEL" > <Component /> </Connect(Droppable)> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when collapsed 2`] = ` <div className="" > <SidebarCategoryHeader displayName="custom_category_1" isCollapsed={true} isCollapsible={true} isDragging={false} isDraggingOver={false} muted={false} onClick={[Function]} > <Memo(SidebarCategoryMenu) category={ Object { "channel_ids": Array [ "channel_id", ], "collapsed": true, "display_name": "custom_category_1", "id": "category1", "muted": false, "sorting": "alpha", "team_id": "team1", "type": "custom", "user_id": "", } } /> </SidebarCategoryHeader> <div className="SidebarChannelGroup_content" > <ul className="NavGroupContent" role="list" > <Connect(SidebarChannel) channelId="channel_id" channelIndex={0} isAutoSortedCategory={true} isCategoryCollapsed={true} isCategoryDragged={false} isDraggable={true} key="channel_id" setChannelRef={[MockFunction]} /> </ul> </div> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when isNewCategory 1`] = ` <div className="SidebarChannelGroup a11y__section" > <Connect(Droppable) direction="vertical" droppableId="category1" getContainerForClone={[Function]} ignoreContainerClipping={false} isCombineEnabled={false} isDropDisabled={false} mode="standard" renderClone={null} type="SIDEBAR_CHANNEL" > <Component /> </Connect(Droppable)> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when isNewCategory 2`] = ` <div className="" > <SidebarCategoryHeader displayName="custom_category_1" isCollapsed={false} isCollapsible={true} isDragging={false} isDraggingOver={false} muted={false} onClick={[Function]} > <div className="SidebarCategory_newLabel" > <MemoizedFormattedMessage defaultMessage="new" id="sidebar_left.sidebar_category.newLabel" /> </div> <Memo(SidebarCategoryMenu) category={ Object { "channel_ids": Array [], "collapsed": false, "display_name": "custom_category_1", "id": "category1", "muted": false, "sorting": "alpha", "team_id": "team1", "type": "custom", "user_id": "", } } /> </SidebarCategoryHeader> <div className="SidebarChannelGroup_content" > <ul className="NavGroupContent" role="list" > <PublicDraggable draggableId="NEW_CHANNEL_SPACER__category1" index={0} isDragDisabled={true} > <Component /> </PublicDraggable> <div className="SidebarCategory_newDropBox" > <div className="SidebarCategory_newDropBox-content" onTransitionEnd={[Function]} > <i className="icon-hand-right" /> <span className="SidebarCategory_newDropBox-label" > <MemoizedFormattedMessage defaultMessage="Drag channels here..." id="sidebar_left.sidebar_category.newDropBoxLabel" /> </span> </div> </div> </ul> </div> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when sorting is set to by recency 1`] = ` <div className="SidebarChannelGroup a11y__section" > <Connect(Droppable) direction="vertical" droppableId="category1" getContainerForClone={[Function]} ignoreContainerClipping={false} isCombineEnabled={false} isDropDisabled={false} mode="standard" renderClone={null} type="SIDEBAR_CHANNEL" > <Component /> </Connect(Droppable)> <InviteMembersButton className="followingSibling" isAdmin={false} /> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when sorting is set to by recency 2`] = ` <div className="" > <SidebarCategoryHeader displayName="custom_category_1" isCollapsed={false} isCollapsible={true} isDragging={false} isDraggingOver={false} muted={false} onClick={[Function]} > <Memo(SidebarCategorySortingMenu) category={ Object { "channel_ids": Array [ "channel_id", ], "collapsed": false, "display_name": "custom_category_1", "id": "category1", "muted": false, "sorting": "recent", "team_id": "team1", "type": "direct_messages", "user_id": "", } } handleOpenDirectMessagesModal={[Function]} /> <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="new-group-tooltip" > Create new direct message <Memo(KeyboardShortcutSequence) hideDescription={true} isInsideTooltip={true} shortcut={ Object { "default": Object { "defaultMessage": "Direct messages menu: Ctrl|Shift|K", "id": "shortcuts.nav.direct_messages_menu", }, "mac": Object { "defaultMessage": "Direct messages menu: ⌘|Shift|K", "id": "shortcuts.nav.direct_messages_menu.mac", }, } } /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-label="Create new direct message" className="SidebarChannelGroupHeader_addButton" onClick={[Function]} > <i className="icon-plus" /> </button> </OverlayTrigger> </SidebarCategoryHeader> <div className="SidebarChannelGroup_content" > <ul className="NavGroupContent" role="list" > <Connect(SidebarChannel) channelId="channel_id" channelIndex={0} isAutoSortedCategory={true} isCategoryCollapsed={false} isCategoryDragged={false} isDraggable={true} key="channel_id" setChannelRef={[MockFunction]} /> </ul> </div> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when the category is DM and there are no DMs to display 1`] = ` <div className="SidebarChannelGroup a11y__section" > <Connect(Droppable) direction="vertical" droppableId="category1" getContainerForClone={[Function]} ignoreContainerClipping={false} isCombineEnabled={false} isDropDisabled={false} mode="standard" renderClone={null} type="SIDEBAR_CHANNEL" > <Component /> </Connect(Droppable)> <InviteMembersButton className="followingSibling" isAdmin={false} /> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when the category is DM and there are no DMs to display 2`] = ` <div className="" > <SidebarCategoryHeader displayName="custom_category_1" isCollapsed={false} isCollapsible={false} isDragging={false} isDraggingOver={false} muted={false} onClick={[Function]} > <Memo(SidebarCategorySortingMenu) category={ Object { "channel_ids": Array [ "channel_id", ], "collapsed": false, "display_name": "custom_category_1", "id": "category1", "muted": false, "sorting": "recent", "team_id": "team1", "type": "direct_messages", "user_id": "", } } handleOpenDirectMessagesModal={[Function]} /> <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="new-group-tooltip" > Create new direct message <Memo(KeyboardShortcutSequence) hideDescription={true} isInsideTooltip={true} shortcut={ Object { "default": Object { "defaultMessage": "Direct messages menu: Ctrl|Shift|K", "id": "shortcuts.nav.direct_messages_menu", }, "mac": Object { "defaultMessage": "Direct messages menu: ⌘|Shift|K", "id": "shortcuts.nav.direct_messages_menu.mac", }, } } /> </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <button aria-label="Create new direct message" className="SidebarChannelGroupHeader_addButton" onClick={[Function]} > <i className="icon-plus" /> </button> </OverlayTrigger> </SidebarCategoryHeader> <div className="SidebarChannelGroup_content" > <ul className="NavGroupContent" role="list" /> </div> </div> `; exports[`components/sidebar/sidebar_category should match snapshot when there are no channels to display 1`] = ` <PublicDraggable disableInteractiveElementBlocking={true} draggableId="category1" index={0} > <Component /> </PublicDraggable> `;
3,147
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/__snapshots__/sidebar_category_sorting_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_category/sidebar_category_sorting_menu should match snapshot 1`] = ` <div className="SidebarMenu MenuWrapper" > <Menu menu={ Object { "aria-label": "Edit category menu", "id": "SidebarCategorySortingMenu-MenuList-category_id", "onToggle": [Function], } } menuButton={ Object { "aria-label": "Category options", "children": <DotsVerticalIcon size={16} />, "class": "SidebarMenu_menuButton sortingMenu", "id": "SidebarCategorySortingMenu-Button-category_id", } } menuButtonTooltip={ Object { "class": "hidden-xs", "id": "SidebarCategorySortingMenu-ButtonTooltip-category_id", "text": "Category options", } } > <SubMenu id="sortDirectMessages-category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Sort" id="sidebar.sort" /> } leadingElement={ <SortAlphabeticalAscendingIcon size={18} /> } menuId="sortDirectMessages-category_id-menu" trailingElements={ <React.Fragment> <Memo(MemoizedFormattedMessage) defaultMessage="Alphabetically" id="user.settings.sidebar.sortAlpha" /> <ChevronRightIcon size={16} /> </React.Fragment> } > <MenuItem id="sortAlphabetical-category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Alphabetically" id="user.settings.sidebar.sortAlpha" /> } onClick={[Function]} /> <MenuItem id="sortByMostRecent-category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Recent Activity" id="sidebar.sortedByRecencyLabel" /> } onClick={[Function]} /> </SubMenu> <SubMenu id="showMessagesCount-category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Show" id="sidebar.show" /> } leadingElement={ <AccountMultipleOutlineIcon size={18} /> } menuId="showMessagesCount-category_id-menu" trailingElements={ <React.Fragment> <span> 10 </span> <ChevronRightIcon size={16} /> </React.Fragment> } > <MenuItem id="showAllDms-category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="All direct messages" id="sidebar.allDirectMessages" /> } onClick={[Function]} /> <MenuItemSeparator /> <MenuItem id="showDmCount-category_id-10" key="showDmCount-category_id-10" labels={ <span> 10 </span> } onClick={[Function]} /> <MenuItem id="showDmCount-category_id-15" key="showDmCount-category_id-15" labels={ <span> 15 </span> } onClick={[Function]} /> <MenuItem id="showDmCount-category_id-20" key="showDmCount-category_id-20" labels={ <span> 20 </span> } onClick={[Function]} /> <MenuItem id="showDmCount-category_id-40" key="showDmCount-category_id-40" labels={ <span> 40 </span> } onClick={[Function]} /> </SubMenu> <MenuItemSeparator /> <MenuItem id="openDirectMessage-category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Open a direct message" id="sidebar.openDirectMessage" /> } leadingElement={ <AccountPlusOutlineIcon size={18} /> } onClick={[MockFunction]} /> </Menu> </div> `;
3,149
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/sidebar_category_menu/index.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 * as redux from 'react-redux'; import {CategorySorting} from '@mattermost/types/channel_categories'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import CreateNewCategoryMenuItem from './create_new_category_menu_item'; import SidebarCategoryMenu from '.'; const initialState = { entities: { preferences: { myPreferences: {}, }, channels: { channels: {}, channelsInTeam: {}, }, users: { currentUserId: '', profiles: {}, }, teams: { currentTeamId: '', }, general: { config: { ExperimentalGroupUnreadChannels: 'default_off', }, }, }, views: { channel: { lastUnreadChannel: '', }, }, }; jest.spyOn(redux, 'useSelector').mockImplementation((cb) => cb(initialState)); jest.spyOn(redux, 'useDispatch').mockReturnValue((t) => t); describe('components/sidebar/sidebar_category/sidebar_category_menu', () => { const categoryId = 'test_category_id'; const baseProps = { category: { id: categoryId, team_id: 'team1', user_id: '', type: CategoryTypes.CUSTOM, display_name: 'custom_category_1', channel_ids: ['channel_id'], sorting: CategorySorting.Alphabetical, muted: false, collapsed: false, }, }; test('should match snapshot and contain correct buttons', () => { const wrapper = shallow( <SidebarCategoryMenu {...baseProps}/>, ); expect(wrapper.find(`#rename-${categoryId}`)).toHaveLength(1); expect(wrapper.find(CreateNewCategoryMenuItem)).toHaveLength(1); expect(wrapper.find(`#delete-${categoryId}`)).toHaveLength(1); expect(wrapper).toMatchSnapshot(); }); test('should show correct menu itemsu when category is favorites', () => { const props = { ...baseProps, category: { ...baseProps.category, type: CategoryTypes.FAVORITES, }, }; const wrapper = shallow( <SidebarCategoryMenu {...props}/>, ); expect(wrapper.find(`#rename-${categoryId}`)).toHaveLength(0); expect(wrapper.find(`#delete-${categoryId}`)).toHaveLength(0); }); test('should show correct menu items when category is direct messages', () => { const props = { ...baseProps, category: { ...baseProps.category, type: CategoryTypes.DIRECT_MESSAGES, }, }; const wrapper = shallow( <SidebarCategoryMenu {...props}/>, ); expect(wrapper.find(`#mute-${categoryId}`)).toHaveLength(0); }); test('should show correct menu items when category is not direct messages', () => { const props = { ...baseProps, category: { ...baseProps.category, type: CategoryTypes.CUSTOM, }, }; const wrapper = shallow( <SidebarCategoryMenu {...props}/>, ); expect(wrapper.find(`#mute-${categoryId}`)).toHaveLength(1); }); });
3,154
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/sidebar_category_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_category/sidebar_category_menu/__snapshots__/index.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_category/sidebar_category_menu should match snapshot and contain correct buttons 1`] = ` <Memo(SidebarCategoryGenericMenu) id="test_category_id" > <MarkAsUnreadItem handleViewCategory={[Function]} id="test_category_id" numChannels={0} /> <MenuItemSeparator /> <MenuItem id="mute-test_category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Mute Category" id="sidebar_left.sidebar_category_menu.muteCategory" /> } leadingElement={ <BellOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup={true} id="rename-test_category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Rename Category" id="sidebar_left.sidebar_category_menu.renameCategory" /> } leadingElement={ <PencilOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItem aria-haspopup={true} id="delete-test_category_id" isDestructive={true} labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Delete Category" id="sidebar_left.sidebar_category_menu.deleteCategory" /> } leadingElement={ <TrashCanOutlineIcon size={18} /> } onClick={[Function]} /> <MenuItemSeparator /> <SubMenu id="sortChannels-test_category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Sort" id="sidebar.sort" /> } leadingElement={ <SortAlphabeticalAscendingIcon size={18} /> } menuAriaLabel="Sort submenu" menuId="sortChannels-test_category_id-menu" trailingElements={ <React.Fragment> <Memo(MemoizedFormattedMessage) defaultMessage="Alphabetically" id="user.settings.sidebar.sortAlpha" /> <ChevronRightIcon size={16} /> </React.Fragment> } > <MenuItem id="sortAplhabetical-test_category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Alphabetically" id="user.settings.sidebar.sortAlpha" /> } onClick={[Function]} /> <MenuItem id="sortByMostRecent-test_category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Recent Activity" id="sidebar.sortedByRecencyLabel" /> } onClick={[Function]} /> <MenuItem id="sortManual-test_category_id" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Manually" id="sidebar.sortedManually" /> } onClick={[Function]} /> </SubMenu> <MenuItemSeparator /> <CreateNewCategoryMenuItem id="test_category_id" /> </Memo(SidebarCategoryGenericMenu)> `;
3,157
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_channel.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 SidebarChannel from 'components/sidebar/sidebar_channel/sidebar_channel'; describe('components/sidebar/sidebar_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, }, channelId: 'channel_id', isDraggable: false, channelIndex: 0, currentTeamName: 'team_name', unreadMentions: 0, isUnread: false, setChannelRef: jest.fn(), isCategoryCollapsed: false, isCurrentChannel: false, isAutoSortedCategory: false, isCategoryDragged: false, isDropDisabled: false, draggingState: {}, multiSelectedChannelIds: [], autoSortedCategoryIds: new Set<string>(), isChannelSelected: false, }; test('should match snapshot', () => { const wrapper = shallow( <SidebarChannel {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when collapsed', () => { const props = { ...baseProps, isCategoryCollapsed: true, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when unread', () => { const props = { ...baseProps, isUnread: true, unreadMentions: 1, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when active', () => { const props = { ...baseProps, isCurrentChannel: true, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when DM channel', () => { const props = { ...baseProps, channel: { ...baseProps.channel, type: 'D' as ChannelType, }, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when GM channel', () => { const props = { ...baseProps, channel: { ...baseProps.channel, type: 'G' as ChannelType, }, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should not be collapsed when there are unread messages', () => { const props = { ...baseProps, isCategoryCollapsed: true, isUnread: true, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper.find('.expanded')).toHaveLength(1); }); test('should not be collapsed if channel is current channel', () => { const props = { ...baseProps, isCategoryCollapsed: true, isCurrentChannel: true, }; const wrapper = shallow( <SidebarChannel {...props}/>, ); expect(wrapper.find('.expanded')).toHaveLength(1); }); });
3,159
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/__snapshots__/sidebar_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_channel should match snapshot 1`] = ` <li className="SidebarChannel expanded" onAnimationEnd={[Function]} onAnimationStart={[Function]} role="listitem" > <Connect(SidebarBaseChannel) 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, } } currentTeamName="team_name" /> </li> `; exports[`components/sidebar/sidebar_channel should match snapshot when DM channel 1`] = ` <li className="SidebarChannel expanded" onAnimationEnd={[Function]} onAnimationStart={[Function]} role="listitem" > <Connect(injectIntl(SidebarDirectChannel)) 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": "D", "update_at": 0, } } currentTeamName="team_name" /> </li> `; exports[`components/sidebar/sidebar_channel should match snapshot when GM channel 1`] = ` <li className="SidebarChannel expanded" onAnimationEnd={[Function]} onAnimationStart={[Function]} role="listitem" > <Connect(SidebarGroupChannel) 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": "G", "update_at": 0, } } currentTeamName="team_name" /> </li> `; exports[`components/sidebar/sidebar_channel should match snapshot when active 1`] = ` <li className="SidebarChannel expanded active" onAnimationEnd={[Function]} onAnimationStart={[Function]} role="listitem" > <Connect(SidebarBaseChannel) 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, } } currentTeamName="team_name" /> </li> `; exports[`components/sidebar/sidebar_channel should match snapshot when collapsed 1`] = ` <li className="SidebarChannel collapsed" onAnimationEnd={[Function]} onAnimationStart={[Function]} role="listitem" > <Connect(SidebarBaseChannel) 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, } } currentTeamName="team_name" /> </li> `; exports[`components/sidebar/sidebar_channel should match snapshot when unread 1`] = ` <li className="SidebarChannel expanded unread" onAnimationEnd={[Function]} onAnimationStart={[Function]} role="listitem" > <Connect(SidebarBaseChannel) 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, } } currentTeamName="team_name" /> </li> `;
3,164
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_base_channel/sidebar_base_channel.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 SidebarBaseChannel from 'components/sidebar/sidebar_channel/sidebar_base_channel/sidebar_base_channel'; describe('components/sidebar/sidebar_channel/sidebar_base_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, }, currentTeamName: 'team_name', actions: { leaveChannel: jest.fn(), openModal: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <SidebarBaseChannel {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when shared channel', () => { const props = { ...baseProps, channel: { ...baseProps.channel, shared: true, }, }; const wrapper = shallow( <SidebarBaseChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when private channel', () => { const props = { ...baseProps, channel: { ...baseProps.channel, type: 'P' as ChannelType, }, }; const wrapper = shallow( <SidebarBaseChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when shared private channel', () => { const props = { ...baseProps, channel: { ...baseProps.channel, type: 'P' as ChannelType, shared: true, }, }; const wrapper = shallow( <SidebarBaseChannel {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('expect callback to be called when leave public channel ', () => { const callback = jest.fn(); const wrapper = shallow<SidebarBaseChannel>(<SidebarBaseChannel {...baseProps}/>); wrapper.instance().handleLeavePublicChannel(callback); expect(callback).toBeCalled(); }); test('expect callback to be called when leave private channel ', () => { const callback = jest.fn(); const props = { ...baseProps, channel: { ...baseProps.channel, type: 'P' as ChannelType, }, }; const wrapper = shallow<SidebarBaseChannel>(<SidebarBaseChannel {...props}/>); wrapper.instance().handleLeavePrivateChannel(callback); expect(callback).toBeCalled(); }); });
3,166
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_base_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/sidebar/sidebar_channel/sidebar_base_channel/__snapshots__/sidebar_base_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/sidebar_channel/sidebar_base_channel should match snapshot 1`] = ` <Connect(SidebarChannelLink) ariaLabelPrefix="public channel" 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-globe" /> } label="channel_display_name" link="/team_name/channels/" /> `; exports[`components/sidebar/sidebar_channel/sidebar_base_channel should match snapshot when private channel 1`] = ` <Connect(SidebarChannelLink) ariaLabelPrefix="private channel" 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": "P", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <i className="icon icon-lock-outline" /> } label="channel_display_name" link="/team_name/channels/" /> `; exports[`components/sidebar/sidebar_channel/sidebar_base_channel should match snapshot when shared channel 1`] = ` <Connect(SidebarChannelLink) ariaLabelPrefix="public channel" 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": "", "shared": true, "team_id": "", "type": "O", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <SharedChannelIndicator channelType="O" className="icon" withTooltip={true} /> } label="channel_display_name" link="/team_name/channels/" /> `; exports[`components/sidebar/sidebar_channel/sidebar_base_channel should match snapshot when shared private channel 1`] = ` <Connect(SidebarChannelLink) ariaLabelPrefix="private channel" 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": "", "shared": true, "team_id": "", "type": "P", "update_at": 0, } } channelLeaveHandler={[Function]} icon={ <SharedChannelIndicator channelType="P" className="icon" withTooltip={true} /> } label="channel_display_name" link="/team_name/channels/" /> `;
3,170
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_link/sidebar_channel_link.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ChannelType} from '@mattermost/types/channels'; import SidebarChannelLink from 'components/sidebar/sidebar_channel/sidebar_channel_link/sidebar_channel_link'; describe('components/sidebar/sidebar_channel/sidebar_channel_link', () => { 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, }, link: 'http://a.fake.link', label: 'channel_label', icon: null, unreadMentions: 0, isUnread: false, isMuted: false, isChannelSelected: false, hasUrgent: false, showChannelsTutorialStep: false, actions: { markMostRecentPostInChannelAsUnread: jest.fn(), multiSelectChannel: jest.fn(), multiSelectChannelAdd: jest.fn(), multiSelectChannelTo: jest.fn(), clearChannelSelection: jest.fn(), openLhs: jest.fn(), unsetEditingPost: jest.fn(), closeRightHandSide: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <SidebarChannelLink {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for desktop', () => { const userAgentMock = jest.requireMock('utils/user_agent'); userAgentMock.isDesktopApp.mockImplementation(() => false); const wrapper = shallow( <SidebarChannelLink {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when tooltip is enabled', () => { const wrapper = shallow( <SidebarChannelLink {...baseProps}/>, ); wrapper.setState({showTooltip: true}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with aria label prefix and unread mentions', () => { const props = { ...baseProps, isUnread: true, unreadMentions: 2, ariaLabelPrefix: 'aria_label_prefix_', }; const wrapper = shallow( <SidebarChannelLink {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should enable tooltip when needed', () => { const wrapper = shallow<SidebarChannelLink>( <SidebarChannelLink {...baseProps}/>, ); const instance = wrapper.instance(); instance.labelRef = { current: { offsetWidth: 50, scrollWidth: 60, }, } as any; instance.enableToolTipIfNeeded(); expect(instance.state.showTooltip).toBe(true); }); });