level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
1,688
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/toggle_mute_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/toggle_mute_channel/__snapshots__/toggle_mute_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown/MenuItemToggleMuteChannel should match snapshot 1`] = ` <MenuItemAction onClick={[Function]} show={true} text="Mute Channel" /> `;
1,690
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/view_pinned_posts/view_pinned_posts.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 Menu from 'components/widgets/menu/menu'; import ViewPinnedPosts from './view_pinned_posts'; describe('components/ChannelHeaderDropdown/MenuItem.ViewPinnedPosts', () => { const baseProps = { channel: { id: 'channel_id', }, hasPinnedPosts: true, actions: { closeRightHandSide: jest.fn(), showPinnedPosts: jest.fn(), }, }; it('should match snapshot', () => { const wrapper = shallow(<ViewPinnedPosts {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should runs closeRightHandSide function if has any pinned posts', () => { const wrapper = shallow(<ViewPinnedPosts {...baseProps}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(baseProps.actions.closeRightHandSide).toHaveBeenCalled(); }); it('should runs showPinnedPosts function if has not pinned posts', () => { const props = { ...baseProps, hasPinnedPosts: false, }; const wrapper = shallow(<ViewPinnedPosts {...props}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(baseProps.actions.showPinnedPosts).toHaveBeenCalled(); }); });
1,692
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/view_pinned_posts
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/view_pinned_posts/__snapshots__/view_pinned_posts.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown/MenuItem.ViewPinnedPosts should match snapshot 1`] = ` <MenuItemAction onClick={[Function]} show={true} text="View Pinned Posts" /> `;
1,693
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/channel_header_mobile.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {TestHelper} from 'utils/test_helper'; import ChannelHeaderMobile from './channel_header_mobile'; describe('components/ChannelHeaderMobile/ChannelHeaderMobile', () => { global.document.querySelector = jest.fn().mockReturnValue({ addEventListener: jest.fn(), removeEventListener: jest.fn(), }); const baseProps = { user: TestHelper.getUserMock({ id: 'user_id', }), channel: TestHelper.getChannelMock({ type: 'O', id: 'channel_id', display_name: 'display_name', team_id: 'team_id', }), member: TestHelper.getChannelMembershipMock({ channel_id: 'channel_id', user_id: 'user_id', }), teamDisplayName: 'team_display_name', isPinnedPosts: true, actions: { closeLhs: jest.fn(), closeRhs: jest.fn(), closeRhsMenu: jest.fn(), }, isLicensed: true, isMobileView: false, isFavoriteChannel: false, }; test('should match snapshot', () => { const wrapper = shallow( <ChannelHeaderMobile {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, for default channel', () => { const props = { ...baseProps, channel: TestHelper.getChannelMock({ type: 'O', id: '123', name: 'town-square', display_name: 'Town Square', team_id: 'team_id', }), }; const wrapper = shallow( <ChannelHeaderMobile {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, if DM channel', () => { const props = { ...baseProps, channel: TestHelper.getChannelMock({ type: 'D', id: 'channel_id', name: 'user_id_1__user_id_2', display_name: 'display_name', team_id: 'team_id', }), }; const wrapper = shallow(<ChannelHeaderMobile {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, for private channel', () => { const props = { ...baseProps, channel: TestHelper.getChannelMock({ type: 'P', id: 'channel_id', display_name: 'display_name', team_id: 'team_id', }), }; const wrapper = shallow(<ChannelHeaderMobile {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
1,696
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/__snapshots__/channel_header_mobile.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderMobile/ChannelHeaderMobile should match snapshot 1`] = ` <nav className="navbar navbar-default navbar-fixed-top" id="navbar" role="navigation" > <div className="container-fluid theme" > <div className="navbar-header" > <Connect(CollapseLhsButton) /> <div className="navbar-brand" > <Connect(injectIntl(MobileChannelHeaderDropdown)) /> </div> <div className="spacer" /> <Connect(NavbarInfoButton) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "display_name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <Connect(ShowSearchButton) /> <Connect(injectIntl(MobileChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "display_name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } isDropdown={false} /> <Connect(CollapseRhsButton) /> </div> </div> </nav> `; exports[`components/ChannelHeaderMobile/ChannelHeaderMobile should match snapshot, for default channel 1`] = ` <nav className="navbar navbar-default navbar-fixed-top" id="navbar" role="navigation" > <div className="container-fluid theme" > <div className="navbar-header" > <Connect(CollapseLhsButton) /> <div className="navbar-brand" > <Connect(injectIntl(MobileChannelHeaderDropdown)) /> </div> <div className="spacer" /> <Connect(NavbarInfoButton) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "Town Square", "group_constrained": false, "header": "header", "id": "123", "last_post_at": 0, "last_root_post_at": 0, "name": "town-square", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> <Connect(ShowSearchButton) /> <Connect(injectIntl(MobileChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "Town Square", "group_constrained": false, "header": "header", "id": "123", "last_post_at": 0, "last_root_post_at": 0, "name": "town-square", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } isDropdown={false} /> <Connect(CollapseRhsButton) /> </div> </div> </nav> `; exports[`components/ChannelHeaderMobile/ChannelHeaderMobile should match snapshot, for private channel 1`] = ` <nav className="navbar navbar-default navbar-fixed-top" id="navbar" role="navigation" > <div className="container-fluid theme" > <div className="navbar-header" > <Connect(CollapseLhsButton) /> <div className="navbar-brand" > <Connect(injectIntl(MobileChannelHeaderDropdown)) /> </div> <div className="spacer" /> <Connect(NavbarInfoButton) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "display_name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "P", "update_at": 0, } } /> <Connect(ShowSearchButton) /> <Connect(injectIntl(MobileChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "display_name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "P", "update_at": 0, } } isDropdown={false} /> <Connect(CollapseRhsButton) /> </div> </div> </nav> `; exports[`components/ChannelHeaderMobile/ChannelHeaderMobile should match snapshot, if DM channel 1`] = ` <nav className="navbar navbar-default navbar-fixed-top" id="navbar" role="navigation" > <div className="container-fluid theme" > <div className="navbar-header" > <Connect(CollapseLhsButton) /> <div className="navbar-brand" > <Connect(injectIntl(MobileChannelHeaderDropdown)) /> </div> <div className="spacer" /> <Connect(NavbarInfoButton) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "display_name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "user_id_1__user_id_2", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "D", "update_at": 0, } } /> <Connect(ShowSearchButton) /> <Connect(injectIntl(MobileChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "display_name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "user_id_1__user_id_2", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "D", "update_at": 0, } } isDropdown={false} /> <Connect(CollapseRhsButton) /> </div> </div> </nav> `;
1,697
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/channel_info_button/channel_info_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; import ChannelInfoButton from './channel_info_button'; describe('components/ChannelHeaderMobile/ChannelInfoButton', () => { const baseProps = { channel: TestHelper.getChannelMock({ id: 'channel_id', }), actions: { showChannelInfo: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = mountWithIntl( <ChannelInfoButton {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,700
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/channel_info_button
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/channel_info_button/__snapshots__/channel_info_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderMobile/ChannelInfoButton should match snapshot 1`] = ` <NavbarInfoButton actions={ Object { "showChannelInfo": [MockFunction], } } channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } > <button aria-label="Info" className="navbar-toggle navbar-right__icon navbar-info-button pull-right" onClick={[Function]} > <InfoIcon aria-hidden="true" className="icon icon__info" > <span aria-hidden="true" className="icon icon__info" > <svg aria-label="Info Icon" height="18px" role="img" viewBox="0 0 22 22" width="18px" > <g fill="inherit" fillRule="evenodd" stroke="none" strokeWidth="1" > <g fill="inherit" transform="translate(-388.000000, -18.000000)" > <g> <g transform="translate(381.000000, 11.000000)" > <g transform="translate(7.000000, 7.000000)" > <path d="M11,22 C4.92486775,22 0,17.0751322 0,11 C0,4.92486775 4.92486775,0 11,0 C17.0751322,0 22,4.92486775 22,11 C22,17.0751322 17.0751322,22 11,22 Z M11,20.7924685 C16.408231,20.7924685 20.7924685,16.408231 20.7924685,11 C20.7924685,5.59176898 16.408231,1.20753149 11,1.20753149 C5.59176898,1.20753149 1.20753149,5.59176898 1.20753149,11 C1.20753149,16.408231 5.59176898,20.7924685 11,20.7924685 Z M10.1572266,16.0625 L10.1572266,8.69335938 L11.3466797,8.69335938 L11.3466797,16.0625 L10.1572266,16.0625 Z M10.7519531,7.50390625 C10.3417969,7.50390625 10,7.16210938 10,6.75195312 C10,6.33496094 10.3417969,6 10.7519531,6 C11.1689453,6 11.5039062,6.33496094 11.5039062,6.75195312 C11.5039062,7.16210938 11.1689453,7.50390625 10.7519531,7.50390625 Z" /> </g> </g> </g> </g> </g> </svg> </span> </InfoIcon> </button> </NavbarInfoButton> `;
1,708
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/unmute_channel_button/unmute_channel_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 {NotificationLevels} from 'utils/constants'; import UnmuteChannelButton from './unmute_channel_button'; describe('components/ChannelHeaderMobile/UnmuteChannelButton', () => { const baseProps = { user: { id: 'user_id', }, channel: { id: 'channel_id', }, actions: { updateChannelNotifyProps: jest.fn(), }, }; it('should match snapshot', () => { const wrapper = shallow(<UnmuteChannelButton {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should runs updateChannelNotifyProps on click', () => { const props = baseProps; props.actions.updateChannelNotifyProps = jest.fn(); const wrapper = shallow(<UnmuteChannelButton {...props}/>); wrapper.simulate('click'); expect(props.actions.updateChannelNotifyProps).toBeCalledWith( props.user.id, props.channel.id, {mark_unread: NotificationLevels.ALL}, ); }); });
1,710
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/unmute_channel_button
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_mobile/unmute_channel_button/__snapshots__/unmute_channel_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderMobile/UnmuteChannelButton should match snapshot 1`] = ` <button className="navbar-toggle icon icon__mute" onClick={[Function]} type="button" > <span className="fa fa-bell-slash-o icon" /> </button> `;
1,712
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/about_area_channel.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 {DeepPartial} from '@mattermost/types/utilities'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import type {GlobalState} from 'types/store'; import AboutAreaChannel from './about_area_channel'; const initialState: DeepPartial<GlobalState> = { entities: { channels: { currentChannelId: 'current_channel_id', myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, }, channels: { current_channel_id: { id: 'current_channel_id', name: 'default-name', display_name: 'Default', delete_at: 0, type: 'O', team_id: 'team_id', }, current_user_id__existingId: { id: 'current_user_id__existingId', name: 'current_user_id__existingId', display_name: 'Default', delete_at: 0, type: 'D', team_id: 'team_id', }, }, channelsInTeam: { 'team-id': ['current_channel_id'], }, messageCounts: { current_channel_id: {total: 10}, current_user_id__existingId: {total: 0}, }, }, teams: { currentTeamId: 'team-id', teams: { 'team-id': { id: 'team_id', name: 'team-1', display_name: 'Team 1', }, }, myMembers: { 'team-id': {roles: 'team_role'}, }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_role'}, }, }, groups: { groups: {}, syncables: {}, myGroups: [], stats: {}, }, emojis: {customEmoji: {}}, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, }, }, roles: { roles: { system_role: { permissions: [], }, team_role: { permissions: [], }, channel_role: { permissions: [], }, }, }, general: { license: {IsLicensed: 'false'}, serverVersion: '5.4.0', config: {PostEditTimeLimit: '-1'}, }, }, }; describe('channel_info_rhs/about_area_channel', () => { const defaultProps = { channel: { id: 'test-c-id', header: 'my channel header', purpose: 'my channel purpose', } as Channel, channelURL: 'https://my-url.mm', canEditChannelProperties: true, actions: { editChannelPurpose: jest.fn(), editChannelHeader: jest.fn(), }, }; test('should display channel purpose', () => { renderWithContext( <AboutAreaChannel {...defaultProps} />, initialState, ); expect(screen.getByText('my channel purpose')).toBeInTheDocument(); }); test('should display channel header', () => { renderWithContext( <AboutAreaChannel {...defaultProps} />, initialState, ); expect(screen.getByText('my channel header')).toBeInTheDocument(); }); });
1,714
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/about_area_dm.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 {UserProfile} from '@mattermost/types/users'; import type {DeepPartial} from '@mattermost/types/utilities'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import Constants from 'utils/constants'; import type {GlobalState} from 'types/store'; import AboutAreaDM from './about_area_dm'; const initialState: DeepPartial<GlobalState> = { entities: { channels: { currentChannelId: 'current_channel_id', myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, }, channels: { current_channel_id: { id: 'current_channel_id', name: 'default-name', display_name: 'Default', delete_at: 0, type: 'O', team_id: 'team_id', }, current_user_id__existingId: { id: 'current_user_id__existingId', name: 'current_user_id__existingId', display_name: 'Default', delete_at: 0, type: 'D', team_id: 'team_id', }, }, channelsInTeam: { 'team-id': ['current_channel_id'], }, messageCounts: { current_channel_id: {total: 10}, current_user_id__existingId: {total: 0}, }, }, teams: { currentTeamId: 'team-id', teams: { 'team-id': { id: 'team_id', name: 'team-1', display_name: 'Team 1', }, }, myMembers: { 'team-id': {roles: 'team_role'}, }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_role'}, }, }, groups: { groups: {}, syncables: {}, myGroups: [], stats: {}, }, emojis: {customEmoji: {}}, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, }, }, roles: { roles: { system_role: { permissions: [], }, team_role: { permissions: [], }, channel_role: { permissions: [], }, }, }, general: { license: {IsLicensed: 'false'}, serverVersion: '5.4.0', config: {PostEditTimeLimit: '-1'}, }, }, }; describe('channel_info_rhs/about_area_dm', () => { const defaultProps = { channel: { id: 'test-c-id', header: 'my channel header', } as Channel, dmUser: { user: { id: 'test-u-id', last_picture_update: 1234, is_bot: false, username: 'my_username', bot_description: 'my bot description', position: 'my position', } as UserProfile, display_name: 'my_username', is_guest: false, status: Constants.UserStatuses.ONLINE, }, actions: { editChannelHeader: jest.fn(), }, }; test('should display user avatar', () => { renderWithContext( <AboutAreaDM {...defaultProps} />, initialState, ); expect(screen.getByAltText('my_username profile image')).toBeInTheDocument(); }); test('should display user name', () => { renderWithContext( <AboutAreaDM {...defaultProps} />, initialState, ); expect(screen.getByText('my_username')).toBeInTheDocument(); }); test('should display user position', () => { renderWithContext( <AboutAreaDM {...defaultProps} />, initialState, ); expect(screen.getByText('my position')).toBeInTheDocument(); }); test('should display bot tag', () => { const props = { ...defaultProps, dmUser: { ...defaultProps.dmUser, user: { ...defaultProps.dmUser.user, is_bot: true, }, }, }; const {container} = renderWithContext( <AboutAreaDM {...props} />, initialState, ); expect(container.querySelector('.Tag')).toBeInTheDocument(); expect(container.querySelector('.Tag')).toHaveTextContent('BOT'); }); test('should display guest tag', () => { const props = { ...defaultProps, dmUser: { ...defaultProps.dmUser, is_guest: true, }, }; const {container} = renderWithContext( <AboutAreaDM {...props} />, initialState, ); expect(container.querySelector('.Tag')).toBeInTheDocument(); expect(container.querySelector('.Tag')).toHaveTextContent('GUEST'); }); test('should display bot description', () => { const props = { ...defaultProps, dmUser: { ...defaultProps.dmUser, user: { ...defaultProps.dmUser.user, is_bot: true, }, }, }; renderWithContext( <AboutAreaDM {...props} />, initialState, ); expect(screen.getByText('my bot description')).toBeInTheDocument(); }); test('should display channel header', () => { renderWithContext( <AboutAreaDM {...defaultProps} />, initialState, ); expect(screen.getByText('my channel header')).toBeInTheDocument(); }); test('should not display channel header for bots', () => { const props = { ...defaultProps, dmUser: { ...defaultProps.dmUser, user: { ...defaultProps.dmUser.user, is_bot: true, }, }, }; renderWithContext( <AboutAreaDM {...props} />, initialState, ); expect(screen.queryByText('my channel header')).not.toBeInTheDocument(); }); });
1,716
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/about_area_gm.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 {UserProfile} from '@mattermost/types/users'; import type {DeepPartial} from '@mattermost/types/utilities'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import type {GlobalState} from 'types/store'; import AboutAreaGM from './about_area_gm'; const initialState: DeepPartial<GlobalState> = { entities: { channels: { currentChannelId: 'current_channel_id', myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, }, channels: { current_channel_id: { id: 'current_channel_id', name: 'default-name', display_name: 'Default', delete_at: 0, type: 'O', team_id: 'team_id', }, current_user_id__existingId: { id: 'current_user_id__existingId', name: 'current_user_id__existingId', display_name: 'Default', delete_at: 0, type: 'D', team_id: 'team_id', }, }, channelsInTeam: { 'team-id': ['current_channel_id'], }, messageCounts: { current_channel_id: {total: 10}, current_user_id__existingId: {total: 0}, }, }, teams: { currentTeamId: 'team-id', teams: { 'team-id': { id: 'team_id', name: 'team-1', display_name: 'Team 1', }, }, myMembers: { 'team-id': {roles: 'team_role'}, }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_role'}, 'test-u-id': {username: 'my username'}, 'test-u-id2': {username: 'my username 2'}, }, }, groups: { groups: {}, syncables: {}, myGroups: [], stats: {}, }, emojis: {customEmoji: {}}, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, }, }, roles: { roles: { system_role: { permissions: [], }, team_role: { permissions: [], }, channel_role: { permissions: [], }, }, }, general: { license: {IsLicensed: 'false'}, serverVersion: '5.4.0', config: {PostEditTimeLimit: '-1'}, }, }, views: { browser: { windowSize: '', }, }, }; describe('channel_info_rhs/about_area_gm', () => { const defaultProps = { channel: { id: 'test-c-id', header: 'my channel header', } as Channel, gmUsers: [ { id: 'test-u-id', last_picture_update: 1234, username: 'my username', } as UserProfile, { id: 'test-u-id2', last_picture_update: 4321, username: 'my username2', } as UserProfile, ], actions: { editChannelHeader: jest.fn(), }, }; test('should display users avatar', () => { renderWithContext( <AboutAreaGM {...defaultProps} />, initialState, ); expect(screen.getByAltText('my username profile image')).toBeInTheDocument(); expect(screen.getByAltText('my username2 profile image')).toBeInTheDocument(); }); test('should display user names', () => { renderWithContext( <AboutAreaGM {...defaultProps} />, initialState, ); expect(screen.getByLabelText('my username')).toBeInTheDocument(); }); test('should display channel header', () => { renderWithContext( <AboutAreaGM {...defaultProps} />, initialState, ); expect(screen.getByText('my channel header')).toBeInTheDocument(); }); });
1,718
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/channel_info_rhs.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {Channel, ChannelStats} from '@mattermost/types/channels'; import type {Team} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {act, renderWithContext} from 'tests/react_testing_utils'; import ChannelInfoRHS from './channel_info_rhs'; const mockAboutArea = jest.fn(); jest.mock('./about_area', () => (props: any) => { mockAboutArea(props); return <div>{'test-about-area'}</div>; }); describe('channel_info_rhs', () => { const OriginalProps = { channel: {display_name: 'my channel title', type: 'O'} as Channel, isArchived: false, channelStats: {} as ChannelStats, currentUser: {} as UserProfile, currentTeam: {} as Team, isFavorite: false, isMuted: false, isInvitingPeople: false, isMobile: false, canManageMembers: true, canManageProperties: true, channelMembers: [], actions: { closeRightHandSide: jest.fn(), unfavoriteChannel: jest.fn(), favoriteChannel: jest.fn(), unmuteChannel: jest.fn(), muteChannel: jest.fn(), openModal: jest.fn(), showChannelFiles: jest.fn(), showPinnedPosts: jest.fn(), showChannelMembers: jest.fn(), getChannelStats: jest.fn().mockImplementation(() => Promise.resolve({data: {}})), }, }; let props = {...OriginalProps}; beforeEach(() => { props = {...OriginalProps}; }); describe('about area', () => { test('should be editable', async () => { renderWithContext( <ChannelInfoRHS {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); expect(mockAboutArea).toHaveBeenCalledWith( expect.objectContaining({ canEditChannelProperties: true, }), ); }); test('should not be editable in archived channel', async () => { props.isArchived = true; renderWithContext( <ChannelInfoRHS {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); expect(mockAboutArea).toHaveBeenCalledWith( expect.objectContaining({ canEditChannelProperties: false, }), ); }); }); });
1,720
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/header.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 {fireEvent, renderWithContext, screen} from 'tests/react_testing_utils'; import Header from './header'; describe('channel_info_rhs/header', () => { test('should the current channel name', () => { renderWithContext( <Header channel={{display_name: 'my channel title'} as Channel} isMobile={false} isArchived={false} onClose={() => {}} />, ); expect(screen.getByText('my channel title')).toBeInTheDocument(); }); test('should call onClose when clicking on the close icon', () => { const onClose = jest.fn(); renderWithContext( <Header channel={{display_name: 'my channel title'} as Channel} isMobile={false} isArchived={false} onClose={onClose} />, ); fireEvent.click(screen.getByLabelText('Close Sidebar Icon')); expect(onClose).toHaveBeenCalled(); }); test('should call onClose when clicking on the back icon', () => { const onClose = jest.fn(); renderWithContext( <Header channel={{display_name: 'my channel title'} as Channel} isMobile={true} isArchived={false} onClose={onClose} />, ); fireEvent.click(screen.getByLabelText('Back Icon')); expect(onClose).toHaveBeenCalled(); }); test('should have archived icon when channel is archived', () => { const {container} = renderWithContext( <Header channel={{display_name: 'my channel title'} as Channel} isMobile={false} isArchived={true} onClose={() => {}} />, ); expect(container.querySelector('i.icon-archive-outline')).toBeInTheDocument(); }); test('should not have archived icon when channel is archived', () => { const {container} = renderWithContext( <Header channel={{display_name: 'my channel title'} as Channel} isMobile={false} isArchived={false} onClose={() => {}} />, ); expect(container.querySelector('i.icon-archive-outline')).not.toBeInTheDocument(); }); });
1,723
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {Channel, ChannelStats} from '@mattermost/types/channels'; import { act, fireEvent, renderWithContext, screen, } from 'tests/react_testing_utils'; import Constants from 'utils/constants'; import Menu from './menu'; describe('channel_info_rhs/menu', () => { const defaultProps = { channel: {type: Constants.OPEN_CHANNEL} as Channel, channelStats: {files_count: 3, pinnedpost_count: 12, member_count: 32} as ChannelStats, isArchived: false, actions: { openNotificationSettings: jest.fn(), showChannelFiles: jest.fn(), showPinnedPosts: jest.fn(), showChannelMembers: jest.fn(), getChannelStats: jest.fn().mockImplementation(() => Promise.resolve({data: {files_count: 3, pinnedpost_count: 12, member_count: 32}})), }, }; beforeEach(() => { defaultProps.actions = { openNotificationSettings: jest.fn(), showChannelFiles: jest.fn(), showPinnedPosts: jest.fn(), showChannelMembers: jest.fn(), getChannelStats: jest.fn().mockImplementation(() => Promise.resolve({data: {files_count: 3, pinnedpost_count: 12, member_count: 32}})), }; }); test('should display notifications preferences', async () => { const props = {...defaultProps}; props.actions.openNotificationSettings = jest.fn(); renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); expect(screen.getByText('Notification Preferences')).toBeInTheDocument(); fireEvent.click(screen.getByText('Notification Preferences')); expect(props.actions.openNotificationSettings).toHaveBeenCalled(); }); test('should NOT display notifications preferences in a DM', async () => { const props = { ...defaultProps, channel: {type: Constants.DM_CHANNEL} as Channel, }; renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); expect(screen.queryByText('Notification Preferences')).not.toBeInTheDocument(); }); test('should NOT display notifications preferences in an archived channel', async () => { const props = { ...defaultProps, isArchived: true, }; renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); expect(screen.queryByText('Notification Preferences')).not.toBeInTheDocument(); }); test('should display the number of files', async () => { const props = {...defaultProps}; props.actions.showChannelFiles = jest.fn(); renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); const fileItem = screen.getByText('Files'); expect(fileItem).toBeInTheDocument(); expect(fileItem.parentElement).toHaveTextContent('3'); fireEvent.click(fileItem); expect(props.actions.showChannelFiles).toHaveBeenCalled(); }); test('should display the pinned messages', async () => { const props = {...defaultProps}; props.actions.showPinnedPosts = jest.fn(); renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); const fileItem = screen.getByText('Pinned messages'); expect(fileItem).toBeInTheDocument(); expect(fileItem.parentElement).toHaveTextContent('12'); fireEvent.click(fileItem); expect(props.actions.showPinnedPosts).toHaveBeenCalled(); }); test('should display members', async () => { const props = {...defaultProps}; props.actions.showChannelMembers = jest.fn(); renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); const membersItem = screen.getByText('Members'); expect(membersItem).toBeInTheDocument(); expect(membersItem.parentElement).toHaveTextContent('32'); fireEvent.click(membersItem); expect(props.actions.showChannelMembers).toHaveBeenCalled(); }); test('should NOT display members in DM', async () => { const props = { ...defaultProps, channel: {type: Constants.DM_CHANNEL} as Channel, }; renderWithContext( <Menu {...props} />, ); await act(async () => { props.actions.getChannelStats(); }); const membersItem = screen.queryByText('Members'); expect(membersItem).not.toBeInTheDocument(); }); });
1,725
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/top_buttons.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {fireEvent, renderWithContext, screen} from 'tests/react_testing_utils'; import Constants from 'utils/constants'; import TopButtons from './top_buttons'; import type {Props} from './top_buttons'; const mockOnCopyTextClick = jest.fn(); jest.mock('../common/hooks/useCopyText', () => { return jest.fn(() => { return { copiedRecently: false, copyError: '', onClick: mockOnCopyTextClick, }; }); }); describe('channel_info_rhs/top_buttons', () => { const topButtonDefaultProps: Props = { channelType: Constants.OPEN_CHANNEL, channelURL: 'https://test.com', isFavorite: false, isMuted: false, isInvitingPeople: false, canAddPeople: true, actions: { addPeople: jest.fn(), toggleFavorite: jest.fn(), toggleMute: jest.fn(), }, }; test('should display and toggle Favorite', () => { const toggleFavorite = jest.fn(); // Favorite to Favorited const testProps: Props = { ...topButtonDefaultProps, actions: { ...topButtonDefaultProps.actions, toggleFavorite, }, }; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.getByText('Favorite')).toBeInTheDocument(); fireEvent.click(screen.getByText('Favorite')); expect(toggleFavorite).toHaveBeenCalled(); // Favorited to Favorite toggleFavorite.mockReset(); testProps.isFavorite = true; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.getByText('Favorited')).toBeInTheDocument(); fireEvent.click(screen.getByText('Favorited')); expect(toggleFavorite).toHaveBeenCalled(); }); test('should display and toggle Mute', () => { const toggleMute = jest.fn(); // Mute to Muted const testProps: Props = { ...topButtonDefaultProps, actions: { ...topButtonDefaultProps.actions, toggleMute, }, }; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.getByText('Mute')).toBeInTheDocument(); fireEvent.click(screen.getByText('Mute')); expect(toggleMute).toHaveBeenCalled(); // Muted to Mute toggleMute.mockReset(); testProps.isMuted = true; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.getByText('Muted')).toBeInTheDocument(); fireEvent.click(screen.getByText('Muted')); expect(toggleMute).toHaveBeenCalled(); }); test('should display and active call Add People', () => { const addPeople = jest.fn(); const testProps = { ...topButtonDefaultProps, actions: { ...topButtonDefaultProps.actions, addPeople, }, }; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.getByText('Add People')).toBeInTheDocument(); fireEvent.click(screen.getByText('Add People')); expect(addPeople).toHaveBeenCalled(); }); test('should not Add People in DM', () => { const testProps: Props = { ...topButtonDefaultProps, channelType: Constants.DM_CHANNEL, }; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.queryByText('Add People')).not.toBeInTheDocument(); }); test('should not Add People without permission', () => { const testProps: Props = { ...topButtonDefaultProps, canAddPeople: false, }; renderWithContext( <TopButtons {...testProps} />, ); expect(screen.queryByText('Add People')).not.toBeInTheDocument(); }); test('can copy link', () => { renderWithContext( <TopButtons {...topButtonDefaultProps} />, ); expect(screen.getByText('Copy Link')).toBeInTheDocument(); fireEvent.click(screen.getByText('Copy Link')); expect(mockOnCopyTextClick).toHaveBeenCalled(); }); test('cannot copy link in DM or GM', () => { [ Constants.GM_CHANNEL, Constants.DM_CHANNEL, ].forEach((channelType) => { const localProps: Props = { ...topButtonDefaultProps, channelType, }; renderWithContext( <TopButtons {...localProps} />, ); expect(screen.queryByText('Copy Link')).not.toBeInTheDocument(); }); }); });
1,727
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_info_rhs/components/editable_area.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {fireEvent, renderWithContext, screen} from 'tests/react_testing_utils'; import EditableArea from './editable_area'; describe('channel_info_rhs/components/editable_area', () => { test('should be able to see content', async () => { renderWithContext( <EditableArea content='test content' editable={true} emptyLabel='' onEdit={() => {}} />, ); expect(screen.getByText('test content')).toBeInTheDocument(); }); test('should be able to edit content', async () => { const mockOnEdit = jest.fn(); renderWithContext( <EditableArea content='test content' editable={true} emptyLabel='' onEdit={mockOnEdit} />, ); expect(screen.getByLabelText('Edit')).toBeInTheDocument(); fireEvent.click(screen.getByLabelText('Edit')); expect(mockOnEdit).toHaveBeenCalled(); }); test('should be able prevent edition', async () => { renderWithContext( <EditableArea content='test content' editable={false} emptyLabel='' onEdit={() => {}} />, ); expect(screen.queryByLabelText('Edit')).not.toBeInTheDocument(); }); test('should show the empty label when there\'s no content', async () => { const mockOnEdit = jest.fn(); renderWithContext( <EditableArea content='' editable={true} emptyLabel='No content' onEdit={mockOnEdit} />, ); expect(screen.getByText('No content')).toBeInTheDocument(); // We should be able to click on the text... fireEvent.click(screen.getByText('No content')); // ... or the Edit icon fireEvent.click(screen.getByLabelText('Edit')); expect(mockOnEdit).toHaveBeenCalledTimes(2); }); });
1,730
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal/channel_invite_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {Modal} from 'react-bootstrap'; import type {Channel} from '@mattermost/types/channels'; import type {UserProfile} from '@mattermost/types/users'; import type {RelationOneToOne} from '@mattermost/types/utilities'; import {General} from 'mattermost-redux/constants'; import ChannelInviteModal from 'components/channel_invite_modal/channel_invite_modal'; import type {Value} from 'components/multiselect/multiselect'; type UserProfileValue = Value & UserProfile; jest.mock('utils/utils', () => { const original = jest.requireActual('utils/utils'); return { ...original, localizeMessage: jest.fn(), sortUsersAndGroups: jest.fn(), }; }); describe('components/channel_invite_modal', () => { const users = [{ id: 'user-1', label: 'user-1', value: 'user-1', delete_at: 0, } as UserProfileValue, { id: 'user-2', label: 'user-2', value: 'user-2', delete_at: 0, } as UserProfileValue]; const userStatuses = { 'user-1': 'online', 'user-2': 'offline', } as RelationOneToOne<UserProfile, string>; const channel = { create_at: 1508265709607, creator_id: 'zaktnt8bpbgu8mb6ez9k64r7sa', delete_at: 0, display_name: 'testing', header: 'test', id: 'owsyt8n43jfxjpzh9np93mx1wa', last_post_at: 1508265709635, name: 'testing', purpose: 'test', team_id: 'eatxocwc3bg9ffo9xyybnj4omr', type: 'O', update_at: 1508265709607, } as Channel; const baseProps = { channel, profilesNotInCurrentChannel: [], profilesInCurrentChannel: [], profilesNotInCurrentTeam: [], profilesFromRecentDMs: [], membersInTeam: {}, groups: [], userStatuses: {}, teammateNameDisplaySetting: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, isGroupsEnabled: true, actions: { addUsersToChannel: jest.fn().mockImplementation(() => { const error = { message: 'Failed', }; return Promise.resolve({error}); }), getProfilesNotInChannel: jest.fn().mockImplementation(() => Promise.resolve()), getProfilesInChannel: jest.fn().mockImplementation(() => Promise.resolve()), searchAssociatedGroupsForReference: jest.fn().mockImplementation(() => Promise.resolve()), getTeamStats: jest.fn(), getUserStatuses: jest.fn().mockImplementation(() => Promise.resolve()), loadStatusesForProfilesList: jest.fn(), searchProfiles: jest.fn(), closeModal: jest.fn(), getTeamMembersByIds: jest.fn(), }, onExited: jest.fn(), }; test('should match snapshot for channel_invite_modal with profiles', () => { const wrapper = shallow( <ChannelInviteModal {...baseProps} profilesNotInCurrentChannel={users} profilesInCurrentChannel={[]} profilesNotInCurrentTeam={[]} profilesFromRecentDMs={[]} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for channel_invite_modal with profiles from DMs', () => { const wrapper = shallow( <ChannelInviteModal {...baseProps} profilesNotInCurrentChannel={[]} profilesInCurrentChannel={[]} profilesNotInCurrentTeam={[]} profilesFromRecentDMs={users} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with exclude and include users', () => { const wrapper = shallow( <ChannelInviteModal {...baseProps} profilesNotInCurrentChannel={users} profilesInCurrentChannel={[]} profilesNotInCurrentTeam={[]} profilesFromRecentDMs={[]} includeUsers={ { 'user-3': { id: 'user-3', label: 'user-3', value: 'user-3', delete_at: 0, } as UserProfileValue, } } excludeUsers={ { 'user-1': { id: 'user-1', label: 'user-1', value: 'user-1', delete_at: 0, } as UserProfileValue, } } />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for channel_invite_modal with userStatuses', () => { const wrapper = shallow( <ChannelInviteModal {...baseProps} profilesNotInCurrentChannel={users} profilesInCurrentChannel={[]} userStatuses={userStatuses} profilesFromRecentDMs={[]} />, ); const instance = wrapper.instance() as ChannelInviteModal; expect(instance.renderOption(users[0], true, jest.fn(), jest.fn())).toMatchSnapshot(); }); test('should match state when onHide is called', () => { const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...baseProps}/>, ); wrapper.setState({show: true}); wrapper.instance().onHide(); expect(wrapper.state('show')).toEqual(false); }); test('should have called props.onHide when Modal.onExited is called', () => { const props = {...baseProps}; const wrapper = shallow( <ChannelInviteModal {...props}/>, ); wrapper.find(Modal).props().onExited!(document.createElement('div')); expect(props.onExited).toHaveBeenCalledTimes(1); }); test('should fail to add users on handleSubmit', (done) => { const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...baseProps} />, ); wrapper.setState({selectedUsers: users, show: true}); wrapper.instance().handleSubmit(); expect(wrapper.state('saving')).toEqual(true); expect(wrapper.instance().props.actions.addUsersToChannel).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('inviteError')).toEqual('Failed'); expect(wrapper.state('saving')).toEqual(false); done(); }); }); test('should add users on handleSubmit', (done) => { const props = { ...baseProps, actions: { ...baseProps.actions, addUsersToChannel: jest.fn().mockImplementation(() => { const data = true; return Promise.resolve({data}); }), }, }; const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...props} />, ); wrapper.setState({selectedUsers: users, show: true}); wrapper.instance().handleSubmit(); expect(wrapper.state('saving')).toEqual(true); expect(wrapper.instance().props.actions.addUsersToChannel).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('inviteError')).toBeUndefined(); expect(wrapper.state('saving')).toEqual(false); expect(wrapper.state('show')).toEqual(false); done(); }); }); test('should call onAddCallback on handleSubmit with skipCommit', () => { const onAddCallback = jest.fn(); const props = { ...baseProps, skipCommit: true, onAddCallback, }; const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...props} />, ); wrapper.setState({selectedUsers: users, show: true}); wrapper.instance().handleSubmit(); expect(onAddCallback).toHaveBeenCalled(); expect(wrapper.instance().props.actions.addUsersToChannel).toHaveBeenCalledTimes(0); }); test('should trim the search term', () => { const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...baseProps}/>, ); wrapper.instance().search(' something '); expect(wrapper.state('term')).toEqual('something'); }); test('should send the invite as guest param through the link', () => { const props = { ...baseProps, canInviteGuests: true, emailInvitationsEnabled: true, }; const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...props}/>, ); const invitationLink = wrapper.find('InviteModalLink'); expect(invitationLink).toHaveLength(1); expect(invitationLink.prop('inviteAsGuest')).toBeTruthy(); }); test('should hide the invite as guest param when can not invite guests', () => { const props = { ...baseProps, canInviteGuests: false, emailInvitationsEnabled: false, }; const wrapper = shallow<ChannelInviteModal>( <ChannelInviteModal {...props}/>, ); const invitationLink = wrapper.find('InviteModalLink'); expect(invitationLink).toHaveLength(0); }); });
1,733
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal/__snapshots__/channel_invite_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/channel_invite_modal should match snapshot for channel_invite_modal with profiles 1`] = ` <Modal animation={true} aria-labelledby="channelInviteModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal channel-invite" dialogComponentClass={[Function]} enforceFocus={true} id="addUsersToChannelModal" 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" id="channelInviteModalLabel" /> <ModalBody bsClass="modal-body" className="overflow--visible" componentClass="div" role="application" > <div className="channel-invite__header" > <h1> <MemoizedFormattedMessage defaultMessage="Add people to {channel}" id="channel_invite.addNewMembers" values={ Object { "channel": "testing", } } /> </h1> </div> <div className="channel-invite__content" > <MultiSelect ariaLabelRenderer={[Function]} backButtonClass="btn-tertiary tertiary-button" backButtonClick={[Function]} customNoOptionsMessage={null} focusOnLoad={true} handleAdd={[Function]} handleCancel={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addUsersToChannelKey" loading={true} optionRenderer={[Function]} options={Array []} perPage={50} saveButtonPosition="bottom" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueWithImage={true} values={Array []} /> <Memo(TeamWarningBanner) guests={Array []} teamId="eatxocwc3bg9ffo9xyybnj4omr" users={Array []} /> </div> </ModalBody> </Modal> `; exports[`components/channel_invite_modal should match snapshot for channel_invite_modal with profiles from DMs 1`] = ` <Modal animation={true} aria-labelledby="channelInviteModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal channel-invite" dialogComponentClass={[Function]} enforceFocus={true} id="addUsersToChannelModal" 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" id="channelInviteModalLabel" /> <ModalBody bsClass="modal-body" className="overflow--visible" componentClass="div" role="application" > <div className="channel-invite__header" > <h1> <MemoizedFormattedMessage defaultMessage="Add people to {channel}" id="channel_invite.addNewMembers" values={ Object { "channel": "testing", } } /> </h1> </div> <div className="channel-invite__content" > <MultiSelect ariaLabelRenderer={[Function]} backButtonClass="btn-tertiary tertiary-button" backButtonClick={[Function]} customNoOptionsMessage={null} focusOnLoad={true} handleAdd={[Function]} handleCancel={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addUsersToChannelKey" loading={true} optionRenderer={[Function]} options={Array []} perPage={50} saveButtonPosition="bottom" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueWithImage={true} values={Array []} /> <Memo(TeamWarningBanner) guests={Array []} teamId="eatxocwc3bg9ffo9xyybnj4omr" users={Array []} /> </div> </ModalBody> </Modal> `; exports[`components/channel_invite_modal should match snapshot for channel_invite_modal with userStatuses 1`] = ` <Memo(GroupOption) addUserProfile={[MockFunction]} group={ Object { "delete_at": 0, "id": "user-1", "label": "user-1", "value": "user-1", } } isSelected={true} onMouseMove={[MockFunction]} rowSelected="more-modal__row--selected" selectedItemRef={ Object { "current": null, } } /> `; exports[`components/channel_invite_modal should match snapshot with exclude and include users 1`] = ` <Modal animation={true} aria-labelledby="channelInviteModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal channel-invite" dialogComponentClass={[Function]} enforceFocus={true} id="addUsersToChannelModal" 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" id="channelInviteModalLabel" /> <ModalBody bsClass="modal-body" className="overflow--visible" componentClass="div" role="application" > <div className="channel-invite__header" > <h1> <MemoizedFormattedMessage defaultMessage="Add people to {channel}" id="channel_invite.addNewMembers" values={ Object { "channel": "testing", } } /> </h1> </div> <div className="channel-invite__content" > <MultiSelect ariaLabelRenderer={[Function]} backButtonClass="btn-tertiary tertiary-button" backButtonClick={[Function]} customNoOptionsMessage={null} focusOnLoad={true} handleAdd={[Function]} handleCancel={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addUsersToChannelKey" loading={true} optionRenderer={[Function]} options={Array []} perPage={50} saveButtonPosition="bottom" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueWithImage={true} values={Array []} /> <Memo(TeamWarningBanner) guests={Array []} teamId="eatxocwc3bg9ffo9xyybnj4omr" users={Array []} /> </div> </ModalBody> </Modal> `;
1,737
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal/team_warning_banner/team_warning_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 type {UserProfile} from '@mattermost/types/users'; import TeamWarningBanner from 'components/channel_invite_modal/team_warning_banner/team_warning_banner'; import type {Value} from 'components/multiselect/multiselect'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; type UserProfileValue = Value & UserProfile; jest.mock('utils/utils', () => { const original = jest.requireActual('utils/utils'); return { ...original, localizeMessage: jest.fn(), sortUsersAndGroups: jest.fn(), }; }); function createUsers(count: number): UserProfileValue[] { const users: UserProfileValue[] = []; for (let x = 0; x < count; x++) { const user = { id: 'user-' + x, username: 'user-' + x, label: 'user-' + x, value: 'user-' + x, delete_at: 0, } as UserProfileValue; users.push(user); } return users; } describe('components/channel_invite_modal/team_warning_banner', () => { const teamId = 'team1'; const state = { entities: { channels: {}, teams: { current: {id: 'team1'}, teams: { team1: { id: 'team1', display_name: 'Team Name Display', }, }, }, general: { config: {}, }, preferences: { myPreferences: {}, }, users: { currentUserId: 'admin1', profiles: {}, }, groups: { myGroups: {}, groups: {}, }, emojis: { customEmoji: {}, }, }, }; const store = mockStore(state); // beforeEach(() => { // state = {...state}; // }); test('should return empty snapshot', () => { const wrapper = mountWithIntl( <Provider store={store}> <TeamWarningBanner teamId={teamId} users={[]} guests={[]} /> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for team_warning_banner with > 10 profiles', () => { const users = createUsers(11); const wrapper = mountWithIntl( <Provider store={store}> <TeamWarningBanner teamId={teamId} users={users} guests={[]} /> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for team_warning_banner with < 10 profiles', () => { const users = createUsers(2); const wrapper = mountWithIntl( <Provider store={store}> <TeamWarningBanner teamId={teamId} users={users} guests={[]} /> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for team_warning_banner with > 10 guest profiles', () => { const guests = createUsers(11); const wrapper = mountWithIntl( <Provider store={store}> <TeamWarningBanner teamId={teamId} users={[]} guests={guests} /> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for team_warning_banner with < 10 guest profiles', () => { const guests = createUsers(2); const wrapper = mountWithIntl( <Provider store={store}> <TeamWarningBanner teamId={teamId} users={[]} guests={guests} /> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); });
1,739
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal/team_warning_banner
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_invite_modal/team_warning_banner/__snapshots__/team_warning_banner.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/channel_invite_modal/team_warning_banner should match snapshot for team_warning_banner with < 10 guest profiles 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(TeamWarningBanner) guests={ Array [ Object { "delete_at": 0, "id": "user-0", "label": "user-0", "username": "user-0", "value": "user-0", }, Object { "delete_at": 0, "id": "user-1", "label": "user-1", "username": "user-1", "value": "user-1", }, ] } teamId="team1" users={Array []} > <AlertBanner footerMessage={ Array [ <FormattedList value={ Array [ <Memo(Connect(Component)) mentionName="user-0" />, <Memo(Connect(Component)) mentionName="user-1" />, ] } />, " are guest users and need to first be invited to the team before you can add them to the channel. Once they've joined the team, you can add them to this channel.", ] } id="teamWarningBanner" message={false} mode="warning" title={ <Memo(MemoizedFormattedMessage) defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 2, } } /> } variant="app" > <div className="AlertBanner warning AlertBanner--app" data-testid="teamWarningBanner" > <div className="AlertBanner__icon" > <AlertOutlineIcon size={24} > <svg fill="currentColor" height={24} version="1.1" viewBox="0 0 24 24" width={24} xmlns="http://www.w3.org/2000/svg" > <path d="M21.638,16.575L14.64,3.578C14.117,2.605,13.105,2,12,2S9.883,2.605,9.359,3.578L2.362,16.575c-0.505,0.939-0.481,2.046,0.065,2.962C2.974,20.453,3.937,21,5.003,21h13.994c1.066,0,2.029-0.547,2.575-1.463 C22.119,18.622,22.143,17.514,21.638,16.575z M18.995,18.998H5.001c-0.757,0-1.239-0.808-0.88-1.475l6.997-12.997 C11.307,4.175,11.652,4,11.998,4s0.691,0.175,0.88,0.526l6.997,12.997C20.234,18.19,19.752,18.998,18.995,18.998z M12.5,13h-1L11,7 h2L12.5,13z M12.999,16c0,0.552-0.448,1-1,1s-1-0.448-1-1s0.448-1,1-1C12.552,15,12.999,15.448,12.999,16z" /> </svg> </AlertOutlineIcon> </div> <div className="AlertBanner__body" > <div className="AlertBanner__title" > <FormattedMessage defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 2, } } > <span> 2 users were not selected because they are not a part of this team </span> </FormattedMessage> </div> <div className="AlertBanner__footerMessage" > <FormattedList key=".0" value={ Array [ <Memo(Connect(Component)) mentionName="user-0" />, <Memo(Connect(Component)) mentionName="user-1" />, ] } > <span> <Connect(Component) key="user-0" mentionName="user-0" > <Memo(AtMention) currentUserId="admin1" dispatch={[Function]} groupsByName={Object {}} mentionName="user-0" teammateNameDisplay="username" usersByUsername={Object {}} /> </Connect(Component)> and <Connect(Component) key="user-1" mentionName="user-1" > <Memo(AtMention) currentUserId="admin1" dispatch={[Function]} groupsByName={Object {}} mentionName="user-1" teammateNameDisplay="username" usersByUsername={Object {}} /> </Connect(Component)> </span> </FormattedList> are guest users and need to first be invited to the team before you can add them to the channel. Once they've joined the team, you can add them to this channel. </div> </div> </div> </AlertBanner> </Memo(TeamWarningBanner)> </Provider> `; exports[`components/channel_invite_modal/team_warning_banner should match snapshot for team_warning_banner with < 10 profiles 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(TeamWarningBanner) guests={Array []} teamId="team1" users={ Array [ Object { "delete_at": 0, "id": "user-0", "label": "user-0", "username": "user-0", "value": "user-0", }, Object { "delete_at": 0, "id": "user-1", "label": "user-1", "username": "user-1", "value": "user-1", }, ] } > <AlertBanner footerMessage={false} id="teamWarningBanner" message={ Array [ "You can add ", <FormattedList value={ Array [ <Memo(Connect(Component)) mentionName="user-0" />, <Memo(Connect(Component)) mentionName="user-1" />, ] } />, " to this channel once they are members of the ", <strong> Team Name Display </strong>, " team.", ] } mode="warning" title={ <Memo(MemoizedFormattedMessage) defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 2, } } /> } variant="app" > <div className="AlertBanner warning AlertBanner--app" data-testid="teamWarningBanner" > <div className="AlertBanner__icon" > <AlertOutlineIcon size={24} > <svg fill="currentColor" height={24} version="1.1" viewBox="0 0 24 24" width={24} xmlns="http://www.w3.org/2000/svg" > <path d="M21.638,16.575L14.64,3.578C14.117,2.605,13.105,2,12,2S9.883,2.605,9.359,3.578L2.362,16.575c-0.505,0.939-0.481,2.046,0.065,2.962C2.974,20.453,3.937,21,5.003,21h13.994c1.066,0,2.029-0.547,2.575-1.463 C22.119,18.622,22.143,17.514,21.638,16.575z M18.995,18.998H5.001c-0.757,0-1.239-0.808-0.88-1.475l6.997-12.997 C11.307,4.175,11.652,4,11.998,4s0.691,0.175,0.88,0.526l6.997,12.997C20.234,18.19,19.752,18.998,18.995,18.998z M12.5,13h-1L11,7 h2L12.5,13z M12.999,16c0,0.552-0.448,1-1,1s-1-0.448-1-1s0.448-1,1-1C12.552,15,12.999,15.448,12.999,16z" /> </svg> </AlertOutlineIcon> </div> <div className="AlertBanner__body" > <div className="AlertBanner__title" > <FormattedMessage defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 2, } } > <span> 2 users were not selected because they are not a part of this team </span> </FormattedMessage> </div> <div className="AlertBanner__message" > You can add <FormattedList key=".1" value={ Array [ <Memo(Connect(Component)) mentionName="user-0" />, <Memo(Connect(Component)) mentionName="user-1" />, ] } > <span> <Connect(Component) key="user-0" mentionName="user-0" > <Memo(AtMention) currentUserId="admin1" dispatch={[Function]} groupsByName={Object {}} mentionName="user-0" teammateNameDisplay="username" usersByUsername={Object {}} /> </Connect(Component)> and <Connect(Component) key="user-1" mentionName="user-1" > <Memo(AtMention) currentUserId="admin1" dispatch={[Function]} groupsByName={Object {}} mentionName="user-1" teammateNameDisplay="username" usersByUsername={Object {}} /> </Connect(Component)> </span> </FormattedList> to this channel once they are members of the <strong key=".3" > Team Name Display </strong> team. </div> </div> </div> </AlertBanner> </Memo(TeamWarningBanner)> </Provider> `; exports[`components/channel_invite_modal/team_warning_banner should match snapshot for team_warning_banner with > 10 guest profiles 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(TeamWarningBanner) guests={ Array [ Object { "delete_at": 0, "id": "user-0", "label": "user-0", "username": "user-0", "value": "user-0", }, Object { "delete_at": 0, "id": "user-1", "label": "user-1", "username": "user-1", "value": "user-1", }, Object { "delete_at": 0, "id": "user-2", "label": "user-2", "username": "user-2", "value": "user-2", }, Object { "delete_at": 0, "id": "user-3", "label": "user-3", "username": "user-3", "value": "user-3", }, Object { "delete_at": 0, "id": "user-4", "label": "user-4", "username": "user-4", "value": "user-4", }, Object { "delete_at": 0, "id": "user-5", "label": "user-5", "username": "user-5", "value": "user-5", }, Object { "delete_at": 0, "id": "user-6", "label": "user-6", "username": "user-6", "value": "user-6", }, Object { "delete_at": 0, "id": "user-7", "label": "user-7", "username": "user-7", "value": "user-7", }, Object { "delete_at": 0, "id": "user-8", "label": "user-8", "username": "user-8", "value": "user-8", }, Object { "delete_at": 0, "id": "user-9", "label": "user-9", "username": "user-9", "value": "user-9", }, Object { "delete_at": 0, "id": "user-10", "label": "user-10", "username": "user-10", "value": "user-10", }, ] } teamId="team1" users={Array []} > <AlertBanner footerMessage={ Array [ <Memo(Connect(Component)) mentionName="user-0" />, " and ", <SimpleTooltip content="@user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10" id="usernames-overflow" > <span className="add-others-link" > <Memo(MemoizedFormattedMessage) defaultMessage="{count} others" id="channel_invite.invite_team_members.messageOthers" values={ Object { "count": 10, } } /> </span> </SimpleTooltip>, " are guest users and need to first be invited to the team before you can add them to the channel. Once they've joined the team, you can add them to this channel.", ] } id="teamWarningBanner" message={false} mode="warning" title={ <Memo(MemoizedFormattedMessage) defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 11, } } /> } variant="app" > <div className="AlertBanner warning AlertBanner--app" data-testid="teamWarningBanner" > <div className="AlertBanner__icon" > <AlertOutlineIcon size={24} > <svg fill="currentColor" height={24} version="1.1" viewBox="0 0 24 24" width={24} xmlns="http://www.w3.org/2000/svg" > <path d="M21.638,16.575L14.64,3.578C14.117,2.605,13.105,2,12,2S9.883,2.605,9.359,3.578L2.362,16.575c-0.505,0.939-0.481,2.046,0.065,2.962C2.974,20.453,3.937,21,5.003,21h13.994c1.066,0,2.029-0.547,2.575-1.463 C22.119,18.622,22.143,17.514,21.638,16.575z M18.995,18.998H5.001c-0.757,0-1.239-0.808-0.88-1.475l6.997-12.997 C11.307,4.175,11.652,4,11.998,4s0.691,0.175,0.88,0.526l6.997,12.997C20.234,18.19,19.752,18.998,18.995,18.998z M12.5,13h-1L11,7 h2L12.5,13z M12.999,16c0,0.552-0.448,1-1,1s-1-0.448-1-1s0.448-1,1-1C12.552,15,12.999,15.448,12.999,16z" /> </svg> </AlertOutlineIcon> </div> <div className="AlertBanner__body" > <div className="AlertBanner__title" > <FormattedMessage defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 11, } } > <span> 11 users were not selected because they are not a part of this team </span> </FormattedMessage> </div> <div className="AlertBanner__footerMessage" > <Connect(Component) key=".$user-0" mentionName="user-0" > <Memo(AtMention) currentUserId="admin1" dispatch={[Function]} groupsByName={Object {}} mentionName="user-0" teammateNameDisplay="username" usersByUsername={Object {}} /> </Connect(Component)> and <SimpleTooltip content="@user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10" id="usernames-overflow" key=".2" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="usernames-overflow" placement="top" > @user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="usernames-overflow" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > @user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <span className="add-others-link" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <FormattedMessage defaultMessage="{count} others" id="channel_invite.invite_team_members.messageOthers" values={ Object { "count": 10, } } > <span> 10 others </span> </FormattedMessage> </span> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> are guest users and need to first be invited to the team before you can add them to the channel. Once they've joined the team, you can add them to this channel. </div> </div> </div> </AlertBanner> </Memo(TeamWarningBanner)> </Provider> `; exports[`components/channel_invite_modal/team_warning_banner should match snapshot for team_warning_banner with > 10 profiles 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(TeamWarningBanner) guests={Array []} teamId="team1" users={ Array [ Object { "delete_at": 0, "id": "user-0", "label": "user-0", "username": "user-0", "value": "user-0", }, Object { "delete_at": 0, "id": "user-1", "label": "user-1", "username": "user-1", "value": "user-1", }, Object { "delete_at": 0, "id": "user-2", "label": "user-2", "username": "user-2", "value": "user-2", }, Object { "delete_at": 0, "id": "user-3", "label": "user-3", "username": "user-3", "value": "user-3", }, Object { "delete_at": 0, "id": "user-4", "label": "user-4", "username": "user-4", "value": "user-4", }, Object { "delete_at": 0, "id": "user-5", "label": "user-5", "username": "user-5", "value": "user-5", }, Object { "delete_at": 0, "id": "user-6", "label": "user-6", "username": "user-6", "value": "user-6", }, Object { "delete_at": 0, "id": "user-7", "label": "user-7", "username": "user-7", "value": "user-7", }, Object { "delete_at": 0, "id": "user-8", "label": "user-8", "username": "user-8", "value": "user-8", }, Object { "delete_at": 0, "id": "user-9", "label": "user-9", "username": "user-9", "value": "user-9", }, Object { "delete_at": 0, "id": "user-10", "label": "user-10", "username": "user-10", "value": "user-10", }, ] } > <AlertBanner footerMessage={false} id="teamWarningBanner" message={ Array [ "You can add ", <Memo(Connect(Component)) mentionName="user-0" />, " and ", <SimpleTooltip content="@user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10" id="usernames-overflow" > <span className="add-others-link" > <Memo(MemoizedFormattedMessage) defaultMessage="{count} others" id="channel_invite.invite_team_members.messageOthers" values={ Object { "count": 10, } } /> </span> </SimpleTooltip>, " to this channel once they are members of the ", <strong> Team Name Display </strong>, " team.", ] } mode="warning" title={ <Memo(MemoizedFormattedMessage) defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 11, } } /> } variant="app" > <div className="AlertBanner warning AlertBanner--app" data-testid="teamWarningBanner" > <div className="AlertBanner__icon" > <AlertOutlineIcon size={24} > <svg fill="currentColor" height={24} version="1.1" viewBox="0 0 24 24" width={24} xmlns="http://www.w3.org/2000/svg" > <path d="M21.638,16.575L14.64,3.578C14.117,2.605,13.105,2,12,2S9.883,2.605,9.359,3.578L2.362,16.575c-0.505,0.939-0.481,2.046,0.065,2.962C2.974,20.453,3.937,21,5.003,21h13.994c1.066,0,2.029-0.547,2.575-1.463 C22.119,18.622,22.143,17.514,21.638,16.575z M18.995,18.998H5.001c-0.757,0-1.239-0.808-0.88-1.475l6.997-12.997 C11.307,4.175,11.652,4,11.998,4s0.691,0.175,0.88,0.526l6.997,12.997C20.234,18.19,19.752,18.998,18.995,18.998z M12.5,13h-1L11,7 h2L12.5,13z M12.999,16c0,0.552-0.448,1-1,1s-1-0.448-1-1s0.448-1,1-1C12.552,15,12.999,15.448,12.999,16z" /> </svg> </AlertOutlineIcon> </div> <div className="AlertBanner__body" > <div className="AlertBanner__title" > <FormattedMessage defaultMessage="{count, plural, =1 {1 user was} other {# users were}} not selected because they are not a part of this team" id="channel_invite.invite_team_members.title" values={ Object { "count": 11, } } > <span> 11 users were not selected because they are not a part of this team </span> </FormattedMessage> </div> <div className="AlertBanner__message" > You can add <Connect(Component) key=".$user-0" mentionName="user-0" > <Memo(AtMention) currentUserId="admin1" dispatch={[Function]} groupsByName={Object {}} mentionName="user-0" teammateNameDisplay="username" usersByUsername={Object {}} /> </Connect(Component)> and <SimpleTooltip content="@user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10" id="usernames-overflow" key=".3" > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip className="hidden-xs" id="usernames-overflow" placement="top" > @user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={500} overlay={ <OverlayWrapper className="hidden-xs" id="usernames-overflow" intl={ Object { "$t": [Function], "defaultFormats": Object {}, "defaultLocale": "en", "defaultRichTextElements": undefined, "fallbackOnEmptyString": true, "formatDate": [Function], "formatDateTimeRange": [Function], "formatDateToParts": [Function], "formatDisplayName": [Function], "formatList": [Function], "formatListToParts": [Function], "formatMessage": [Function], "formatNumber": [Function], "formatNumberToParts": [Function], "formatPlural": [Function], "formatRelativeTime": [Function], "formatTime": [Function], "formatTimeToParts": [Function], "formats": Object {}, "formatters": Object { "getDateTimeFormat": [Function], "getDisplayNames": [Function], "getListFormat": [Function], "getMessageFormat": [Function], "getNumberFormat": [Function], "getPluralRules": [Function], "getRelativeTimeFormat": [Function], }, "locale": "en", "messages": Object {}, "onError": [Function], "onWarn": [Function], "textComponent": "span", "timeZone": "Etc/UTC", "wrapRichTextChunksInFragment": undefined, } } placement="top" > @user-1, @user-2, @user-3, @user-4, @user-5, @user-6, @user-7, @user-8, @user-9, @user-10 </OverlayWrapper> } placement="top" trigger={ Array [ "hover", "focus", ] } > <span className="add-others-link" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <FormattedMessage defaultMessage="{count} others" id="channel_invite.invite_team_members.messageOthers" values={ Object { "count": 10, } } > <span> 10 others </span> </FormattedMessage> </span> </OverlayTrigger> </OverlayTrigger> </SimpleTooltip> to this channel once they are members of the <strong key=".5" > Team Name Display </strong> team. </div> </div> </div> </AlertBanner> </Memo(TeamWarningBanner)> </Provider> `; exports[`components/channel_invite_modal/team_warning_banner should return empty snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <Memo(TeamWarningBanner) guests={Array []} teamId="team1" users={Array []} /> </Provider> `;
1,740
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout/channel_controller.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {getClassnamesForBody} from './channel_controller'; jest.mock('components/reset_status_modal', () => () => <div/>); jest.mock('components/sidebar', () => () => <div/>); jest.mock('components/channel_layout/center_channel', () => () => <div/>); jest.mock('components/loading_screen', () => () => <div/>); jest.mock('components/favicon_title_handler', () => () => <div/>); jest.mock('components/product_notices_modal', () => () => <div/>); jest.mock('plugins/pluggable', () => () => <div/>); describe('components/channel_layout/ChannelController', () => { test('Should have app__body and channel-view classes by default', () => { expect(getClassnamesForBody('')).toEqual(['app__body', 'channel-view']); }); test('Should have os--windows class on body for windows 32 or windows 64', () => { expect(getClassnamesForBody('Win32')).toEqual(['app__body', 'channel-view', 'os--windows']); expect(getClassnamesForBody('Win64')).toEqual(['app__body', 'channel-view', 'os--windows']); }); test('Should have os--mac class on body for MacIntel or MacPPC', () => { expect(getClassnamesForBody('MacIntel')).toEqual(['app__body', 'channel-view', 'os--mac']); expect(getClassnamesForBody('MacPPC')).toEqual(['app__body', 'channel-view', 'os--mac']); }); });
1,743
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout/center_channel/center_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 CenterChannel from './center_channel'; import type {OwnProps} from './index'; describe('components/channel_layout/CenterChannel', () => { const props = { location: { pathname: '/some', } as OwnProps['location'], match: { url: '/url', } as OwnProps['match'], history: {} as OwnProps['history'], lastChannelPath: '', lhsOpen: true, rhsOpen: true, rhsMenuOpen: true, isCollapsedThreadsEnabled: true, currentUserId: 'testUserId', isMobileView: false, actions: { getProfiles: jest.fn, }, }; test('should call update returnTo on props change', () => { const wrapper = shallow(<CenterChannel {...props}/>); expect(wrapper.state('returnTo')).toBe(''); wrapper.setProps({ location: { pathname: '/pl/path', }, }); expect(wrapper.state('returnTo')).toBe('/some'); wrapper.setProps({ location: { pathname: '/pl/path1', }, }); expect(wrapper.state('returnTo')).toBe('/pl/path'); }); });
1,746
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout/channel_identifier_router/actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import {getChannelByNameAndTeamName, getChannelMember, joinChannel} from 'mattermost-redux/actions/channels'; import {getUserByEmail} from 'mattermost-redux/actions/users'; import {Client4} from 'mattermost-redux/client'; import {emitChannelClickEvent} from 'actions/global_actions'; import { goToChannelByChannelName, goToDirectChannelByUserId, goToDirectChannelByUserIds, goToChannelByChannelId, goToDirectChannelByEmail, getPathFromIdentifier, } from 'components/channel_layout/channel_identifier_router/actions'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import mockStore from 'tests/test_store'; import {joinPrivateChannelPrompt} from 'utils/channel_utils'; jest.mock('actions/global_actions', () => ({ emitChannelClickEvent: jest.fn(), })); jest.mock('mattermost-redux/actions/channels', () => ({ joinChannel: jest.fn(() => ({type: '', data: {channel: {id: 'channel_id3', name: 'achannel3', team_id: 'team_id1', type: 'O'}}})), getChannelByNameAndTeamName: jest.fn(() => ({type: '', data: {id: 'channel_id3', name: 'achannel3', team_id: 'team_id1', type: 'O'}})), getChannelMember: jest.fn(() => ({type: '', error: {}})), })); jest.mock('mattermost-redux/actions/users', () => ({ getUserByEmail: jest.fn(() => ({type: '', data: {id: 'user_id3', email: '[email protected]', username: 'user3'}})), getUser: jest.fn(() => ({type: '', data: {id: 'user_id3', email: '[email protected]', username: 'user3'}})), })); jest.mock('utils/channel_utils', () => ({ joinPrivateChannelPrompt: jest.fn(() => { return async () => { return {data: {join: true}}; }; }), })); describe('Actions', () => { const channel1 = {id: 'channel_id1', name: 'achannel', team_id: 'team_id1'}; const channel2 = {id: 'channel_id2', name: 'achannel', team_id: 'team_id2'}; const channel3 = {id: 'channel_id3', name: 'achannel3', team_id: 'team_id1', type: 'O'}; const channel4 = {id: 'channel_id4', name: 'additional-abilities---community-systems', team_id: 'team_id1', type: 'O'}; const channel5 = {id: 'channel_id5', name: 'some-group-channel', team_id: 'team_id1', type: 'G'}; const channel6 = {id: 'channel_id6', name: '12345678901234567890123456', team_id: 'team_id1', type: 'O'}; const initialState = { entities: { channels: { currentChannelId: 'channel_id1', channels: {channel_id1: channel1, channel_id2: channel2, channel_id3: channel3, channel_id4: channel4, channel_id5: channel5, channel_id6: channel6}, myMembers: {channel_id1: {channel_id: 'channel_id1', user_id: 'current_user_id'}, channel_id2: {channel_id: 'channel_id2', user_id: 'current_user_id'}}, channelsInTeam: {team_id1: ['channel_id1'], team_id2: ['channel_id2']}, }, teams: { currentTeamId: 'team_id1', teams: { team_id1: { id: 'team_id1', name: 'team1', }, team_id2: { id: 'team_id2', name: 'team2', }, }, }, users: { currentUserId: 'current_user_id', profiles: {user_id2: {id: 'user_id2', username: 'user2', email: '[email protected]'}}, }, general: {license: {IsLicensed: 'false'}, config: {}}, preferences: {myPreferences: {}}, }, }; describe('getPathFromIdentifier', () => { test.each([ {desc: 'identifier is a channel name', expected: 'channel_name', path: 'channels', identifier: 'channelName'}, {desc: 'identifier is a group id', expected: 'group_channel_group_id', path: 'channels', identifier: '9c992e32cc7b3e5651f68b0ead4935fdf40d67ff'}, {desc: 'channel exists and is type G', expected: 'group_channel_group_id', path: 'channels', identifier: 'some-group-channel'}, {desc: 'identifier is a group id', expected: 'group_channel_group_id', path: 'messages', identifier: '9c992e32cc7b3e5651f68b0ead4935fdf40d67ff'}, {desc: 'identifier looks like a group id but matching channel is an open channel', expected: 'channel_name', path: 'channels', identifier: 'additional-abilities--community-systems'}, {desc: 'identifier is in the format userid--userid2', expected: 'channel_name', path: 'channels', identifier: '3y8ujrgtbfn78ja5nfms3qm5jw--3y8ujrgtbfn78ja5nfms3qm5jw'}, {desc: 'identifier is the username', expected: 'direct_channel_username', path: 'messages', identifier: '@user1'}, {desc: 'identifier is the user email', expected: 'direct_channel_email', path: 'messages', identifier: '[email protected]'}, {desc: 'identifier is the user id', expected: 'direct_channel_user_id', path: 'messages', identifier: '3y8ujrgtbfn78ja5nfms3qm5jw'}, {desc: 'the path is not right', expected: 'error', path: 'messages', identifier: 'test'}, ])('Should return $expected if $desc', async ({expected, path, identifier}) => { const res = await getPathFromIdentifier((initialState as any), path, identifier); expect(res).toEqual(expected); }); describe('identifier is 26 char long', () => { beforeAll(() => { TestHelper.initBasic(Client4); }); afterAll(() => { TestHelper.tearDown(); }); test.each([ {desc: 'fetching a channel by id succeeds', expected: 'channel_id', statusCode: 200, identifier: 'pjz4yj7jw7nzmmo3upi4htmt1y'}, {desc: 'fetching a channel by id fails status 404', expected: 'channel_name', statusCode: 404, identifier: 'channelnamethatis26charlon'}, {desc: 'fetching a channel by id fails status not 404', expected: 'error', statusCode: 403, identifier: 'channelnamethatis26charlon'}, {desc: 'identifier is a channel name stored in redux (no fetching happens)', expected: 'channel_name', identifier: '12345678901234567890123456'}, ])('Should return $expected if $desc', async ({expected, statusCode, identifier}) => { const scope = nock(Client4.getBaseRoute()). get(`/channels/${identifier}`). reply(statusCode, {status_code: statusCode}); const res = await getPathFromIdentifier((initialState as any), 'channels', identifier); expect(res).toEqual(expected); expect(scope.isDone()).toBe(Boolean(statusCode)); }); }); }); describe('goToChannelByChannelId', () => { test('switch to public channel we have locally but need to join', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToChannelByChannelId({params: {team: 'team1', identifier: 'channel_id3', path: '/'}, url: ''}, history as any) as any)); expect(joinChannel).toHaveBeenCalledWith('current_user_id', 'team_id1', 'channel_id3', ''); expect(history.replace).toHaveBeenCalledWith('/team1/channels/achannel3'); }); }); describe('goToChannelByChannelName', () => { test('switch to channel on different team with same name', async () => { const testStore = await mockStore(initialState); await testStore.dispatch((goToChannelByChannelName({params: {team: 'team2', identifier: 'achannel', path: '/'}, url: ''}, {} as any) as any)); expect(emitChannelClickEvent).toHaveBeenCalledWith(channel2); }); test('switch to public channel we have locally but need to join', async () => { const testStore = await mockStore(initialState); await testStore.dispatch((goToChannelByChannelName({params: {team: 'team1', identifier: 'achannel3', path: '/'}, url: ''}, {} as any) as any)); expect(joinChannel).toHaveBeenCalledWith('current_user_id', 'team_id1', '', 'achannel3'); expect(emitChannelClickEvent).toHaveBeenCalledWith(channel3); }); test('switch to private channel we don\'t have locally and get prompted if super user and then join', async () => { const testStore = await mockStore({ ...initialState, entities: { ...initialState.entities, users: { ...initialState.entities.users, profiles: { ...initialState.entities.users.profiles, current_user_id: { roles: 'system_admin', }, }, }, }, }); const channel = {id: 'channel_id6', name: 'achannel6', team_id: 'team_id1', type: 'P'}; (joinChannel as jest.Mock).mockReturnValueOnce({type: '', data: {channel}}); (getChannelByNameAndTeamName as jest.Mock).mockReturnValueOnce({type: '', data: channel}); await testStore.dispatch((goToChannelByChannelName({params: {team: 'team1', identifier: channel.name, path: '/'}, url: ''}, {} as any) as any)); expect(getChannelByNameAndTeamName).toHaveBeenCalledWith('team1', channel.name, true); expect(getChannelMember).toHaveBeenCalledWith(channel.id, 'current_user_id'); expect(joinPrivateChannelPrompt).toHaveBeenCalled(); expect(joinChannel).toHaveBeenCalledWith('current_user_id', 'team_id1', '', channel.name); }); }); describe('goToDirectChannelByUserId', () => { test('switch to a direct channel by user id on the same team', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToDirectChannelByUserId({params: {team: 'team1', identifier: 'channel', path: '/'}, url: ''}, history as any, 'user_id2') as any)); expect(history.replace).toHaveBeenCalledWith('/team1/messages/@user2'); }); test('switch to a direct channel by user id on different team', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToDirectChannelByUserId({params: {team: 'team2', identifier: 'channel', path: '/'}, url: ''}, history as any, 'user_id2') as any)); expect(history.replace).toHaveBeenCalledWith('/team2/messages/@user2'); }); }); describe('goToDirectChannelByUserIds', () => { test('switch to a direct channel by name on the same team', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToDirectChannelByUserIds({params: {team: 'team1', identifier: 'current_user_id__user_id2', path: '/'}, url: ''}, history as any) as any)); expect(history.replace).toHaveBeenCalledWith('/team1/messages/@user2'); }); test('switch to a direct channel by name on different team', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToDirectChannelByUserIds({params: {team: 'team2', identifier: 'current_user_id__user_id2', path: '/'}, url: ''}, history as any) as any)); expect(history.replace).toHaveBeenCalledWith('/team2/messages/@user2'); }); }); describe('goToDirectChannelByEmail', () => { test('switch to a direct channel by email with user already existing locally', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToDirectChannelByEmail({params: {team: 'team1', identifier: '[email protected]', path: '/'}, url: ''}, history as any) as any)); expect(getUserByEmail).not.toHaveBeenCalled(); expect(history.replace).toHaveBeenCalledWith('/team1/messages/@user2'); }); test('switch to a direct channel by email with user not existing locally', async () => { const testStore = await mockStore(initialState); const history = {replace: jest.fn()}; await testStore.dispatch((goToDirectChannelByEmail({params: {team: 'team1', identifier: '[email protected]', path: '/'}, url: ''}, history as any) as any)); expect(getUserByEmail).toHaveBeenCalledWith('[email protected]'); expect(history.replace).toHaveBeenCalledWith('/team1/messages/@user3'); }); }); });
1,748
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_layout/channel_identifier_router/channel_identifier_router.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 {getHistory} from 'utils/browser_history'; import ChannelIdentifierRouter from './channel_identifier_router'; jest.useFakeTimers({legacyFakeTimers: true}); describe('components/channel_layout/CenterChannel', () => { const baseProps = { match: { params: { identifier: 'identifier', team: 'team', path: '/path', }, url: '/team/channel/identifier', }, actions: { onChannelByIdentifierEnter: jest.fn(), }, history: [], }; test('should call onChannelByIdentifierEnter on props change', () => { const wrapper = shallow(<ChannelIdentifierRouter {...baseProps}/>); const instance = wrapper.instance(); expect(baseProps.actions.onChannelByIdentifierEnter).toHaveBeenCalledTimes(1); expect(baseProps.actions.onChannelByIdentifierEnter).toHaveBeenLastCalledWith(baseProps); const props2 = { match: { params: { identifier: 'identifier2', team: 'team2', path: '/path2', }, url: '/team2/channel/identifier2', }, }; wrapper.setProps(props2); // expect(propsTest.match).toEqual(props2.match); //Should clear the timeout if url is changed expect(clearTimeout).toHaveBeenCalledWith((instance as any).replaceUrlTimeout); expect(baseProps.actions.onChannelByIdentifierEnter).toHaveBeenCalledTimes(2); expect(baseProps.actions.onChannelByIdentifierEnter).toHaveBeenLastCalledWith({ ...baseProps, match: props2.match, actions: baseProps.actions, }); }); test('should call browserHistory.replace if it is permalink after timer', () => { const props = { ...baseProps, match: { params: { identifier: 'identifier', team: 'team', path: '/path', postid: 'abcd', }, url: '/team/channel/identifier/abcd', }, }; shallow(<ChannelIdentifierRouter {...props}/>); jest.runOnlyPendingTimers(); expect(getHistory().replace).toHaveBeenLastCalledWith('/team/channel/identifier'); }); test('should call browserHistory.replace on props change to permalink', () => { const props = { ...baseProps, match: { params: { identifier: 'identifier1', team: 'team1', path: '/path1', postid: 'abcd', }, url: '/team1/channel/identifier1/abcd', }, }; const wrapper = shallow(<ChannelIdentifierRouter {...baseProps}/>); wrapper.setProps(props); jest.runOnlyPendingTimers(); expect(getHistory().replace).toHaveBeenLastCalledWith('/team1/channel/identifier1'); }); });
1,751
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_dropdown/channel_members_dropdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Channel, ChannelMembership} from '@mattermost/types/channels'; import type {UserProfile} from '@mattermost/types/users'; import type {ActionResult} from 'mattermost-redux/types/actions'; import ChannelMembersDropdown from 'components/channel_members_dropdown/channel_members_dropdown'; import {mockDispatch} from 'packages/mattermost-redux/test/test_store'; import {ModalIdentifiers} from 'utils/constants'; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useDispatch: () => mockDispatch, })); describe('components/channel_members_dropdown', () => { const user = { id: 'user-1', } as UserProfile; const channel = { create_at: 1508265709607, creator_id: 'zaktnt8bpbgu8mb6ez9k64r7sa', delete_at: 0, display_name: 'testing', header: 'test', id: 'owsyt8n43jfxjpzh9np93mx1wa', last_post_at: 1508265709635, name: 'testing', purpose: 'test', team_id: 'eatxocwc3bg9ffo9xyybnj4omr', type: 'O', update_at: 1508265709607, } as Channel; const channelMember = { roles: 'channel_admin', scheme_admin: true, } as ChannelMembership; const baseProps = { channel, user, channelMember, currentUserId: 'current-user-id', canChangeMemberRoles: false, canRemoveMember: true, index: 0, totalUsers: 10, actions: { removeChannelMember: jest.fn().mockImplementation(() => { const error = { message: 'Failed', }; return Promise.resolve({error}); }), getChannelStats: jest.fn(), updateChannelMemberSchemeRoles: jest.fn(), getChannelMember: jest.fn(), openModal: jest.fn(), }, }; test('should match snapshot for dropdown with guest user', () => { const props = { ...baseProps, user: { ...baseProps.user, roles: 'system_guest', }, channelMember: { ...baseProps.channelMember, roles: 'channel_guest', }, canChangeMemberRoles: true, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for dropdown with shared user', () => { const props = { ...baseProps, user: { ...baseProps.user, roles: 'system_user', remote_id: 'fakeid', }, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for not dropdown with guest user', () => { const props = { ...baseProps, user: { ...baseProps.user, roles: 'system_guest', }, channelMember: { ...baseProps.channelMember, roles: 'channel_guest', }, canChangeMemberRoles: false, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for channel_members_dropdown', () => { const wrapper = shallow( <ChannelMembersDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot opening dropdown upwards', () => { const wrapper = shallow( <ChannelMembersDropdown {...baseProps} index={4} totalUsers={5} />, ); expect(wrapper).toMatchSnapshot(); }); test('If a removal is in progress do not execute another removal', () => { const removeMock = jest.fn().mockImplementation(() => { const myPromise = new Promise<ActionResult>((resolve) => { setTimeout(() => { resolve({data: {}}); }, 3000); }); return myPromise; }); const props = { ...baseProps, actions: { ...baseProps.actions, removeChannelMember: removeMock, }, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); wrapper.find('[data-testid="removeFromChannel"]').simulate('click'); wrapper.find('[data-testid="removeFromChannel"]').simulate('click'); expect(removeMock).toHaveBeenCalledTimes(1); }); test('should fail to remove channel member', (done) => { const removeMock = jest.fn().mockImplementation(() => { return Promise.resolve({error: {message: 'Failed'}}); }); const props = { ...baseProps, actions: { ...baseProps.actions, removeChannelMember: removeMock, }, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); wrapper.find('[data-testid="removeFromChannel"]').simulate('click'); process.nextTick(() => { expect(removeMock).toHaveBeenCalledTimes(1); expect(wrapper.find('.has-error.control-label').text()).toEqual('Failed'); done(); }); }); test('should remove the channel member', (done) => { const removeMock = jest.fn().mockImplementation(() => { return Promise.resolve({data: true}); }); const props = { ...baseProps, actions: { ...baseProps.actions, removeChannelMember: removeMock, }, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); wrapper.find('[data-testid="removeFromChannel"]').simulate('click'); process.nextTick(() => { expect(removeMock).toHaveBeenCalledTimes(1); done(); }); }); test('should match snapshot for group_constrained channel', () => { baseProps.channel.group_constrained = true; const wrapper = shallow( <ChannelMembersDropdown {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with role change possible', () => { const wrapper = shallow( <ChannelMembersDropdown {...baseProps} canChangeMemberRoles={true} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when user is current user', () => { const props = { ...baseProps, currentUserId: 'user-1', }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should open a confirmation modal when current user tries to remove themselves from a channel', () => { const removeMock = jest.fn().mockImplementation(() => { const myPromise = new Promise<ActionResult>((resolve) => { setTimeout(() => { resolve({data: {}}); }, 3000); }); return myPromise; }); const props = { ...baseProps, currentUserId: 'user-1', channel: { ...baseProps.channel, group_constrained: false, }, actions: { ...baseProps.actions, removeChannelMember: removeMock, }, }; const wrapper = shallow( <ChannelMembersDropdown {...props}/>, ); expect(wrapper.find('[data-testid="leaveChannel"]').exists()).toBe(true); wrapper.find('[data-testid="leaveChannel"]').simulate('click'); expect(removeMock).not.toHaveBeenCalled(); expect(props.actions.openModal).toHaveBeenCalledWith( expect.objectContaining({ modalId: ModalIdentifiers.LEAVE_PRIVATE_CHANNEL_MODAL, dialogProps: expect.objectContaining({ channel: expect.objectContaining({id: props.channel.id}), }), })); }); });
1,754
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_dropdown
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_dropdown/__snapshots__/channel_members_dropdown.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/channel_members_dropdown should match snapshot for channel_members_dropdown 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button className="dropdown-toggle theme color--link style--none" type="button" > <span className="sr-only" /> <span> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </span> <DropdownIcon /> </button> <Menu ariaLabel="Change the role of channel member" openLeft={true} openUp={false} > <MenuItemAction data-testid="removeFromChannel" isDangerous={true} onClick={[Function]} show={true} text="Remove from Channel" /> </Menu> </MenuWrapper> `; exports[`components/channel_members_dropdown should match snapshot for dropdown with guest user 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button className="dropdown-toggle theme color--link style--none" type="button" > <span className="sr-only" /> <span> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </span> <DropdownIcon /> </button> <Menu ariaLabel="Change the role of channel member" openLeft={true} openUp={false} > <MenuItemAction id="undefined-make-channel-member" onClick={[Function]} show={true} text="Make Channel Member" /> <MenuItemAction data-testid="removeFromChannel" isDangerous={true} onClick={[Function]} show={true} text="Remove from Channel" /> </Menu> </MenuWrapper> `; exports[`components/channel_members_dropdown should match snapshot for dropdown with shared user 1`] = ` <div className="more-modal__shared-actions" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="sharedTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="From trusted organizations" id="shared_user_indicator.tooltip" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <span> <MemoizedFormattedMessage defaultMessage="Shared Member" id="channel_members_dropdown.shared_member" /> <i className="shared-user-icon icon-circle-multiple-outline" /> </span> </OverlayTrigger> </div> `; exports[`components/channel_members_dropdown should match snapshot for group_constrained channel 1`] = ` <div> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </div> `; exports[`components/channel_members_dropdown should match snapshot for not dropdown with guest user 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button className="dropdown-toggle theme color--link style--none" type="button" > <span className="sr-only" /> <span> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </span> <DropdownIcon /> </button> <Menu ariaLabel="Change the role of channel member" openLeft={true} openUp={false} > <MenuItemAction data-testid="removeFromChannel" isDangerous={true} onClick={[Function]} show={true} text="Remove from Channel" /> </Menu> </MenuWrapper> `; exports[`components/channel_members_dropdown should match snapshot opening dropdown upwards 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button className="dropdown-toggle theme color--link style--none" type="button" > <span className="sr-only" /> <span> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </span> <DropdownIcon /> </button> <Menu ariaLabel="Change the role of channel member" openLeft={true} openUp={true} > <MenuItemAction data-testid="removeFromChannel" isDangerous={true} onClick={[Function]} show={true} text="Remove from Channel" /> </Menu> </MenuWrapper> `; exports[`components/channel_members_dropdown should match snapshot when user is current user 1`] = ` <div> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </div> `; exports[`components/channel_members_dropdown should match snapshot with role change possible 1`] = ` <MenuWrapper animationComponent={[Function]} className="" > <button className="dropdown-toggle theme color--link style--none" type="button" > <span className="sr-only" /> <span> <MemoizedFormattedMessage defaultMessage="Channel Admin" id="channel_members_dropdown.channel_admin" /> </span> <DropdownIcon /> </button> <Menu ariaLabel="Change the role of channel member" openLeft={true} openUp={false} > <MenuItemAction id="undefined-make-channel-member" onClick={[Function]} show={true} text="Make Channel Member" /> </Menu> </MenuWrapper> `;
1,755
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_modal/channel_members_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {Modal} from 'react-bootstrap'; import type {ChannelType} from '@mattermost/types/channels'; import ChannelInviteModal from 'components/channel_invite_modal'; import {ModalIdentifiers} from 'utils/constants'; import ChannelMembersModal from './channel_members_modal'; describe('components/ChannelMembersModal', () => { 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, }, canManageChannelMembers: true, onExited: jest.fn(), actions: { openModal: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <ChannelMembersModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match state when onHide is called', () => { const wrapper = shallow<ChannelMembersModal>( <ChannelMembersModal {...baseProps}/>, ); wrapper.setState({show: true}); wrapper.instance().handleHide(); expect(wrapper.state('show')).toEqual(false); }); test('should have called props.actions.openModal and hide modal when onAddNewMembersButton is called', () => { const wrapper = shallow<ChannelMembersModal>( <ChannelMembersModal {...baseProps}/>, ); wrapper.instance().onAddNewMembersButton(); expect(baseProps.actions.openModal).toHaveBeenCalledTimes(1); expect(wrapper.state('show')).toBe(false); }); test('should have state when Modal.onHide', () => { const wrapper = shallow( <ChannelMembersModal {...baseProps}/>, ); wrapper.setState({show: true}); wrapper.find(Modal).first().props().onHide(); expect(wrapper.state('show')).toEqual(false); }); test('should match snapshot with archived channel', () => { const props = {...baseProps, channel: {...baseProps.channel, delete_at: 1234}}; const wrapper = shallow( <ChannelMembersModal {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('renders the channel display name', () => { const wrapper = shallow( <ChannelMembersModal {...baseProps}/>, ); expect(wrapper.find('.name').text()).toBe(baseProps.channel.display_name); }); test('should show the invite modal link if the user can manage channel members', () => { const newProps = {...baseProps, canManageChannelMembers: true}; const wrapper = shallow( <ChannelMembersModal {...newProps}/>, ); expect(wrapper.find('#showInviteModal').length).toBe(1); }); test('should not show the invite modal link if the user can not manage channel members', () => { const newProps = {...baseProps, canManageChannelMembers: false}; const wrapper = shallow( <ChannelMembersModal {...newProps}/>, ); expect(wrapper.find('#showInviteModal').length).toBe(0); }); test('should call openModal with ChannelInviteModal when the add members link is clicked', () => { const openModal = jest.fn(); const newProps = { ...baseProps, canManageChannelMembers: false, actions: { openModal, }, }; const wrapper = shallow( <ChannelMembersModal {...newProps}/>, ); expect(openModal).not.toHaveBeenCalled(); (wrapper.instance() as ChannelMembersModal).onAddNewMembersButton(); expect(openModal).toHaveBeenCalledWith({ modalId: ModalIdentifiers.CHANNEL_INVITE, dialogType: ChannelInviteModal, dialogProps: {channel: newProps.channel}, }); }); });
1,758
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_modal/__snapshots__/channel_members_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelMembersModal should match snapshot 1`] = ` <div> <Modal animation={true} aria-labelledby="channelMembersModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-modal--action" dialogComponentClass={[Function]} enforceFocus={true} id="channelMembersModal" 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="channelMembersModalLabel" > <span className="name" > channel_display_name </span> <MemoizedFormattedMessage defaultMessage=" Members" id="channel_members_modal.members" /> </ModalTitle> <a className="btn btn-md btn-primary" href="#" id="showInviteModal" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage=" Add Members" id="channel_members_modal.addNew" /> </a> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <Connect(MemberListChannel) 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, } } /> </ModalBody> </Modal> </div> `; exports[`components/ChannelMembersModal should match snapshot with archived channel 1`] = ` <div> <Modal animation={true} aria-labelledby="channelMembersModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-modal--action" dialogComponentClass={[Function]} enforceFocus={true} id="channelMembersModal" 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="channelMembersModalLabel" > <span className="name" > channel_display_name </span> <MemoizedFormattedMessage defaultMessage=" Members" id="channel_members_modal.members" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <Connect(MemberListChannel) channel={ Object { "create_at": 0, "creator_id": "", "delete_at": 1234, "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, } } /> </ModalBody> </Modal> </div> `;
1,759
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_members_rhs/action_bar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {fireEvent, renderWithContext, screen} from 'tests/react_testing_utils'; import Constants from 'utils/constants'; import ActionBar from './action_bar'; import type {Props} from './action_bar'; describe('channel_members_rhs/action_bar', () => { const actionBarDefaultProps: Props = { channelType: Constants.OPEN_CHANNEL, membersCount: 12, canManageMembers: true, editing: false, actions: { startEditing: jest.fn(), stopEditing: jest.fn(), inviteMembers: jest.fn(), }, }; beforeEach(() => { actionBarDefaultProps.actions = { startEditing: jest.fn(), stopEditing: jest.fn(), inviteMembers: jest.fn(), }; }); test('should display the members count', () => { const testProps: Props = {...actionBarDefaultProps}; renderWithContext( <ActionBar {...testProps} />, ); expect(screen.getByText(`${testProps.membersCount} members`)).toBeInTheDocument(); }); test('should display Add button', () => { const testProps: Props = {...actionBarDefaultProps}; renderWithContext( <ActionBar {...testProps} />, ); expect(screen.getByText('Add')).toBeInTheDocument(); fireEvent.click(screen.getByText('Add')); expect(testProps.actions.inviteMembers).toHaveBeenCalled(); }); test('should not display Add button to members', () => { const testProps: Props = {...actionBarDefaultProps, canManageMembers: false}; renderWithContext( <ActionBar {...testProps} />, ); expect(screen.queryByText('Add')).not.toBeInTheDocument(); }); test('should display Manage', () => { const testProps: Props = {...actionBarDefaultProps}; renderWithContext( <ActionBar {...testProps} />, ); expect(screen.getByText('Manage')).toBeInTheDocument(); fireEvent.click(screen.getByText('Manage')); expect(testProps.actions.startEditing).toHaveBeenCalled(); }); test('should display Done', () => { const testProps: Props = { ...actionBarDefaultProps, editing: true, }; renderWithContext( <ActionBar {...testProps} />, ); expect(screen.getByText('Done')).toBeInTheDocument(); fireEvent.click(screen.getByText('Done')); expect(testProps.actions.stopEditing).toHaveBeenCalled(); }); test('should not display manage button to members', () => { const testProps: Props = {...actionBarDefaultProps, canManageMembers: false}; renderWithContext( <ActionBar {...testProps} />, ); expect(screen.queryByText('Manage')).not.toBeInTheDocument(); }); });
1,772
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_notifications_modal/channel_notifications_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {screen, fireEvent, waitFor} from '@testing-library/react'; import type {ComponentProps} from 'react'; import React from 'react'; import type {ChannelMembership} from '@mattermost/types/channels'; import type {UserNotifyProps} from '@mattermost/types/users'; import ChannelNotificationsModal from 'components/channel_notifications_modal/channel_notifications_modal'; import {renderWithContext} from 'tests/react_testing_utils'; import {IgnoreChannelMentions, NotificationLevels} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; describe('components/channel_notifications_modal/ChannelNotificationsModal', () => { const baseProps: ComponentProps<typeof ChannelNotificationsModal> = { onExited: jest.fn(), channel: TestHelper.getChannelMock({ id: 'channel_id', display_name: 'channel_display_name', }), channelMember: { notify_props: { desktop: NotificationLevels.ALL, mark_unread: NotificationLevels.ALL, push: NotificationLevels.DEFAULT, ignore_channel_mentions: IgnoreChannelMentions.DEFAULT, desktop_threads: NotificationLevels.ALL, push_threads: NotificationLevels.DEFAULT, }, } as unknown as ChannelMembership, currentUser: TestHelper.getUserMock({ id: 'current_user_id', notify_props: { desktop: NotificationLevels.ALL, desktop_threads: NotificationLevels.ALL, } as UserNotifyProps, }), sendPushNotifications: true, actions: { updateChannelNotifyProps: jest.fn().mockImplementation(() => Promise.resolve({data: true})), }, collapsedReplyThreads: false, }; it('should not show other settings if channel is mute', async () => { const wrapper = renderWithContext( <ChannelNotificationsModal {...baseProps}/>, ); const muteChannel = screen.getByTestId('muteChannel'); fireEvent.click(muteChannel); expect(muteChannel).toBeChecked(); const AlertBanner = screen.queryByText('This channel is muted'); expect(AlertBanner).toBeVisible(); expect(screen.queryByText('Desktop Notifications')).toBeNull(); expect(screen.queryByText('Mobile Notifications')).toBeNull(); expect(screen.queryByText('Follow all threads in this channel')).toBeNull(); fireEvent.click(screen.getByRole('button', {name: /Save/i})); await waitFor(() => expect(baseProps.actions.updateChannelNotifyProps).toHaveBeenCalledWith( 'current_user_id', 'channel_id', { desktop: baseProps.channelMember?.notify_props.desktop, ignore_channel_mentions: 'off', mark_unread: 'mention', push: 'all', }, ), ); expect(wrapper).toMatchSnapshot(); }); test('should Ignore mentions for @channel, @here and @all', async () => { const wrapper = renderWithContext( <ChannelNotificationsModal {...baseProps}/>, ); const ignoreChannel = screen.getByTestId('ignoreMentions'); fireEvent.click(ignoreChannel); expect(ignoreChannel).toBeChecked(); fireEvent.click(screen.getByRole('button', {name: /Save/i})); await waitFor(() => expect(baseProps.actions.updateChannelNotifyProps).toHaveBeenCalledWith( 'current_user_id', 'channel_id', { desktop: 'all', ignore_channel_mentions: 'on', mark_unread: baseProps.channelMember?.notify_props.mark_unread, push: 'all', }, ), ); expect(wrapper).toMatchSnapshot(); }); test('should check the options in the desktop notifications', async () => { const wrapper = renderWithContext( <ChannelNotificationsModal {...baseProps}/>, ); expect(screen.queryByText('Desktop Notifications')).toBeVisible(); const AlllabelRadio: HTMLInputElement = screen.getByTestId( 'desktopNotification-all', ); fireEvent.click(AlllabelRadio); expect(AlllabelRadio.checked).toEqual(true); const MentionslabelRadio: HTMLInputElement = screen.getByTestId( 'desktopNotification-mention', ); fireEvent.click(MentionslabelRadio); expect(MentionslabelRadio.checked).toEqual(true); const NothinglabelRadio: HTMLInputElement = screen.getByTestId( 'desktopNotification-none', ); fireEvent.click(NothinglabelRadio); expect(NothinglabelRadio.checked).toEqual(true); fireEvent.click(screen.getByRole('button', {name: /Save/i})); await waitFor(() => expect(baseProps.actions.updateChannelNotifyProps).toHaveBeenCalledWith( 'current_user_id', 'channel_id', { desktop: 'none', ignore_channel_mentions: 'off', mark_unread: 'all', push: 'all', }, ), ); expect(wrapper).toMatchSnapshot(); }); test('should save the options exactly same as Desktop for mobile if use same as desktop checkbox is checked', async () => { const wrapper = renderWithContext( <ChannelNotificationsModal {...baseProps}/>, ); expect(screen.queryByText('Desktop Notifications')).toBeVisible(); const sameAsDesktop: HTMLInputElement = screen.getByTestId( 'sameMobileSettingsDesktop', ); fireEvent.click(sameAsDesktop); expect(sameAsDesktop.checked).toEqual(true); expect(screen.queryByText('All new messages')).toBeNull(); fireEvent.click(screen.getByRole('button', {name: /Save/i})); await waitFor(() => expect(baseProps.actions.updateChannelNotifyProps).toHaveBeenCalledWith( 'current_user_id', 'channel_id', { desktop: 'all', ignore_channel_mentions: 'off', mark_unread: 'all', push: 'all', }, ), ); expect(wrapper).toMatchSnapshot(); }); test('should check the options in the mobile notifications', async () => { const wrapper = renderWithContext( <ChannelNotificationsModal {...baseProps}/>, ); const AlllabelRadio: HTMLInputElement = screen.getByTestId( 'MobileNotification-all', ); fireEvent.click(AlllabelRadio); expect(AlllabelRadio.checked).toEqual(true); const MentionslabelRadio: HTMLInputElement = screen.getByTestId( 'MobileNotification-mention', ); fireEvent.click(MentionslabelRadio); expect(MentionslabelRadio.checked).toEqual(true); const NothinglabelRadio: HTMLInputElement = screen.getByTestId( 'MobileNotification-none', ); fireEvent.click(NothinglabelRadio); expect(NothinglabelRadio.checked).toEqual(true); fireEvent.click(screen.getByRole('button', {name: /Save/i})); await waitFor(() => expect(baseProps.actions.updateChannelNotifyProps).toHaveBeenCalledWith( 'current_user_id', 'channel_id', { desktop: 'all', ignore_channel_mentions: 'off', mark_unread: 'all', push: 'none', }, ), ); expect(wrapper).toMatchSnapshot(); }); it('should show auto follow, desktop threads and mobile threads settings if collapsed reply threads is enabled', async () => { const props = { ...baseProps, collapsedReplyThreads: true, }; const wrapper = renderWithContext( <ChannelNotificationsModal {...props}/>, ); expect(screen.queryByText('Follow all threads in this channel')).toBeVisible(); fireEvent.click(screen.getByRole('button', {name: /Save/i})); await waitFor(() => expect(baseProps.actions.updateChannelNotifyProps).toHaveBeenCalledWith( 'current_user_id', 'channel_id', { desktop: baseProps.channelMember?.notify_props.desktop, ignore_channel_mentions: 'off', mark_unread: 'all', channel_auto_follow_threads: 'off', push: 'all', push_threads: 'default', desktop_threads: 'all', }, ), ); expect(wrapper).toMatchSnapshot(); }); });
1,776
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_notifications_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_notifications_modal/__snapshots__/channel_notifications_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/channel_notifications_modal/ChannelNotificationsModal should Ignore mentions for @channel, @here and @all 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop" /> <div aria-labelledby="channelNotificationModalLabel" class="fade modal" role="dialog" style="display: flex; place-items: center; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal channel-notifications-settings-modal modal-dialog" > <div class="modal-content" role="document" > <header class="mm-modal-header" > <h1 class="mm-modal-header__title" id="mm-modal-header-channelNotificationModalLabel" tabindex="0" > Notification Preferences </h1> <div class="mm-modal-header__vertical-divider" /> <p class="mm-modal-header__subtitle" > channel_display_name </p> <div class="mm-modal-header__ctr" > <button class="style--none mm-modal-header__close-btn" > <svg fill="currentcolor" height="24" version="1.1" viewBox="0 0 24 24" width="24" 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> </button> </div> </header> <main class="channel-notifications-settings-modal__body" > <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Mute or ignore </h4> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="muteChannel" name="mute channel" type="checkbox" /> Mute channel </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > Turns off notifications for this channel. You’ll still see badges if you’re mentioned. </p> </div> <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="ignoreMentions" name="ignore mentions" type="checkbox" /> Ignore mentions for @channel, @here and @all </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > When enabled, @channel, @here and @all will not trigger mentions or mention notifications in this channel </p> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Desktop Notifications </h4> </div> <p class="mm-modal-generic-section__description" > Available on Chrome, Edge, Firefox, and the Mattermost Desktop App. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="desktopNotification-all" id="desktopNotification-all" name="desktopNotification-all" type="radio" value="all" /> All new messages (default) </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-mention" id="desktopNotification-mention" name="desktopNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-none" id="desktopNotification-none" name="desktopNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Mobile Notifications </h4> <button class="channel-notifications-settings-modal__reset-btn" > <svg fill="currentColor" height="14" version="1.1" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg" > <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" /> </svg> Reset to default </button> </div> <p class="mm-modal-generic-section__description" > Notification alerts are pushed to your mobile device when there is activity in Mattermost. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="sameMobileSettingsDesktop" name="same mobile settings as Desktop" type="checkbox" /> Use the same notification settings as desktop </label> <br /> </fieldset> </div> </div> <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="MobileNotification-all" id="MobileNotification-all" name="MobileNotification-all" type="radio" value="all" /> All new messages </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-mention" id="MobileNotification-mention" name="MobileNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-none" id="MobileNotification-none" name="MobileNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> </main> <footer class="channel-notifications-settings-modal__footer" > <button class="channel-notifications-settings-modal__cancel-btn" > Cancel </button> <button class="channel-notifications-settings-modal__save-btn" > Save </button> </footer> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `; exports[`components/channel_notifications_modal/ChannelNotificationsModal should check the options in the desktop notifications 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop" /> <div aria-labelledby="channelNotificationModalLabel" class="fade modal" role="dialog" style="display: flex; place-items: center; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal channel-notifications-settings-modal modal-dialog" > <div class="modal-content" role="document" > <header class="mm-modal-header" > <h1 class="mm-modal-header__title" id="mm-modal-header-channelNotificationModalLabel" tabindex="0" > Notification Preferences </h1> <div class="mm-modal-header__vertical-divider" /> <p class="mm-modal-header__subtitle" > channel_display_name </p> <div class="mm-modal-header__ctr" > <button class="style--none mm-modal-header__close-btn" > <svg fill="currentcolor" height="24" version="1.1" viewBox="0 0 24 24" width="24" 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> </button> </div> </header> <main class="channel-notifications-settings-modal__body" > <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Mute or ignore </h4> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="muteChannel" name="mute channel" type="checkbox" /> Mute channel </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > Turns off notifications for this channel. You’ll still see badges if you’re mentioned. </p> </div> <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="ignoreMentions" name="ignore mentions" type="checkbox" /> Ignore mentions for @channel, @here and @all </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > When enabled, @channel, @here and @all will not trigger mentions or mention notifications in this channel </p> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Desktop Notifications </h4> <button class="channel-notifications-settings-modal__reset-btn" > <svg fill="currentColor" height="14" version="1.1" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg" > <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" /> </svg> Reset to default </button> </div> <p class="mm-modal-generic-section__description" > Available on Chrome, Edge, Firefox, and the Mattermost Desktop App. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="desktopNotification-all" id="desktopNotification-all" name="desktopNotification-all" type="radio" value="all" /> All new messages (default) </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-mention" id="desktopNotification-mention" name="desktopNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-none" id="desktopNotification-none" name="desktopNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Mobile Notifications </h4> <button class="channel-notifications-settings-modal__reset-btn" > <svg fill="currentColor" height="14" version="1.1" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg" > <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" /> </svg> Reset to default </button> </div> <p class="mm-modal-generic-section__description" > Notification alerts are pushed to your mobile device when there is activity in Mattermost. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="sameMobileSettingsDesktop" name="same mobile settings as Desktop" type="checkbox" /> Use the same notification settings as desktop </label> <br /> </fieldset> </div> </div> <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="MobileNotification-all" id="MobileNotification-all" name="MobileNotification-all" type="radio" value="all" /> All new messages </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-mention" id="MobileNotification-mention" name="MobileNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-none" id="MobileNotification-none" name="MobileNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> </main> <footer class="channel-notifications-settings-modal__footer" > <button class="channel-notifications-settings-modal__cancel-btn" > Cancel </button> <button class="channel-notifications-settings-modal__save-btn" > Save </button> </footer> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `; exports[`components/channel_notifications_modal/ChannelNotificationsModal should check the options in the mobile notifications 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop" /> <div aria-labelledby="channelNotificationModalLabel" class="fade modal" role="dialog" style="display: flex; place-items: center; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal channel-notifications-settings-modal modal-dialog" > <div class="modal-content" role="document" > <header class="mm-modal-header" > <h1 class="mm-modal-header__title" id="mm-modal-header-channelNotificationModalLabel" tabindex="0" > Notification Preferences </h1> <div class="mm-modal-header__vertical-divider" /> <p class="mm-modal-header__subtitle" > channel_display_name </p> <div class="mm-modal-header__ctr" > <button class="style--none mm-modal-header__close-btn" > <svg fill="currentcolor" height="24" version="1.1" viewBox="0 0 24 24" width="24" 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> </button> </div> </header> <main class="channel-notifications-settings-modal__body" > <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Mute or ignore </h4> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="muteChannel" name="mute channel" type="checkbox" /> Mute channel </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > Turns off notifications for this channel. You’ll still see badges if you’re mentioned. </p> </div> <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="ignoreMentions" name="ignore mentions" type="checkbox" /> Ignore mentions for @channel, @here and @all </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > When enabled, @channel, @here and @all will not trigger mentions or mention notifications in this channel </p> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Desktop Notifications </h4> </div> <p class="mm-modal-generic-section__description" > Available on Chrome, Edge, Firefox, and the Mattermost Desktop App. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="desktopNotification-all" id="desktopNotification-all" name="desktopNotification-all" type="radio" value="all" /> All new messages (default) </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-mention" id="desktopNotification-mention" name="desktopNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-none" id="desktopNotification-none" name="desktopNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Mobile Notifications </h4> <button class="channel-notifications-settings-modal__reset-btn" > <svg fill="currentColor" height="14" version="1.1" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg" > <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" /> </svg> Reset to default </button> </div> <p class="mm-modal-generic-section__description" > Notification alerts are pushed to your mobile device when there is activity in Mattermost. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="sameMobileSettingsDesktop" name="same mobile settings as Desktop" type="checkbox" /> Use the same notification settings as desktop </label> <br /> </fieldset> </div> </div> <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="MobileNotification-all" id="MobileNotification-all" name="MobileNotification-all" type="radio" value="all" /> All new messages </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-mention" id="MobileNotification-mention" name="MobileNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-none" id="MobileNotification-none" name="MobileNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> </main> <footer class="channel-notifications-settings-modal__footer" > <button class="channel-notifications-settings-modal__cancel-btn" > Cancel </button> <button class="channel-notifications-settings-modal__save-btn" > Save </button> </footer> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `; exports[`components/channel_notifications_modal/ChannelNotificationsModal should not show other settings if channel is mute 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop" /> <div aria-labelledby="channelNotificationModalLabel" class="fade modal" role="dialog" style="display: flex; place-items: center; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal channel-notifications-settings-modal modal-dialog" > <div class="modal-content" role="document" > <header class="mm-modal-header" > <h1 class="mm-modal-header__title" id="mm-modal-header-channelNotificationModalLabel" tabindex="0" > Notification Preferences </h1> <div class="mm-modal-header__vertical-divider" /> <p class="mm-modal-header__subtitle" > channel_display_name </p> <div class="mm-modal-header__ctr" > <button class="style--none mm-modal-header__close-btn" > <svg fill="currentcolor" height="24" version="1.1" viewBox="0 0 24 24" width="24" 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> </button> </div> </header> <main class="channel-notifications-settings-modal__body" > <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Mute or ignore </h4> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="muteChannel" name="mute channel" type="checkbox" /> Mute channel </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > Turns off notifications for this channel. You’ll still see badges if you’re mentioned. </p> </div> <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="ignoreMentions" name="ignore mentions" type="checkbox" /> Ignore mentions for @channel, @here and @all </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > When enabled, @channel, @here and @all will not trigger mentions or mention notifications in this channel </p> </div> </div> </section> <div class="AlertBanner info AlertBanner--app" > <div class="AlertBanner__icon" > <svg fill="currentColor" height="24" version="1.1" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" > <path d="M22.11,21.46L2.39,1.73L1.11,3L5.83,7.72C5.29,8.73 5,9.86 5,11V17L3,19V20H18.11L20.84,22.73L22.11,21.46M7,18V11C7,10.39 7.11,9.79 7.34,9.23L16.11,18H7M10,21H14A2,2 0 0,1 12,23A2,2 0 0,1 10,21M8.29,5.09C8.82,4.75 9.4,4.5 10,4.29C10,4.19 10,4.1 10,4A2,2 0 0,1 12,2A2,2 0 0,1 14,4C14,4.1 14,4.19 14,4.29C16.97,5.17 19,7.9 19,11V15.8L17,13.8V11A5,5 0 0,0 12,6C11.22,6 10.45,6.2 9.76,6.56L8.29,5.09Z" /> </svg> </div> <div class="AlertBanner__body" > <div class="AlertBanner__title" > This channel is muted </div> <div class="AlertBanner__message" > All other notification preferences for this channel are disabled </div> </div> </div> </main> <footer class="channel-notifications-settings-modal__footer" > <button class="channel-notifications-settings-modal__cancel-btn" > Cancel </button> <button class="channel-notifications-settings-modal__save-btn" > Save </button> </footer> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `; exports[`components/channel_notifications_modal/ChannelNotificationsModal should save the options exactly same as Desktop for mobile if use same as desktop checkbox is checked 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop" /> <div aria-labelledby="channelNotificationModalLabel" class="fade modal" role="dialog" style="display: flex; place-items: center; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal channel-notifications-settings-modal modal-dialog" > <div class="modal-content" role="document" > <header class="mm-modal-header" > <h1 class="mm-modal-header__title" id="mm-modal-header-channelNotificationModalLabel" tabindex="0" > Notification Preferences </h1> <div class="mm-modal-header__vertical-divider" /> <p class="mm-modal-header__subtitle" > channel_display_name </p> <div class="mm-modal-header__ctr" > <button class="style--none mm-modal-header__close-btn" > <svg fill="currentcolor" height="24" version="1.1" viewBox="0 0 24 24" width="24" 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> </button> </div> </header> <main class="channel-notifications-settings-modal__body" > <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Mute or ignore </h4> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="muteChannel" name="mute channel" type="checkbox" /> Mute channel </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > Turns off notifications for this channel. You’ll still see badges if you’re mentioned. </p> </div> <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="ignoreMentions" name="ignore mentions" type="checkbox" /> Ignore mentions for @channel, @here and @all </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > When enabled, @channel, @here and @all will not trigger mentions or mention notifications in this channel </p> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Desktop Notifications </h4> </div> <p class="mm-modal-generic-section__description" > Available on Chrome, Edge, Firefox, and the Mattermost Desktop App. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="desktopNotification-all" id="desktopNotification-all" name="desktopNotification-all" type="radio" value="all" /> All new messages (default) </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-mention" id="desktopNotification-mention" name="desktopNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-none" id="desktopNotification-none" name="desktopNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Mobile Notifications </h4> <button class="channel-notifications-settings-modal__reset-btn" > <svg fill="currentColor" height="14" version="1.1" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg" > <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" /> </svg> Reset to default </button> </div> <p class="mm-modal-generic-section__description" > Notification alerts are pushed to your mobile device when there is activity in Mattermost. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="sameMobileSettingsDesktop" name="same mobile settings as Desktop" type="checkbox" /> Use the same notification settings as desktop </label> <br /> </fieldset> </div> </div> </div> </section> </main> <footer class="channel-notifications-settings-modal__footer" > <button class="channel-notifications-settings-modal__cancel-btn" > Cancel </button> <button class="channel-notifications-settings-modal__save-btn" > Save </button> </footer> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `; exports[`components/channel_notifications_modal/ChannelNotificationsModal should show auto follow, desktop threads and mobile threads settings if collapsed reply threads is enabled 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop" /> <div aria-labelledby="channelNotificationModalLabel" class="fade modal" role="dialog" style="display: flex; place-items: center; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal channel-notifications-settings-modal modal-dialog" > <div class="modal-content" role="document" > <header class="mm-modal-header" > <h1 class="mm-modal-header__title" id="mm-modal-header-channelNotificationModalLabel" tabindex="0" > Notification Preferences </h1> <div class="mm-modal-header__vertical-divider" /> <p class="mm-modal-header__subtitle" > channel_display_name </p> <div class="mm-modal-header__ctr" > <button class="style--none mm-modal-header__close-btn" > <svg fill="currentcolor" height="24" version="1.1" viewBox="0 0 24 24" width="24" 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> </button> </div> </header> <main class="channel-notifications-settings-modal__body" > <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Mute or ignore </h4> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="muteChannel" name="mute channel" type="checkbox" /> Mute channel </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > Turns off notifications for this channel. You’ll still see badges if you’re mentioned. </p> </div> <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="ignoreMentions" name="ignore mentions" type="checkbox" /> Ignore mentions for @channel, @here and @all </label> <br /> </fieldset> </div> <p class="mm-modal-generic-section-item__description" > When enabled, @channel, @here and @all will not trigger mentions or mention notifications in this channel </p> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Desktop Notifications </h4> </div> <p class="mm-modal-generic-section__description" > Available on Chrome, Edge, Firefox, and the Mattermost Desktop App. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="desktopNotification-all" id="desktopNotification-all" name="desktopNotification-all" type="radio" value="all" /> All new messages (default) </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-mention" id="desktopNotification-mention" name="desktopNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="desktopNotification-none" id="desktopNotification-none" name="desktopNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <div class="mm-modal-generic-section__row" > <h4 class="mm-modal-generic-section__title" > Mobile Notifications </h4> <button class="channel-notifications-settings-modal__reset-btn" > <svg fill="currentColor" height="14" version="1.1" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg" > <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" /> </svg> Reset to default </button> </div> <p class="mm-modal-generic-section__description" > Notification alerts are pushed to your mobile device when there is activity in Mattermost. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="sameMobileSettingsDesktop" name="same mobile settings as Desktop" type="checkbox" /> Use the same notification settings as desktop </label> <br /> </fieldset> </div> </div> <div class="mm-modal-generic-section-item" > <h4 class="mm-modal-generic-section-item__title" > Notify me about… </h4> <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-radio" > <label class="mm-modal-generic-section-item__label-radio" > <input checked="" data-testid="MobileNotification-all" id="MobileNotification-all" name="MobileNotification-all" type="radio" value="all" /> All new messages </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-mention" id="MobileNotification-mention" name="MobileNotification-mention" type="radio" value="mention" /> Mentions, direct messages, and keywords only </label> <label class="mm-modal-generic-section-item__label-radio" > <input data-testid="MobileNotification-none" id="MobileNotification-none" name="MobileNotification-none" type="radio" value="none" /> Nothing </label> </fieldset> </div> </div> </div> </section> <div class="channel-notifications-settings-modal__divider" /> <section class="mm-modal-generic-section" > <div class="mm-modal-generic-section__info-ctr" > <h4 class="mm-modal-generic-section__title" > Follow all threads in this channel </h4> <p class="mm-modal-generic-section__description" > When enabled, all new replies in this channel will be automatically followed and will appear in your Threads view. </p> </div> <div class="mm-modal-generic-section__content" > <div class="mm-modal-generic-section-item" > <div class="mm-modal-generic-section-item__content" > <fieldset class="mm-modal-generic-section-item__fieldset-checkbox-ctr" > <label class="mm-modal-generic-section-item__fieldset-checkbox" > <input class="mm-modal-generic-section-item__input-checkbox" data-testid="autoFollowThreads" name="auto follow threads" type="checkbox" /> Automatically follow threads in this channel </label> <br /> </fieldset> </div> </div> </div> </section> </main> <footer class="channel-notifications-settings-modal__footer" > <button class="channel-notifications-settings-modal__cancel-btn" > Cancel </button> <button class="channel-notifications-settings-modal__save-btn" > Save </button> </footer> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "replaceStoreState": [Function], "rerender": [Function], "unmount": [Function], "updateStoreState": [Function], } `;
1,777
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_select/channel_select.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 ChannelSelect from 'components/channel_select/channel_select'; import Constants from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; describe('components/ChannelSelect', () => { const defaultProps = { channels: [ TestHelper.getChannelMock({ id: 'id1', display_name: 'Channel 1', name: 'channel1', type: Constants.OPEN_CHANNEL as ChannelType, }), TestHelper.getChannelMock({ id: 'id2', display_name: 'Channel 2', name: 'channel2', type: Constants.PRIVATE_CHANNEL as ChannelType, }), TestHelper.getChannelMock({ id: 'id3', display_name: 'Channel 3', name: 'channel3', type: Constants.DM_CHANNEL as ChannelType, }), ], onChange: jest.fn(), value: 'testValue', selectOpen: false, selectPrivate: false, selectDm: false, }; test('should match snapshot', () => { const wrapper = shallow(<ChannelSelect {...defaultProps}/>); expect(wrapper).toMatchSnapshot(); }); });
1,780
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_select
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_select/__snapshots__/channel_select.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelSelect should match snapshot 1`] = ` <select className="form-control" id="channelSelect" onChange={[MockFunction]} value="testValue" > <option key="" value="" > --- Select a channel --- </option> </select> `;
1,781
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_selector_modal/channel_selector_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ChannelWithTeamData} from '@mattermost/types/channels'; import ChannelSelectorModal from 'components/channel_selector_modal/channel_selector_modal'; import {TestHelper} from 'utils/test_helper'; describe('components/ChannelSelectorModal', () => { const channel1: ChannelWithTeamData = Object.assign(TestHelper.getChannelWithTeamDataMock({id: 'channel-1', team_id: 'teamid1'})); const channel2: ChannelWithTeamData = Object.assign(TestHelper.getChannelWithTeamDataMock({id: 'channel-2', team_id: 'teamid2'})); const channel3: ChannelWithTeamData = Object.assign(TestHelper.getChannelWithTeamDataMock({id: 'channel-3', team_id: 'teamid1'})); const defaultProps = { excludeNames: [], currentSchemeId: 'xxx', alreadySelected: ['channel-1'], searchTerm: '', onModalDismissed: jest.fn(), onChannelsSelected: jest.fn(), groupID: '', actions: { loadChannels: jest.fn().mockResolvedValue({data: [ channel1, channel2, channel3, ]}), setModalSearchTerm: jest.fn(), searchChannels: jest.fn(() => Promise.resolve({data: []})), searchAllChannels: jest.fn(() => Promise.resolve({data: []})), }, }; test('should match snapshot', () => { const wrapper = shallow(<ChannelSelectorModal {...defaultProps}/>); wrapper.setState({channels: [ channel1, channel2, channel3, ]}); expect(wrapper).toMatchSnapshot(); }); test('exclude already selected', () => { const wrapper = shallow( <ChannelSelectorModal {...defaultProps} excludeTeamIds={['teamid2']} />, ); wrapper.setState({channels: [ channel1, channel2, channel3, ]}); expect(wrapper).toMatchSnapshot(); }); });
1,784
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_selector_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_selector_modal/__snapshots__/channel_selector_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelSelectorModal exclude already selected 1`] = ` <Modal animation={true} aria-labelledby="channelSelectorModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels channel-selector-modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="channelSelectorModalLabel" > <FormattedMarkdownMessage defaultMessage="Add Channels to **Channel Selection** List" id="add_channels_to_scheme.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <MultiSelect ariaLabelRenderer={[Function]} buttonSubmitText="Add" focusOnLoad={true} handleAdd={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addChannelsToSchemeKey" loading={true} numRemainingText={ <Memo(MemoizedFormattedMessage) defaultMessage="Use ↑↓ to browse, ↵ to select." id="multiselect.selectChannels" /> } optionRenderer={[Function]} options={ Array [ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel-3", "label": "name", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_display_name": "teamDisplayName", "team_id": "teamid1", "team_name": "teamName", "team_update_at": 0, "type": "O", "update_at": 0, "value": "channel-3", }, ] } perPage={50} placeholderText="Search and add channels" saveButtonPosition="top" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueRenderer={[Function]} valueWithImage={false} values={Array []} /> </ModalBody> </Modal> `; exports[`components/ChannelSelectorModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="channelSelectorModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels channel-selector-modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="channelSelectorModalLabel" > <FormattedMarkdownMessage defaultMessage="Add Channels to **Channel Selection** List" id="add_channels_to_scheme.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <MultiSelect ariaLabelRenderer={[Function]} buttonSubmitText="Add" focusOnLoad={true} handleAdd={[Function]} handleDelete={[Function]} handleInput={[Function]} handlePageChange={[Function]} handleSubmit={[Function]} key="addChannelsToSchemeKey" loading={true} numRemainingText={ <Memo(MemoizedFormattedMessage) defaultMessage="Use ↑↓ to browse, ↵ to select." id="multiselect.selectChannels" /> } optionRenderer={[Function]} options={ Array [ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel-2", "label": "name", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_display_name": "teamDisplayName", "team_id": "teamid2", "team_name": "teamName", "team_update_at": 0, "type": "O", "update_at": 0, "value": "channel-2", }, Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel-3", "label": "name", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "team_display_name": "teamDisplayName", "team_id": "teamid1", "team_name": "teamName", "team_update_at": 0, "type": "O", "update_at": 0, "value": "channel-3", }, ] } perPage={50} placeholderText="Search and add channels" saveButtonPosition="top" saving={false} savingEnabled={true} selectedItemRef={ Object { "current": null, } } valueRenderer={[Function]} valueWithImage={false} values={Array []} /> </ModalBody> </Modal> `;
1,785
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_view/channel_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 ChannelView from './channel_view'; import type {Props} from './channel_view'; describe('components/channel_view', () => { const baseProps: Props = { channelId: 'channelId', deactivatedChannel: false, history: {} as Props['history'], location: {} as Props['location'], match: { url: '/team/channel/channelId', params: {}, } as Props['match'], enableOnboardingFlow: true, teamUrl: '/team', channelIsArchived: false, viewArchivedChannels: false, isCloud: false, goToLastViewedChannel: jest.fn(), isFirstAdmin: false, }; it('Should match snapshot with base props', () => { const wrapper = shallow(<ChannelView {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('Should match snapshot if channel is archived', () => { const wrapper = shallow( <ChannelView {...baseProps} channelIsArchived={true} />, ); expect(wrapper).toMatchSnapshot(); }); it('Should match snapshot if channel is deactivated', () => { const wrapper = shallow( <ChannelView {...baseProps} deactivatedChannel={true} />, ); expect(wrapper).toMatchSnapshot(); }); it('Should have focusedPostId state based on props', () => { const wrapper = shallow(<ChannelView {...baseProps}/>); expect(wrapper.state('focusedPostId')).toEqual(undefined); wrapper.setProps({channelId: 'newChannelId', match: {url: '/team/channel/channelId/postId', params: {postid: 'postid'}}}); expect(wrapper.state('focusedPostId')).toEqual('postid'); wrapper.setProps({channelId: 'newChannelId', match: {url: '/team/channel/channelId/postId1', params: {postid: 'postid1'}}}); expect(wrapper.state('focusedPostId')).toEqual('postid1'); }); });
1,788
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_view
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_view/__snapshots__/channel_view.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/channel_view Should match snapshot if channel is archived 1`] = ` <div className="app__content" id="app-content" > <FileUploadOverlay overlayType="center" /> <withRouter(Connect(injectIntl(ChannelHeader))) channelId="channelId" channelIsArchived={true} deactivatedChannel={false} enableOnboardingFlow={true} goToLastViewedChannel={[MockFunction]} history={Object {}} isCloud={false} isFirstAdmin={false} location={Object {}} match={ Object { "params": Object {}, "url": "/team/channel/channelId", } } teamUrl="/team" viewArchivedChannels={false} /> <DeferredRenderWrapper channelId="channelId" /> <div className="post-create__container" id="post-create" > <div className="channel-archived__message" id="channelArchivedMessage" > <FormattedMarkdownMessage defaultMessage="You are viewing an **archived channel**. New messages cannot be posted." id="archivedChannelMessage" /> <button className="btn btn-primary channel-archived__close-btn" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Close Channel" id="center_panel.archived.closeChannel" /> </button> </div> </div> </div> `; exports[`components/channel_view Should match snapshot if channel is deactivated 1`] = ` <div className="app__content" id="app-content" > <FileUploadOverlay overlayType="center" /> <withRouter(Connect(injectIntl(ChannelHeader))) channelId="channelId" channelIsArchived={false} deactivatedChannel={true} enableOnboardingFlow={true} goToLastViewedChannel={[MockFunction]} history={Object {}} isCloud={false} isFirstAdmin={false} location={Object {}} match={ Object { "params": Object {}, "url": "/team/channel/channelId", } } teamUrl="/team" viewArchivedChannels={false} /> <DeferredRenderWrapper channelId="channelId" /> <div className="post-create__container" id="post-create" > <div className="channel-archived__message" > <FormattedMarkdownMessage defaultMessage="You are viewing an archived channel with a **deactivated user**. New messages cannot be posted." id="create_post.deactivated" /> <button className="btn btn-primary channel-archived__close-btn" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Close Channel" id="center_panel.archived.closeChannel" /> </button> </div> </div> </div> `; exports[`components/channel_view Should match snapshot with base props 1`] = ` <div className="app__content" id="app-content" > <FileUploadOverlay overlayType="center" /> <withRouter(Connect(injectIntl(ChannelHeader))) channelId="channelId" channelIsArchived={false} deactivatedChannel={false} enableOnboardingFlow={true} goToLastViewedChannel={[MockFunction]} history={Object {}} isCloud={false} isFirstAdmin={false} location={Object {}} match={ Object { "params": Object {}, "url": "/team/channel/channelId", } } teamUrl="/team" viewArchivedChannels={false} /> <DeferredRenderWrapper channelId="channelId" /> <div className="post-create__container AdvancedTextEditor__ctr" data-testid="post-create" id="post-create" > <Connect(AdvancedCreatePost) getChannelView={[Function]} /> </div> </div> `;
1,796
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/claim
petrpan-code/mattermost/mattermost/webapp/channels/src/components/claim/components/ldap_to_email.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 LDAPToEmail from './ldap_to_email'; describe('components/claim/components/ldap_to_email.jsx', () => { const requiredProps = { email: '', passwordConfig: { minimumLength: 5, requireLowercase: true, requireUppercase: true, requireNumber: true, requireSymbol: true, }, switchLdapToEmail: jest.fn(() => Promise.resolve({data: {follow_link: '/login'}})), }; test('submit() should have called switchLdapToEmail', async () => { const loginId = ''; const password = 'psw'; const token = 'abcd1234'; const ldapPasswordParam = 'ldapPsw'; const wrapper = shallow(<LDAPToEmail {...requiredProps}/>); wrapper.find('LoginMfa').simulate('submit', {loginId, password, token, ldapPasswordParam}); expect(requiredProps.switchLdapToEmail).toHaveBeenCalledTimes(1); expect(requiredProps.switchLdapToEmail). toHaveBeenCalledWith(ldapPasswordParam, requiredProps.email, password, token); }); });
1,800
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_effects/index.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 type {GlobalState} from '@mattermost/types/store'; import type {DeepPartial} from '@mattermost/types/utilities'; import * as useShowAdminLimitReachedHook from 'components/common/hooks/useShowAdminLimitReached'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {TestHelper} from 'utils/test_helper'; import CloudEffectsWrapper from './'; function nonCloudLicense(state: DeepPartial<GlobalState>): GlobalState { const newState = JSON.parse(JSON.stringify(state)); if (!newState.entities) { newState.entities = {}; } if (!newState.entities.general) { newState.entities.general = {}; } if (!newState.entities.general.license) { newState.entities.general.license = TestHelper.getLicenseMock(); } newState.entities.general.license.Cloud = 'false'; return newState; } function cloudLicense(state: DeepPartial<GlobalState>): DeepPartial<GlobalState> { const newState = nonCloudLicense(state); newState.entities.general.license.Cloud = 'true'; return newState; } function stubUsers(state: DeepPartial<GlobalState>): GlobalState { const newState = JSON.parse(JSON.stringify(state)); if (!newState.entities) { newState.entities = {}; } if (!newState.entities.users) { newState.entities.users = {}; } newState.entities.users.currentUserId = ''; if (!newState.entities.users.profiles) { newState.entities.users.profiles = {}; } return newState; } function adminUser(state: DeepPartial<GlobalState>): GlobalState { const newState = stubUsers(state); const userId = 'admin'; newState.entities.users.currentUserId = userId; newState.entities.users.profiles[userId] = TestHelper.getUserMock({ id: userId, roles: 'system_admin', }); return newState; } function nonAdminUser(state: DeepPartial<GlobalState>) { const newState = adminUser(state); const userId = 'user'; newState.entities.users.currentUserId = userId; newState.entities.users.profiles[userId] = TestHelper.getUserMock({id: userId}); return newState; } describe('CloudEffectsWrapper', () => { it('short circuits if not cloud', () => { const initialState = adminUser(nonCloudLicense({})); const store = mockStore(initialState); mountWithIntl( <Provider store={store}> <CloudEffectsWrapper/> </Provider>, ); const spy = jest.spyOn(useShowAdminLimitReachedHook, 'default'); expect(spy).not.toHaveBeenCalled(); }); it('short circuits if user not logged in', () => { const initialState = stubUsers(cloudLicense({})); const store = mockStore(initialState); mountWithIntl( <Provider store={store}> <CloudEffectsWrapper/> </Provider>, ); const spy = jest.spyOn(useShowAdminLimitReachedHook, 'default'); expect(spy).not.toHaveBeenCalled(); }); it('short circuits if user is not admin', () => { const initialState = nonAdminUser(cloudLicense({})); const store = mockStore(initialState); mountWithIntl( <Provider store={store}> <CloudEffectsWrapper/> </Provider>, ); const spy = jest.spyOn(useShowAdminLimitReachedHook, 'default'); expect(spy).not.toHaveBeenCalled(); }); it('calls effects if user is admin of a cloud instance', () => { const initialState = adminUser(cloudLicense({})); const store = mockStore(initialState); const spy = jest.spyOn(useShowAdminLimitReachedHook, 'default').mockImplementation(jest.fn()); mountWithIntl( <Provider store={store}> <CloudEffectsWrapper/> </Provider>, ); expect(spy).toHaveBeenCalledTimes(1); }); });
1,807
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial/cloud_start_trial_btn.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ReactWrapper} from 'enzyme'; import {shallow} from 'enzyme'; import React from 'react'; import {act} from 'react-dom/test-utils'; import {Provider} from 'react-redux'; import * as cloudActions from 'actions/cloud'; import {trackEvent} from 'actions/telemetry_actions.jsx'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {TELEMETRY_CATEGORIES} from 'utils/constants'; import CloudStartTrialButton from './cloud_start_trial_btn'; jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); jest.mock('mattermost-redux/actions/general', () => ({ ...jest.requireActual('mattermost-redux/actions/general'), getLicenseConfig: () => ({type: 'adsf'}), getClientConfig: () => ({type: 'adsf'}), })); jest.mock('mattermost-redux/actions/cloud', () => ({ ...jest.requireActual('mattermost-redux/actions/cloud'), getCloudSubscription: () => ({type: 'adsf'}), getCloudProducts: () => ({type: 'adsf'}), getCloudLimits: () => ({}), })); describe('components/cloud_start_trial_btn/cloud_start_trial_btn', () => { const state = { entities: { admin: {}, general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, cloud: { subscription: { is_free_trial: 'false', trial_end_at: 0, }, }, }, views: { modals: { modalState: { learn_more_trial_modal: { open: 'true', }, }, }, }, }; const store = mockStore(state); const props = { onClick: jest.fn(), message: 'Cloud Start trial', telemetryId: 'test_telemetry_id', }; test('should match snapshot', () => { const wrapper = shallow( <Provider store={store}> <CloudStartTrialButton {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should handle on click and change button text on SUCCESSFUL trial request', async () => { const mockOnClick = jest.fn(); const requestTrialFn: () => () => Promise<any> = () => () => Promise.resolve(true); jest.spyOn(cloudActions, 'requestCloudTrial').mockImplementation(requestTrialFn); let wrapper: ReactWrapper<any>; // Mount the component await act(async () => { wrapper = mountWithIntl( <Provider store={store}> <CloudStartTrialButton {...props} onClick={mockOnClick} email='fakeemail@topreventbusinessemailvalidation' /> </Provider>, ); }); await act(async () => { expect(wrapper.find('.CloudStartTrialButton').text().includes('Cloud Start trial')).toBe(true); wrapper.find('.CloudStartTrialButton').simulate('click'); }); await act(async () => { expect(wrapper.find('.CloudStartTrialButton').text().includes('Loaded!')).toBe(true); }); expect(mockOnClick).toHaveBeenCalled(); expect(trackEvent).toHaveBeenCalledWith(TELEMETRY_CATEGORIES.CLOUD_START_TRIAL_BUTTON, 'test_telemetry_id'); }); test('should handle on click and change button text on FAILED trial request', async () => { const mockOnClick = jest.fn(); const requestTrialFn: () => () => Promise<any> = () => () => Promise.resolve(true); jest.spyOn(cloudActions, 'requestCloudTrial').mockImplementation(requestTrialFn); let wrapper: ReactWrapper<any>; // Mount the component await act(async () => { wrapper = mountWithIntl( <Provider store={store}> <CloudStartTrialButton {...props} onClick={mockOnClick} /> </Provider>, ); }); await act(async () => { expect(wrapper.find('.CloudStartTrialButton').text().includes('Cloud Start trial')).toBe(true); }); await act(async () => { wrapper.find('.CloudStartTrialButton').simulate('click'); }); await act(async () => { expect(wrapper.find('.CloudStartTrialButton').text().includes('Failed')).toBe(true); }); }); });
1,809
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial/input_business_email.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount, shallow} from 'enzyme'; import React from 'react'; import {ItemStatus} from 'utils/constants'; import InputBusinessEmail from './input_business_email'; describe('/components/cloud_start_trial/input_business_email', () => { const handleEmailValuesMockFn = jest.fn(); const baseProps = { handleEmailValues: handleEmailValuesMockFn, email: '[email protected]', customInputLabel: null, }; test('should match snapshot', () => { const wrapper = shallow(<InputBusinessEmail {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('test input business email displays the input element correctly', () => { const wrapper = mount( <InputBusinessEmail {...baseProps}/>, ); const inputElement = wrapper.find('.Input'); expect(inputElement.length).toBe(1); }); test('test input business email displays the SUCCESS custom message correctly', () => { const wrapper = mount( <InputBusinessEmail {...{...baseProps, customInputLabel: {type: ItemStatus.SUCCESS, value: 'success value'}}}/>, ); const customMessageElement = wrapper.find('.Input___customMessage.Input___success'); expect(customMessageElement.length).toBe(1); }); test('test input business email displays the WARNING custom message correctly', () => { const wrapper = mount( <InputBusinessEmail {...{...baseProps, customInputLabel: {type: ItemStatus.WARNING, value: 'warning value'}}}/>, ); const customMessageElement = wrapper.find('.Input___customMessage.Input___warning'); expect(customMessageElement.length).toBe(1); }); test('test input business email displays the ERROR custom message correctly', () => { const wrapper = mount( <InputBusinessEmail {...{...baseProps, customInputLabel: {type: ItemStatus.ERROR, value: 'error value'}}}/>, ); const customMessageElement = wrapper.find('.Input___customMessage.Input___error'); expect(customMessageElement.length).toBe(1); }); test('test input business email displays the INFO custom message correctly', () => { const wrapper = mount( <InputBusinessEmail {...{...baseProps, customInputLabel: {type: ItemStatus.INFO, value: 'info value'}}}/>, ); const customMessageElement = wrapper.find('.Input___customMessage.Input___info'); expect(customMessageElement.length).toBe(1); }); test('test the input element handles the onChange event correctly', () => { const event = { target: {value: '[email protected]'}, }; const wrapper = mount( <InputBusinessEmail {...baseProps}/>, ); const inputElement = wrapper.find('.Input'); inputElement.find('input').simulate('change', event); expect(handleEmailValuesMockFn).toBeCalled(); }); });
1,812
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial/request_business_email_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 {act} from 'react-dom/test-utils'; import {Provider} from 'react-redux'; import {GenericModal} from '@mattermost/components'; import * as cloudActions from 'actions/cloud'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import RequestBusinessEmailModal from './request_business_email_modal'; jest.useFakeTimers(); jest.mock('lodash/debounce', () => jest.fn((fn) => fn)); describe('components/request_business_email_modal/request_business_email_modal', () => { const state = { entities: { users: { currentUserId: 'current_user_id', }, admin: {}, general: { license: { IsLicensed: 'true', Cloud: 'true', }, config: {}, }, cloud: { subscription: {id: 'subscriptionID'}, }, }, views: { modals: { modalState: { request_business_email_modal: { open: 'true', }, }, }, }, }; const props = { onExited: jest.fn(), }; const store = mockStore(state); test('should match snapshot', () => { const wrapper = shallow( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); test('should show the Start Cloud Trial Button', async () => { const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { const startTrialBtn = wrapper.find('CloudStartTrialButton'); expect(startTrialBtn).toHaveLength(1); }); }); test('should call on close', async () => { const mockOnClose = jest.fn(); const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props} onClose={mockOnClose} /> </Provider>, ); await act(async () => { wrapper.find(GenericModal).props().onExited(); expect(mockOnClose).toHaveBeenCalled(); }); }); test('should call on exited', async () => { const mockOnExited = jest.fn(); const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props} onExited={mockOnExited} /> </Provider>, ); await act(async () => { wrapper.find(GenericModal).props().onExited(); expect(mockOnExited).toHaveBeenCalled(); }); }); test('should show the Input to enter the valid Business Email', async () => { const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { expect(wrapper.find('InputBusinessEmail')).toHaveLength(1); }); }); test('should start with Start Cloud Trial Button disabled', async () => { const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { const startTrialBtn = wrapper.find('CloudStartTrialButton'); expect(startTrialBtn.props().disabled).toEqual(true); }); }); test('should ENABLE the trial button if email is VALID', async () => { // mock validation response to TRUE meaning the email is a valid email const validateBusinessEmail = () => () => Promise.resolve(true); jest.spyOn(cloudActions, 'validateBusinessEmail').mockImplementation(validateBusinessEmail); const event = { target: {value: '[email protected]'}, }; const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { const inputBusinessEmail = wrapper.find('InputBusinessEmail'); const input = inputBusinessEmail.find('input'); input.find('input').at(0).simulate('change', event); }); act(() => { wrapper.update(); const startTrialBtn = wrapper.find('CloudStartTrialButton'); expect(startTrialBtn.props().disabled).toEqual(false); }); }); test('should show the success custom message if the email is valid', async () => { // mock validation response to TRUE meaning the email is a valid email const validateBusinessEmail = () => () => Promise.resolve(true); jest.spyOn(cloudActions, 'validateBusinessEmail').mockImplementation(validateBusinessEmail); const event = { target: {value: '[email protected]'}, }; const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { const inputBusinessEmail = wrapper.find('InputBusinessEmail'); const input = inputBusinessEmail.find('input'); input.find('input').at(0).simulate('change', event); }); act(() => { wrapper.update(); const customMessageElement = wrapper.find('.Input___customMessage.Input___success'); expect(customMessageElement.length).toBe(1); }); }); test('should DISABLE the trial button if email is INVALID', async () => { // mock validation response to FALSE meaning the email is an invalid email const validateBusinessEmail = () => () => Promise.resolve(false); jest.spyOn(cloudActions, 'validateBusinessEmail').mockImplementation(validateBusinessEmail); const event = { target: {value: '[email protected]'}, }; const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { const inputBusinessEmail = wrapper.find('InputBusinessEmail'); const input = inputBusinessEmail.find('input'); input.find('input').at(0).simulate('change', event); }); act(() => { wrapper.update(); const startTrialBtn = wrapper.find('CloudStartTrialButton'); expect(startTrialBtn.props().disabled).toEqual(true); }); }); test('should show the error custom message if the email is invalid', async () => { // mock validation response to FALSE meaning the email is an invalid email const validateBusinessEmail = () => () => Promise.resolve(false); jest.spyOn(cloudActions, 'validateBusinessEmail').mockImplementation(validateBusinessEmail); const event = { target: {value: '[email protected]'}, }; const wrapper = mountWithIntl( <Provider store={store}> <RequestBusinessEmailModal {...props}/> </Provider>, ); await act(async () => { const inputBusinessEmail = wrapper.find('InputBusinessEmail'); const input = inputBusinessEmail.find('input'); input.find('input').at(0).simulate('change', event); }); act(() => { wrapper.update(); const customMessageElement = wrapper.find('.Input___customMessage.Input___error'); expect(customMessageElement.length).toBe(1); }); }); });
1,814
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial/__snapshots__/cloud_start_trial_btn.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/cloud_start_trial_btn/cloud_start_trial_btn should match snapshot 1`] = ` <ContextProvider value={ Object { "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "subscription": Subscription { "handleChangeWrapper": [Function], "listeners": Object { "notify": [Function], }, "onStateChange": [Function], "parentSub": undefined, "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "unsubscribe": null, }, } } > <CloudStartTrialButton message="Cloud Start trial" onClick={[MockFunction]} telemetryId="test_telemetry_id" /> </ContextProvider> `;
1,815
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial/__snapshots__/input_business_email.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/cloud_start_trial/input_business_email should match snapshot 1`] = ` <ForwardRef autoComplete="off" autoFocus={true} containerClassName="request-business-email-container" customMessage={null} inputClassName="request-business-email-input" label="Enter business email" name="request-business-email" onChange={[MockFunction]} placeholder="[email protected]" required={true} type="email" value="[email protected]" /> `;
1,816
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_start_trial/__snapshots__/request_business_email_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/request_business_email_modal/request_business_email_modal should match snapshot 1`] = ` <ContextProvider value={ Object { "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "subscription": Subscription { "handleChangeWrapper": [Function], "listeners": Object { "notify": [Function], }, "onStateChange": [Function], "parentSub": undefined, "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "unsubscribe": null, }, } } > <RequestBusinessEmailModal onExited={[MockFunction]} /> </ContextProvider> `;
1,817
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_subscribe_result_modal/error.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as redux from 'react-redux'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import SuccessModal from './error'; jest.mock('components/common/hooks/useOpenSalesLink', () => ({ __esModule: true, default: () => () => true, })); describe('components/pricing_modal/downgrade_team_removal_modal', () => { beforeEach(() => { jest.spyOn(redux, 'useDispatch').mockImplementation( jest.fn(() => jest.fn()), ); }); const state = { entities: { cloud: { subscription: { is_free_trial: 'false', trial_end_at: 0, product_id: 'prod_starter', }, }, }, views: { modals: { modalState: { success_modal: { open: 'true', }, }, }, }, }; test('matches snapshot', () => { const store = mockStore(state); const wrapper = mountWithIntl( <redux.Provider store={store}> <SuccessModal/> </redux.Provider>, ); expect(wrapper).toMatchSnapshot(); }); });
1,820
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_subscribe_result_modal/success.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as redux from 'react-redux'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import SuccessModal from './success'; describe('components/pricing_modal/downgrade_team_removal_modal', () => { beforeEach(() => { jest.spyOn(redux, 'useDispatch').mockImplementation( jest.fn(() => jest.fn()), ); }); const state = { entities: { cloud: { subscription: { is_free_trial: 'false', trial_end_at: 0, product_id: 'prod_starter', }, }, }, views: { modals: { modalState: { success_modal: { open: 'true', }, }, }, }, }; test('matches snapshot', () => { const store = mockStore(state); const wrapper = mountWithIntl( <redux.Provider store={store}> <SuccessModal/> </redux.Provider>, ); expect(wrapper).toMatchSnapshot(); }); });
1,822
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_subscribe_result_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_subscribe_result_modal/__snapshots__/error.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/pricing_modal/downgrade_team_removal_modal matches snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <ErrorModal> <injectIntl(FullScreenModal) onClose={[Function]} overrideTargetEvent={true} show={false} > <injectIntl(FullScreenModal) forwardedRef={null} onClose={[Function]} overrideTargetEvent={true} show={false} > <FullScreenModal forwardedRef={null} 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, } } onClose={[Function]} overrideTargetEvent={true} show={false} > <CSSTransition appear={true} classNames="FullScreenModal" in={false} mountOnEnter={true} timeout={100} unmountOnExit={true} > <Transition appear={true} enter={true} exit={true} in={false} mountOnEnter={true} onEnter={[Function]} onEntered={[Function]} onEntering={[Function]} onExit={[Function]} onExited={[Function]} onExiting={[Function]} timeout={100} unmountOnExit={true} /> </CSSTransition> </FullScreenModal> </injectIntl(FullScreenModal)> </injectIntl(FullScreenModal)> </ErrorModal> </Provider> `;
1,823
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_subscribe_result_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_subscribe_result_modal/__snapshots__/success.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/pricing_modal/downgrade_team_removal_modal matches snapshot 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <SuccessModal> <injectIntl(FullScreenModal) onClose={[Function]} overrideTargetEvent={true} show={true} > <injectIntl(FullScreenModal) forwardedRef={null} onClose={[Function]} overrideTargetEvent={true} show={true} > <FullScreenModal forwardedRef={null} 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, } } onClose={[Function]} overrideTargetEvent={true} show={true} > <CSSTransition appear={true} classNames="FullScreenModal" in={true} mountOnEnter={true} timeout={100} unmountOnExit={true} > <Transition appear={true} enter={true} exit={true} in={true} mountOnEnter={true} onEnter={[Function]} onEntered={[Function]} onEntering={[Function]} onExit={[Function]} onExited={[Function]} onExiting={[Function]} timeout={100} unmountOnExit={true} > <div aria-modal={true} className="FullScreenModal" role="dialog" tabIndex={-1} > <button aria-label="Close" className="close-x" onClick={[Function]} > <CloseIcon id="closeIcon" > <span id="closeIcon" > <svg aria-label="Close Icon" height="24px" role="img" viewBox="0 0 24 24" width="24px" > <path d="M18 7.209L16.791 6 12 10.791 7.209 6 6 7.209 10.791 12 6 16.791 7.209 18 12 13.209 16.791 18 18 16.791 13.209 12z" fillRule="nonzero" /> </svg> </span> </CloseIcon> </button> <div className="cloud_subscribe_result_modal" > <IconMessage buttonHandler={[Function]} className="success" date="" error={false} formattedButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Return to workspace" id="success_modal.return_to_workspace" /> } formattedSubtitle={ <Memo(MemoizedFormattedMessage) defaultMessage="Your final bill will be prorated. Your workspace now has {plan} limits." id="success_modal.subtitle" values={ Object { "plan": undefined, } } /> } formattedTitle={ <Memo(MemoizedFormattedMessage) defaultMessage="You are now subscribed to {selectedProductName}" id="admin.billing.subscription.proratedPayment.title" values={ Object { "selectedProductName": undefined, } } /> } icon={ <PaymentSuccessStandardSvg height={313} width={444} /> } subtitle="" > <div className="IconMessage" id="payment_complete_header" > <div className="content success" > <div className="IconMessage__svg-wrapper" > <PaymentSuccessStandardSvg height={313} width={444} > <svg fill="none" height="313" viewBox="0 0 312 257" width="444" xmlns="http://www.w3.org/2000/svg" > <g clipPath="url(#clip_payment_success)" > <path d="M22.6373 196.797H232.466C234.01 196.775 235.483 196.143 236.562 195.038C237.64 193.934 238.237 192.447 238.222 190.904V50.7664C238.237 49.2229 237.64 47.7363 236.562 46.6319C235.483 45.5274 234.01 44.8952 232.466 44.8735H22.6373C21.094 44.8973 19.6227 45.5303 18.5445 46.6342C17.4663 47.7382 16.8686 49.2236 16.8818 50.7664V190.912C16.8708 192.454 17.4694 193.937 18.5474 195.039C19.6254 196.141 21.0954 196.773 22.6373 196.797Z" fill="#24262E" /> <path d="M0.0098877 217.376C0.0098877 224.445 5.76538 231.513 12.746 231.513H242.242C248.82 231.513 254.97 224.461 254.97 217.376H0.0098877Z" fill="#24262E" /> <path d="M233.724 196.796H21.2559L0.0098877 217.376H254.97L233.724 196.796Z" fill="#D1D4DB" /> <path d="M226.703 198.432H28.401L21.3218 207.087H233.79L226.703 198.432Z" fill="#AFB3C0" /> <path d="M149.357 210.892H105.755L102.483 215.215H152.621L149.357 210.892Z" fill="#24262E" /> <path d="M225.288 57.6704H29.8234V184.001H225.288V57.6704Z" fill="#DDDFE4" /> <path d="M153.186 90.751L113.343 134.562L101.779 125.806H95.3497L113.343 155.016L159.615 90.751H153.186Z" fill="#339970" /> <path d="M127.552 48.1526C128.202 48.1526 128.838 48.3454 129.379 48.7066C129.92 49.0679 130.341 49.5813 130.59 50.182C130.839 50.7827 130.904 51.4437 130.777 52.0814C130.651 52.7192 130.337 53.3049 129.877 53.7647C129.417 54.2245 128.831 54.5376 128.193 54.6644C127.555 54.7913 126.894 54.7261 126.293 54.4773C125.692 54.2285 125.179 53.8071 124.817 53.2665C124.456 52.7259 124.263 52.0903 124.263 51.4401C124.263 50.5682 124.609 49.732 125.226 49.1155C125.843 48.4989 126.68 48.1526 127.552 48.1526Z" fill="#DDDFE4" /> <path d="M145.838 226.581H109.15C107.884 226.581 104.538 226.581 104.538 222.307H150.475C150.475 226.581 147.03 226.581 145.838 226.581Z" fill="#3F4350" /> </g> <path d="M307.836 95.9331C311.392 99.4834 312.126 104.864 309.445 107.979L247.319 180.211C243.548 184.598 236.935 184.715 232.639 180.412L179.605 127.366C175.296 123.056 175.419 116.456 179.799 112.685L252.031 50.5654C255.146 47.8913 260.519 48.6182 264.075 52.1815L307.836 95.9331Z" fill="#BABEC9" /> <path d="M283.016 71.231L202.947 151.039L184.295 132.192L267.629 55.6836L283.016 71.231Z" fill="#363A45" /> <path d="M279.947 87.0945L223.559 144.847L238.672 160.013L293.112 100.299L279.947 87.0945Z" fill="white" /> <path d="M247.841 139.774C244.735 136.785 246.576 131.177 247.708 128.122C249.461 123.387 251.308 132.473 251.397 133.882C251.694 138.499 251.306 143.137 250.245 147.63C249.65 150.15 248.78 152.591 247.651 154.904C246.973 156.332 246.001 157.585 244.804 158.574C241.831 160.452 239.939 158.627 239.174 153.112C239.483 151.426 240.257 149.872 241.401 148.641C245.285 143.596 251.428 141.05 255.952 137.135C256.395 136.745 255.686 136.018 255.249 136.395C249.866 141.07 238.8 144.925 238.168 154.163C237.712 160.266 243.64 161.576 246.816 158.177C250.947 153.76 252.004 145.712 252.358 139.661C252.567 136.15 253.421 126.436 248.486 125.259C248.391 125.227 248.289 125.229 248.195 125.267C248.102 125.304 248.024 125.374 247.974 125.464C246.019 129.055 243.223 136.58 247.265 140.481C247.305 140.543 247.358 140.595 247.42 140.632C247.482 140.669 247.551 140.69 247.623 140.695C247.694 140.699 247.765 140.686 247.831 140.657C247.896 140.627 247.955 140.582 248.001 140.526C248.047 140.469 248.08 140.401 248.097 140.329C248.115 140.257 248.115 140.181 248.1 140.108C248.084 140.035 248.053 139.967 248.008 139.909C247.963 139.851 247.906 139.805 247.841 139.774Z" fill="#505667" /> <path d="M255.236 137.171C259.742 139.71 260.856 129.601 260.27 126.845C260.249 126.763 260.208 126.688 260.151 126.626C260.094 126.565 260.023 126.519 259.944 126.493C259.865 126.467 259.782 126.461 259.7 126.477C259.619 126.492 259.542 126.528 259.478 126.582C257.116 128.509 256.697 133.587 258.706 136.54C258.745 136.616 258.804 136.679 258.876 136.723C258.948 136.767 259.031 136.79 259.114 136.79C259.198 136.79 259.281 136.767 259.353 136.723C259.425 136.679 259.484 136.616 259.523 136.54C260.818 133.802 261.914 130.971 262.8 128.068C263.199 126.845 264.235 127.127 265.053 126.279C266.714 124.556 268.329 122.806 269.958 121.096C272.011 118.925 272.719 116.064 274.618 113.861C277.039 111.085 279.369 109.743 280.579 105.922C280.856 105.047 280.875 103.021 279.401 102.909C276.569 102.686 274.078 108.829 277.863 108.224C282.491 107.507 286.643 102.001 289.643 99.0745C290.003 98.7259 289.34 98.055 288.999 98.4167C287.505 99.8704 285.973 101.317 284.383 102.712C283.117 103.83 281.793 104.88 280.418 105.856C279.716 106.349 274.425 108.737 277.785 104.725L279.575 106.145C279.388 106.651 279.173 107.145 278.931 107.625C278.479 108.515 277.949 109.36 277.348 110.151C276.24 111.697 274.483 112.598 273.228 114.032C271.631 115.86 271.007 118.472 269.301 120.379C268.548 121.221 264.428 126.601 262.961 125.963C262.867 125.929 262.765 125.932 262.673 125.971C262.581 126.01 262.507 126.082 262.465 126.174C261.989 127.562 261.525 128.963 261.055 130.37C260.888 130.883 258.931 134.882 258.989 135.02C258.25 132.883 258.305 130.542 259.143 128.443C259.418 128.958 259.582 129.527 259.625 130.112C259.668 130.697 259.59 131.285 259.394 131.837C259.066 134.33 257.824 135.823 255.68 136.283C255.623 136.254 255.561 136.236 255.497 136.23C255.433 136.225 255.369 136.233 255.308 136.253C255.247 136.273 255.191 136.305 255.142 136.348C255.093 136.39 255.053 136.442 255.024 136.5C254.995 136.559 254.977 136.622 254.972 136.688C254.967 136.753 254.974 136.819 254.994 136.881C255.014 136.943 255.045 137.001 255.087 137.051C255.128 137.101 255.179 137.142 255.236 137.171Z" fill="#505667" /> <defs> <clipPath id="clip_payment_success" > <rect fill="white" height="217.226" transform="translate(0.0098877 14.2778)" width="254.96" /> </clipPath> </defs> </svg> </PaymentSuccessStandardSvg> </div> <h3 className="IconMessage-h3" > <FormattedMessage defaultMessage="You are now subscribed to {selectedProductName}" id="admin.billing.subscription.proratedPayment.title" values={ Object { "selectedProductName": undefined, } } > <span> You are now subscribed to </span> </FormattedMessage> </h3> <div className="IconMessage-sub" > <FormattedMessage defaultMessage="Your final bill will be prorated. Your workspace now has {plan} limits." id="success_modal.subtitle" values={ Object { "plan": undefined, } } > <span> Your final bill will be prorated. Your workspace now has limits. </span> </FormattedMessage> </div> <div className="IconMessage-buttons" > <div className="IconMessage-button" > <button className="btn btn-primary Form-btn" onClick={[Function]} > <FormattedMessage defaultMessage="Return to workspace" id="success_modal.return_to_workspace" > <span> Return to workspace </span> </FormattedMessage> </button> </div> </div> </div> </div> </IconMessage> </div> </div> <div style={ Object { "display": "none", } } tabIndex={0} /> </Transition> </CSSTransition> </FullScreenModal> </injectIntl(FullScreenModal)> </injectIntl(FullScreenModal)> </SuccessModal> </Provider> `;
1,825
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/cloud_usage_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 redux from 'react-redux'; import type {Subscription} from '@mattermost/types/cloud'; import type {GlobalState} from '@mattermost/types/store'; import type {DeepPartial} from '@mattermost/types/utilities'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {Constants} from 'utils/constants'; import {FileSizes} from 'utils/file_utils'; import CloudUsageModal from './index'; import type {Props} from './index'; const freeLimits = { messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, teamsLimits: true, }, }; function setupState(hasLimits: boolean) { const state: DeepPartial<GlobalState> = { entities: { cloud: { limits: { limitsLoaded: hasLimits, limits: hasLimits ? freeLimits : {}, }, subscription: {} as Subscription, }, usage: { files: { totalStorage: 0, totalStorageLoaded: true, }, messages: { history: 0, historyLoaded: true, }, teams: { active: 0, cloudArchived: 0, teamsLoaded: true, }, }, admin: { analytics: { [Constants.StatTypes.TOTAL_POSTS]: 1234, } as GlobalState['entities']['admin']['analytics'], }, teams: { currentTeamId: '', }, preferences: { myPreferences: { }, }, general: { license: {}, config: {}, }, users: { currentUserId: 'uid', profiles: { uid: {}, }, } as unknown as GlobalState['entities']['users'], }, }; return state; } let props: Props = { title: '', onClose: jest.fn(), }; describe('CloudUsageModal', () => { beforeEach(() => { jest.spyOn(redux, 'useDispatch').mockImplementation(jest.fn(() => jest.fn())); props = { title: '', onClose: jest.fn(), needsTheme: false, }; }); test('renders text elements', () => { const state = setupState(true); props.title = 'very important title'; props.description = 'very important description'; renderWithContext( <CloudUsageModal {...props} />, state, ); screen.getByText(props.title as string); screen.getByText(props.description as string); }); test('renders primary modal action', () => { const state = setupState(true); props.primaryAction = { message: 'primary action', onClick: jest.fn(), }; renderWithContext( <CloudUsageModal {...props} />, state, ); expect(props.primaryAction.onClick).not.toHaveBeenCalled(); screen.getByText(props.primaryAction.message as string).click(); expect(props.primaryAction.onClick).toHaveBeenCalled(); }); test('renders secondary modal action', () => { const state = setupState(true); props.secondaryAction = { message: 'secondary action', }; renderWithContext( <CloudUsageModal {...props} />, state, ); expect(props.onClose).not.toHaveBeenCalled(); screen.getByText(props.secondaryAction.message as string).click(); expect(props.onClose).toHaveBeenCalled(); }); test('hides footer when there are no actions', () => { const state = setupState(true); renderWithContext( <CloudUsageModal {...props} />, state, ); expect(screen.queryByTestId('limits-modal-footer')).not.toBeInTheDocument(); }); });
1,831
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/code_block/code_block.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ReactWrapper} from 'enzyme'; import {mount} from 'enzyme'; import React from 'react'; import {act} from 'react-dom/test-utils'; import {IntlProvider} from 'react-intl'; import {Provider as ReduxProvider} from 'react-redux'; import mockStore from 'tests/test_store'; import CodeBlock from './code_block'; const actImmediate = (wrapper: ReactWrapper) => act( () => new Promise<void>((resolve) => { setImmediate(() => { wrapper.update(); resolve(); }); }), ); describe('codeBlock', () => { const state = { plugins: {components: {CodeBlockAction: []}}, }; const store = mockStore(state); test('should render typescript code block before syntax highlighting', async () => { const language = 'typescript'; const input = `\`\`\`${language} const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` `; const wrapper = mount( <ReduxProvider store={store}> <IntlProvider locale='en'> <CodeBlock code={input} language={language} /> </IntlProvider> </ReduxProvider>, ); await actImmediate(wrapper); const languageHeader = wrapper.find('span.post-code__language').text(); const lineNumbersDiv = wrapper.find('.post-code__line-numbers').exists(); expect(languageHeader).toEqual('TypeScript'); expect(lineNumbersDiv).toBeTruthy(); expect(wrapper).toMatchSnapshot(); }); test('should render typescript code block after syntax highlighting', async () => { const language = 'typescript'; const input = `\`\`\`${language} const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` `; const wrapper = mount( <ReduxProvider store={store}> <IntlProvider locale='en'> <CodeBlock code={input} language={language} /> </IntlProvider> </ReduxProvider>, ); await actImmediate(wrapper); const languageHeader = wrapper.find('span.post-code__language').text(); const lineNumbersDiv = wrapper.find('.post-code__line-numbers').exists(); expect(languageHeader).toEqual('TypeScript'); expect(lineNumbersDiv).toBeTruthy(); expect(wrapper).toMatchSnapshot(); }); test('should render html code block with proper indentation before syntax highlighting', async () => { const language = 'html'; const input = `\`\`\`${language} <div className='myClass'> <a href='https://randomgibberishurl.com'>ClickMe</a> </div> \`\`\` `; const wrapper = mount( <ReduxProvider store={store}> <IntlProvider locale='en'> <CodeBlock code={input} language={language} /> </IntlProvider> </ReduxProvider>, ); await actImmediate(wrapper); const languageHeader = wrapper.find('span.post-code__language').text(); const lineNumbersDiv = wrapper.find('.post-code__line-numbers').exists(); expect(languageHeader).toEqual('HTML, XML'); expect(lineNumbersDiv).toBeTruthy(); expect(wrapper).toMatchSnapshot(); }); test('should render html code block with proper indentation after syntax highlighting', async () => { const language = 'html'; const input = `\`\`\`${language} <div className='myClass'> <a href='https://randomgibberishurl.com'>ClickMe</a> </div> \`\`\` `; const wrapper = mount( <ReduxProvider store={store}> <IntlProvider locale='en'> <CodeBlock code={input} language={language} /> </IntlProvider> </ReduxProvider>, ); await actImmediate(wrapper); const languageHeader = wrapper.find('span.post-code__language').text(); const lineNumbersDiv = wrapper.find('.post-code__line-numbers').exists(); expect(languageHeader).toEqual('HTML, XML'); expect(lineNumbersDiv).toBeTruthy(); expect(wrapper).toMatchSnapshot(); }); test('should render unknown language before syntax highlighting', async () => { const language = 'unknownLanguage'; const input = `\`\`\`${language} this is my unknown language it shouldn't highlight, it's just garbage \`\`\` `; const wrapper = mount( <ReduxProvider store={store}> <IntlProvider locale='en'> <CodeBlock code={input} language={language} /> </IntlProvider> </ReduxProvider>, ); await actImmediate(wrapper); const languageHeader = wrapper.find('span.post-code__language').exists(); const lineNumbersDiv = wrapper.find('.post-code__line-numbers').exists(); expect(languageHeader).toBeFalsy(); expect(lineNumbersDiv).toBeFalsy(); expect(wrapper).toMatchSnapshot(); }); test('should render unknown language after syntax highlighting', async () => { const language = 'unknownLanguage'; const input = `\`\`\`${language} this is my unknown language it shouldn't highlight, it's just garbage \`\`\` `; const wrapper = mount( <ReduxProvider store={store}> <IntlProvider locale='en'> <CodeBlock code={input} language={language} /> </IntlProvider> </ReduxProvider>, ); await actImmediate(wrapper); const languageHeader = wrapper.find('span.post-code__language').exists(); const lineNumbersDiv = wrapper.find('.post-code__line-numbers').exists(); expect(languageHeader).toBeFalsy(); expect(lineNumbersDiv).toBeFalsy(); expect(wrapper).toMatchSnapshot(); }); });
1,833
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/code_block
petrpan-code/mattermost/mattermost/webapp/channels/src/components/code_block/__snapshots__/code_block.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`codeBlock should render html code block with proper indentation after syntax highlighting 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={Object {}} onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <CodeBlock code="\`\`\`html <div className='myClass'> <a href='https://randomgibberishurl.com'>ClickMe</a> </div> \`\`\` " language="html" > <div className="post-code" > <div className="post-code__overlay" > <CopyButton afterCopyText="Copied" content="\`\`\`html <div className='myClass'> <a href='https://randomgibberishurl.com'>ClickMe</a> </div> \`\`\` " placement="top" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="copyButton" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="copyButton" 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": Symbol(react.fragment), "timeZone": undefined, "wrapRichTextChunksInFragment": undefined, } } placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </OverlayWrapper> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <span className="post-code__clipboard" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-content-copy" role="button" /> </span> </OverlayTrigger> </OverlayTrigger> </CopyButton> <span className="post-code__language" > HTML, XML </span> </div> <div className="hljs" > <div className="post-code__line-numbers" > 1 2 3 4 5 6 </div> <code dangerouslySetInnerHTML={ Object { "__html": "\`\`\`html <span class=\\"hljs-tag\\">&lt;<span class=\\"hljs-name\\">div</span> <span class=\\"hljs-attr\\">className</span>=<span class=\\"hljs-string\\">&#x27;myClass&#x27;</span>&gt;</span> <span class=\\"hljs-tag\\">&lt;<span class=\\"hljs-name\\">a</span> <span class=\\"hljs-attr\\">href</span>=<span class=\\"hljs-string\\">&#x27;https://randomgibberishurl.com&#x27;</span>&gt;</span>ClickMe<span class=\\"hljs-tag\\">&lt;/<span class=\\"hljs-name\\">a</span>&gt;</span> <span class=\\"hljs-tag\\">&lt;/<span class=\\"hljs-name\\">div</span>&gt;</span> \`\`\` ", } } /> </div> </div> </CodeBlock> </IntlProvider> </Provider> `; exports[`codeBlock should render html code block with proper indentation before syntax highlighting 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={Object {}} onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <CodeBlock code="\`\`\`html <div className='myClass'> <a href='https://randomgibberishurl.com'>ClickMe</a> </div> \`\`\` " language="html" > <div className="post-code" > <div className="post-code__overlay" > <CopyButton afterCopyText="Copied" content="\`\`\`html <div className='myClass'> <a href='https://randomgibberishurl.com'>ClickMe</a> </div> \`\`\` " placement="top" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="copyButton" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="copyButton" 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": Symbol(react.fragment), "timeZone": undefined, "wrapRichTextChunksInFragment": undefined, } } placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </OverlayWrapper> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <span className="post-code__clipboard" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-content-copy" role="button" /> </span> </OverlayTrigger> </OverlayTrigger> </CopyButton> <span className="post-code__language" > HTML, XML </span> </div> <div className="hljs" > <div className="post-code__line-numbers" > 1 2 3 4 5 6 </div> <code dangerouslySetInnerHTML={ Object { "__html": "\`\`\`html <span class=\\"hljs-tag\\">&lt;<span class=\\"hljs-name\\">div</span> <span class=\\"hljs-attr\\">className</span>=<span class=\\"hljs-string\\">&#x27;myClass&#x27;</span>&gt;</span> <span class=\\"hljs-tag\\">&lt;<span class=\\"hljs-name\\">a</span> <span class=\\"hljs-attr\\">href</span>=<span class=\\"hljs-string\\">&#x27;https://randomgibberishurl.com&#x27;</span>&gt;</span>ClickMe<span class=\\"hljs-tag\\">&lt;/<span class=\\"hljs-name\\">a</span>&gt;</span> <span class=\\"hljs-tag\\">&lt;/<span class=\\"hljs-name\\">div</span>&gt;</span> \`\`\` ", } } /> </div> </div> </CodeBlock> </IntlProvider> </Provider> `; exports[`codeBlock should render typescript code block after syntax highlighting 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={Object {}} onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <CodeBlock code="\`\`\`typescript const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` " language="typescript" > <div className="post-code" > <div className="post-code__overlay" > <CopyButton afterCopyText="Copied" content="\`\`\`typescript const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` " placement="top" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="copyButton" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="copyButton" 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": Symbol(react.fragment), "timeZone": undefined, "wrapRichTextChunksInFragment": undefined, } } placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </OverlayWrapper> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <span className="post-code__clipboard" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-content-copy" role="button" /> </span> </OverlayTrigger> </OverlayTrigger> </CopyButton> <span className="post-code__language" > TypeScript </span> </div> <div className="hljs" > <div className="post-code__line-numbers" > 1 2 3 4 5 6 </div> <code dangerouslySetInnerHTML={ Object { "__html": "<span class=\\"hljs-string\\">\`\`</span><span class=\\"hljs-string\\">\`typescript const myFunction = () =&gt; { console.log(&#x27;This is a meaningful function&#x27;); }; \`</span><span class=\\"hljs-string\\">\`\`</span> ", } } /> </div> </div> </CodeBlock> </IntlProvider> </Provider> `; exports[`codeBlock should render typescript code block before syntax highlighting 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={Object {}} onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <CodeBlock code="\`\`\`typescript const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` " language="typescript" > <div className="post-code" > <div className="post-code__overlay" > <CopyButton afterCopyText="Copied" content="\`\`\`typescript const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` " placement="top" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="copyButton" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="copyButton" 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": Symbol(react.fragment), "timeZone": undefined, "wrapRichTextChunksInFragment": undefined, } } placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </OverlayWrapper> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <span className="post-code__clipboard" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-content-copy" role="button" /> </span> </OverlayTrigger> </OverlayTrigger> </CopyButton> <span className="post-code__language" > TypeScript </span> </div> <div className="hljs" > <div className="post-code__line-numbers" > 1 2 3 4 5 6 </div> <code dangerouslySetInnerHTML={ Object { "__html": "<span class=\\"hljs-string\\">\`\`</span><span class=\\"hljs-string\\">\`typescript const myFunction = () =&gt; { console.log(&#x27;This is a meaningful function&#x27;); }; \`</span><span class=\\"hljs-string\\">\`\`</span> ", } } /> </div> </div> </CodeBlock> </IntlProvider> </Provider> `; exports[`codeBlock should render unknown language after syntax highlighting 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={Object {}} onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <CodeBlock code="\`\`\`unknownLanguage this is my unknown language it shouldn't highlight, it's just garbage \`\`\` " language="unknownLanguage" > <div className="post-code" > <div className="post-code__overlay" > <CopyButton afterCopyText="Copied" content="\`\`\`unknownLanguage this is my unknown language it shouldn't highlight, it's just garbage \`\`\` " placement="top" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="copyButton" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="copyButton" 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": Symbol(react.fragment), "timeZone": undefined, "wrapRichTextChunksInFragment": undefined, } } placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </OverlayWrapper> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <span className="post-code__clipboard" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-content-copy" role="button" /> </span> </OverlayTrigger> </OverlayTrigger> </CopyButton> </div> <div className="hljs" > <code dangerouslySetInnerHTML={ Object { "__html": "\`\`\`unknownLanguage this is my unknown language it shouldn&apos;t highlight, it&apos;s just garbage \`\`\` ", } } /> </div> </div> </CodeBlock> </IntlProvider> </Provider> `; exports[`codeBlock should render unknown language before syntax highlighting 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={Object {}} onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <CodeBlock code="\`\`\`unknownLanguage this is my unknown language it shouldn't highlight, it's just garbage \`\`\` " language="unknownLanguage" > <div className="post-code" > <div className="post-code__overlay" > <CopyButton afterCopyText="Copied" content="\`\`\`unknownLanguage this is my unknown language it shouldn't highlight, it's just garbage \`\`\` " placement="top" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="copyButton" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </Tooltip> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="copyButton" 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": Symbol(react.fragment), "timeZone": undefined, "wrapRichTextChunksInFragment": undefined, } } placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Copy code" id="copy.code.message" /> </OverlayWrapper> } placement="top" shouldUpdatePosition={true} trigger={ Array [ "hover", "focus", ] } > <span className="post-code__clipboard" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="icon icon-content-copy" role="button" /> </span> </OverlayTrigger> </OverlayTrigger> </CopyButton> </div> <div className="hljs" > <code dangerouslySetInnerHTML={ Object { "__html": "\`\`\`unknownLanguage this is my unknown language it shouldn&apos;t highlight, it&apos;s just garbage \`\`\` ", } } /> </div> </div> </CodeBlock> </IntlProvider> </Provider> `;
1,835
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/commercial_support_modal/commercial_support_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 CommercialSupportModal from 'components/commercial_support_modal/commercial_support_modal'; import {TestHelper} from 'utils/test_helper'; describe('components/CommercialSupportModal', () => { test('should match snapshot', () => { const mockUser = TestHelper.getUserMock(); const wrapper = shallow( <CommercialSupportModal onExited={jest.fn()} showBannerWarning={true} isCloud={false} currentUser={mockUser} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,838
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/commercial_support_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/commercial_support_modal/__snapshots__/commercial_support_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/CommercialSupportModal should match snapshot 1`] = ` <Modal animation={true} autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-direct-channels" dialogComponentClass={[Function]} enforceFocus={true} id="commercialSupportModal" 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} show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h4" > <MemoizedFormattedMessage defaultMessage="Commercial Support" id="commercial_support.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="CommercialSupportModal" > <FormattedMarkdownMessage defaultMessage="If you're experiencing issues, [submit a support ticket.](!{supportLink}) **Download Support Packet** We recommend that you download additional environment details about your Mattermost environment to help with troubleshooting. Once downloaded, attach the packet to your support ticket to share with our Customer Support team." id="commercial_support.description" values={ Object { "supportLink": "https://support.mattermost.com/hc/en-us/requests/new", } } /> <a className="btn btn-primary DownloadSupportPacket" href="/api/v4/system/support_packet" rel="noopener noreferrer" > <MemoizedFormattedMessage defaultMessage="Download Support Packet" id="commercial_support.download_support_packet" /> </a> <AlertBanner message={ <FormattedMarkdownMessage defaultMessage="Before downloading the support packet, set **Output Logs to File** to **true** and set **File Log Level** to **DEBUG** [here](!/admin_console/environment/logging)." id="commercial_support.warning.banner" /> } mode="info" onDismiss={[Function]} /> </div> </ModalBody> </Modal> `;
1,843
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/infinite_scroll.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ReactWrapper} from 'enzyme'; import React from 'react'; import InfiniteScroll from 'components/common/infinite_scroll'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; describe('/components/common/InfiniteScroll', () => { const baseProps = { callBack: jest.fn(), endOfData: false, endOfDataMessage: 'No more items to fetch', styleClass: 'signup-team-all', totalItems: 20, itemsPerPage: 10, pageNumber: 1, }; let wrapper: ReactWrapper<any, any, InfiniteScroll>; beforeEach(() => { wrapper = mountWithIntl(<InfiniteScroll {...baseProps}><div/></InfiniteScroll>) as unknown as ReactWrapper<any, any, InfiniteScroll>; }); test('should match snapshot', () => { expect(wrapper).toMatchSnapshot(); const wrapperDiv = wrapper.find(`.${baseProps.styleClass}`); // InfiniteScroll is styled by the user's style expect(wrapperDiv.exists()).toBe(true); // Ensure that scroll is added to InfiniteScroll wrapper div expect(wrapperDiv.hasClass('infinite-scroll')).toBe(true); }); test('should attach and remove event listeners', () => { const instance = wrapper.instance(); const node = instance.node; node.current!.addEventListener = jest.fn(); node.current!.removeEventListener = jest.fn(); instance.componentDidMount(); expect(node.current!.addEventListener).toHaveBeenCalledTimes(1); expect(node.current!.removeEventListener).not.toBeCalled(); instance.componentWillUnmount(); expect(node.current!.removeEventListener).toHaveBeenCalledTimes(1); }); test('should execute call back function when scroll reaches the bottom and there \'s more data and no current fetch is taking place', () => { const instance = wrapper.instance(); expect(baseProps.callBack).toHaveBeenCalledTimes(0); instance.handleScroll(); expect(wrapper.state().isFetching).toBe(true); expect(baseProps.callBack).toHaveBeenCalledTimes(1); }); test('should not execute call back even if scroll is a the bottom when there \'s no more data', () => { wrapper.setState({isEndofData: true}); const instance = wrapper.instance(); instance.handleScroll(); expect(baseProps.callBack).toHaveBeenCalledTimes(0); }); test('should not show loading screen if there is no data', () => { let loadingDiv = wrapper.find('.loading-screen'); expect(loadingDiv.exists()).toBe(false); wrapper.setState({isFetching: true}); expect(wrapper).toMatchSnapshot(); expect(wrapper.state().isFetching).toBe(true); // Now it should show the loader. loadingDiv = wrapper.find('.loading-screen'); expect(loadingDiv.exists()).toBe(true); }); });
1,845
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/radio_group.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 RadioButtonGroup from 'components/common/radio_group'; describe('/components/common/RadioButtonGroup', () => { const onChange = jest.fn(); const baseProps = { id: 'test-string', value: 'value2', values: [{key: 'key1', value: 'value1'}, {key: 'key2', value: 'value2'}, {key: 'key3', value: 'value3'}], onChange, }; test('should match snapshot', () => { const wrapper = shallow(<RadioButtonGroup {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('test radio button group input lenght is as expected', () => { const wrapper = shallow(<RadioButtonGroup {...baseProps}/>); const buttons = wrapper.find('input'); expect(buttons.length).toBe(3); }); test('test radio button group onChange function', () => { const wrapper = shallow(<RadioButtonGroup {...baseProps}/>); const buttons = wrapper.find('input'); buttons.at(0).simulate('change'); expect(onChange).toHaveBeenCalledTimes(1); }); });
1,847
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/site_name_and_description.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 {FormattedMessage} from 'react-intl'; import SiteNameAndDescription from 'components/common/site_name_and_description'; describe('/components/common/SiteNameAndDescription', () => { const baseProps = { customDescriptionText: '', siteName: 'Mattermost', }; test('should match snapshot, default', () => { const wrapper = shallow(<SiteNameAndDescription {...baseProps}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('h1').text()).toEqual(baseProps.siteName); expect(wrapper.find(FormattedMessage).exists()).toBe(true); }); test('should match snapshot, with custom site name and description', () => { const props = {...baseProps, customDescriptionText: 'custom_description_text', siteName: 'other_site'}; const wrapper = shallow(<SiteNameAndDescription {...props}/>); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('h1').text()).toEqual(props.siteName); expect(wrapper.find('h3').text()).toEqual(props.customDescriptionText); }); });
1,849
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/__snapshots__/infinite_scroll.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/InfiniteScroll should match snapshot 1`] = ` <InfiniteScroll bufferValue={100} callBack={[MockFunction]} endOfData={false} endOfDataMessage="No more items to fetch" itemsPerPage={10} loaderStyle={Object {}} pageNumber={1} styleClass="signup-team-all" totalItems={20} > <div className="infinite-scroll signup-team-all" > <div /> No more items to fetch </div> </InfiniteScroll> `; exports[`/components/common/InfiniteScroll should not show loading screen if there is no data 1`] = ` <InfiniteScroll bufferValue={100} callBack={[MockFunction]} endOfData={false} endOfDataMessage="No more items to fetch" itemsPerPage={10} loaderStyle={Object {}} pageNumber={1} styleClass="signup-team-all" totalItems={20} > <div className="infinite-scroll signup-team-all" > <div /> <LoadingScreen message=" " style={Object {}} > <div className="loading-screen" style={ Object { "position": "relative", } } > <div className="loading__content" > <p> </p> <div className="round round-1" /> <div className="round round-2" /> <div className="round round-3" /> </div> </div> </LoadingScreen> </div> </InfiniteScroll> `;
1,850
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/__snapshots__/radio_group.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/RadioButtonGroup should match snapshot 1`] = ` <div className="radio-list" data-testid="" > <div className="radio" key="value1" > <label className="" > <input checked={false} disabled={false} name="test-string" onChange={[Function]} type="radio" value="value1" /> key1 </label> </div> <div className="radio" key="value2" > <label className="selected" > <input checked={true} disabled={false} name="test-string" onChange={[Function]} type="radio" value="value2" /> key2 </label> </div> <div className="radio" key="value3" > <label className="" > <input checked={false} disabled={false} name="test-string" onChange={[Function]} type="radio" value="value3" /> key3 </label> </div> </div> `;
1,851
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/__snapshots__/site_name_and_description.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/SiteNameAndDescription should match snapshot, default 1`] = ` <Fragment> <h1 id="site_name" > Mattermost </h1> <h3 className="color--light" id="site_description" > <MemoizedFormattedMessage defaultMessage="All team communication in one place, searchable and accessible anywhere" id="web.root.signup_info" /> </h3> </Fragment> `; exports[`/components/common/SiteNameAndDescription should match snapshot, with custom site name and description 1`] = ` <Fragment> <h1 id="site_name" > other_site </h1> <h3 className="color--light" id="site_description" > custom_description_text </h3> </Fragment> `;
1,853
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/accordion/accordion.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 Accordion from 'components/common/accordion/accordion'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; describe('/components/common/Accordion', () => { const texts = ['First List Item', 'Second List Item', 'Third List Item']; const baseProps = { onHeaderClick: jest.fn(), openMultiple: false, accordionItemsData: [ { title: 'First Accordion Item', description: 'First accordion Item Description', items: [ ( <p className='accordion-item-content-el' key={1} > {texts[0]} </p> ), ( <p className='accordion-item-content-el' key={2} > {texts[1]} </p> ), ], }, { title: 'Second Accordion Item', description: 'Second accordion Item Description', items: [ ( <p className='accordion-item-content-el' key={1} > {texts[2]} </p> ), ], }, ], }; test('should match snapshot', () => { const wrapper = shallow(<Accordion {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('test accordion items length is 2 as specified in items property in baseProps', () => { const wrapper = shallow(<Accordion {...baseProps}/>); const accordionItems = wrapper.find('AccordionCard'); expect(accordionItems.length).toBe(2); }); test('test accordion opens first accordion item when clicked', () => { const wrapper = mountWithIntl(<Accordion {...baseProps}/>); const firstAccordionCard = wrapper.find('ul AccordionCard:first-child'); const header = firstAccordionCard.find('div.accordion-card-header'); header.simulate('click'); const firstChildItem = firstAccordionCard.find('div.accordion-card-container p.accordion-item-content-el:first-child'); const slide1Text = firstChildItem.text(); expect(slide1Text).toEqual('First List Item'); }); test('test accordion opens ONLY one accordion item at a time if NO openMultiple prop is set or set to FALSE', () => { const wrapper = mountWithIntl(<Accordion {...baseProps}/>); const firstAccordionCard = wrapper.find('ul AccordionCard:first-child'); const secondAccordionCard = wrapper.find('ul AccordionCard:last-child'); const header1 = firstAccordionCard.find('div.accordion-card-header'); const header2 = secondAccordionCard.find('div.accordion-card-header'); header1.simulate('click'); // refind the element after making changes so those gets reflected const firstAccordionCardAfterEvent = wrapper.find('ul AccordionCard:first-child'); const secondAccordionCardAfterEvent = wrapper.find('ul AccordionCard:last-child'); // clicking first list element should only apply the active class to the first one and not to the last expect(firstAccordionCardAfterEvent.find('li.accordion-card').hasClass('active')).toEqual(true); expect(secondAccordionCardAfterEvent.find('li.accordion-card').hasClass('active')).toEqual(false); header2.simulate('click'); // refind the element after making changes so those gets reflected const firstAccordionCardAfterEvent1 = wrapper.find('ul AccordionCard:first-child'); const secondAccordionCardAfterEvent1 = wrapper.find('ul AccordionCard:last-child'); // clicking last list element should only apply the active class to the last one and not to the first expect(firstAccordionCardAfterEvent1.find('li.accordion-card').hasClass('active')).toEqual(false); expect(secondAccordionCardAfterEvent1.find('li.accordion-card').hasClass('active')).toEqual(true); }); test('test accordion opens MORE THAN one accordion item at a time if openMultiple prop IS set to TRUE', () => { const wrapper = mountWithIntl( <Accordion {...baseProps} expandMultiple={true} />); const firstAccordionCard = wrapper.find('ul AccordionCard:first-child'); const secondAccordionCard = wrapper.find('ul AccordionCard:last-child'); const header1 = firstAccordionCard.find('div.accordion-card-header'); const header2 = secondAccordionCard.find('div.accordion-card-header'); header1.simulate('click'); // refind the element after making changes so those gets reflected const firstAccordionCardAfterEvent = wrapper.find('ul AccordionCard:first-child'); const secondAccordionCardAfterEvent = wrapper.find('ul AccordionCard:last-child'); // clicking first list element should only apply the active class to the first one and not to the last expect(firstAccordionCardAfterEvent.find('li.accordion-card').hasClass('active')).toEqual(true); expect(secondAccordionCardAfterEvent.find('li.accordion-card').hasClass('active')).toEqual(false); header2.simulate('click'); // refind the element after making changes so those gets reflected const firstAccordionCardAfterEvent1 = wrapper.find('ul AccordionCard:first-child'); const secondAccordionCardAfterEvent1 = wrapper.find('ul AccordionCard:last-child'); // clicking last list element should apply active class to both expect(firstAccordionCardAfterEvent1.find('li.accordion-card').hasClass('active')).toEqual(true); expect(secondAccordionCardAfterEvent1.find('li.accordion-card').hasClass('active')).toEqual(true); }); });
1,856
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/accordion
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/accordion/__snapshots__/accordion.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/Accordion should match snapshot 1`] = ` <ul className="Accordion" > <AccordionCard data={ Object { "description": "First accordion Item Description", "items": Array [ <p className="accordion-item-content-el" > First List Item </p>, <p className="accordion-item-content-el" > Second List Item </p>, ], "title": "First Accordion Item", } } isExpanded={false} key="0" onButtonClick={[Function]} onHeaderClick={[MockFunction]} /> <AccordionCard data={ Object { "description": "Second accordion Item Description", "items": Array [ <p className="accordion-item-content-el" > Third List Item </p>, ], "title": "Second Accordion Item", } } isExpanded={false} key="1" onButtonClick={[Function]} onHeaderClick={[MockFunction]} /> </ul> `;
1,858
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/carousel/carousel.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 Carousel from 'components/common/carousel/carousel'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {BtnStyle} from './carousel_button'; describe('/components/common/Carousel', () => { const texts = ['First Slide', 'Second Slide', 'Third Slide']; const baseProps = { id: 'test-string', infiniteSlide: true, dataSlides: [ ( <p className='slide' key={1} > {texts[0]} </p>), ( <p className='slide' key={2} > {texts[1]} </p> ), ( <p className='slide' key={3} > {texts[2]} </p> ), ], }; test('should match snapshot', () => { const wrapper = shallow(<Carousel {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('test carouse slides lenght is as expected', () => { const wrapper = shallow(<Carousel {...baseProps}/>); const slides = wrapper.find('p.slide'); expect(slides.length).toBe(3); }); test('test carousel shows next and previous button', () => { const wrapper = mountWithIntl(<Carousel {...baseProps}/>); const buttonNext = wrapper.find('CarouselButton').find('a.next'); const buttonPrev = wrapper.find('CarouselButton').find('a.prev'); expect(buttonNext).toHaveLength(1); expect(buttonPrev).toHaveLength(1); }); test('test carousel shows next and previous chevrons when this option is sent', () => { const wrapper = mountWithIntl( <Carousel {...baseProps} btnsStyle={BtnStyle.CHEVRON} />, ); const nextButton = wrapper.find(Carousel).find('CarouselButton div.chevron-right'); const prevButton = wrapper.find(Carousel).find('CarouselButton div.chevron-left'); expect(nextButton).toHaveLength(1); expect(prevButton).toHaveLength(1); }); test('test carousel shows first slide as active', () => { const wrapper = shallow(<Carousel {...baseProps}/>); const activeSlide = wrapper.find('div.active-anim'); const slideText = activeSlide.find('p.slide').text(); expect(slideText).toEqual('First Slide'); }); test('test carousel moves slides when clicking buttons', (done) => { const wrapper = mountWithIntl(<Carousel {...baseProps}/>); const activeSlide = wrapper.find('div.active-anim'); const slide1Text = activeSlide.find('p.slide').text(); expect(slide1Text).toEqual('First Slide'); const buttonNext = wrapper.find('CarouselButton').find('a.next'); buttonNext.simulate('click'); jest.useFakeTimers(); setTimeout(() => { const activeSlide = wrapper.find('div.active-anim'); const slide1Text = activeSlide.find('p.slide').text(); expect(slide1Text).toEqual('Second Slide'); done(); }, 1000); jest.runAllTimers(); }); test('test carousel executes custom next and prev btn callback functions', () => { const onPrevSlideClick = jest.fn(); const onNextSlideClick = jest.fn(); const props = { ...baseProps, onPrevSlideClick, onNextSlideClick}; const wrapper = mountWithIntl(<Carousel {...props}/>); const buttonNext = wrapper.find('CarouselButton').find('a.next'); const buttonPrev = wrapper.find('CarouselButton').find('a.prev'); buttonNext.simulate('click'); buttonPrev.simulate('click'); expect(onNextSlideClick).toHaveBeenCalledWith(2); expect(onPrevSlideClick).toHaveBeenCalledWith(1); }); });
1,861
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/carousel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/carousel/__snapshots__/carousel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/Carousel should match snapshot 1`] = ` <div className="container-slider" id="test-string" > <div className="slide active-anim" key="0" > <p className="slide" key="1" > First Slide </p> </div> <div className="slide" key="1" > <p className="slide" key="2" > Second Slide </p> </div> <div className="slide" key="2" > <p className="slide" key="3" > Third Slide </p> </div> <div className="container-footer" > <div className="container-dots" > <div className="dot active" key="0" onClick={[Function]} /> <div className="dot" key="1" onClick={[Function]} /> <div className="dot" key="2" onClick={[Function]} /> </div> <div className=" buttons container-buttons" > <CarouselButton direction="prev" disabled={false} moveSlide={[Function]} /> <CarouselButton direction="next" moveSlide={[Function]} /> </div> </div> </div> `;
1,864
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/circular_chart/circular_chart.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 CircularChart from 'components/common/circular_chart/circular_chart'; // import {mountWithIntl} from 'tests/helpers/intl-test-helper'; describe('/components/common/CircularChart', () => { const baseProps = { value: 75, isPercentage: false, width: 100, height: 100, }; test('should match snapshot', () => { const wrapper = shallow( <CircularChart {...baseProps} type={'success'} />); expect(wrapper).toMatchSnapshot(); }); test('test circularChart contains the text value as specified in the base props', () => { const wrapper = shallow( <CircularChart {...baseProps} type={'success'} />); const circularChartText = wrapper.find('.percentageOrNumber').text(); expect(parseInt(circularChartText, 10)).toBe(baseProps.value); }); test('test circularChart contains the text value with the percentage symbol when isPercentage is set to true', () => { const wrapper = shallow( <CircularChart {...{...baseProps, isPercentage: true}} type={'success'} />); const circularChartText = wrapper.find('.percentageOrNumber').text(); expect(circularChartText).toBe(`${baseProps.value.toString()} %`); }); });
1,866
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/circular_chart
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/circular_chart/__snapshots__/circular_chart.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/CircularChart should match snapshot 1`] = ` <div className="CircularChart" > <svg className="circular-chart success" height="100" viewBox="0 0 36 36" width="100" > <path className="circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" /> <path className="circle" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" strokeDasharray="75, 100" /> <text className="percentageOrNumber" x="18" y="20.70" > 75 </text> </svg> </div> `;
1,867
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hocs
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hocs/cloud/with_get_cloud_subscription.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import type {ComponentType} from 'react'; import withGetCloudSubscription from './with_get_cloud_subscription'; describe('/components/common/hocs/with_get_cloud_subcription', () => { let TestComponent: ComponentType; beforeEach(() => { TestComponent = () => <div/>; }); test('should call the getCloudSubscription when cloud license is being used and no subscription was fetched', () => { const EnhancedComponent = withGetCloudSubscription(TestComponent); const actions = { getCloudSubscription: () => {}, }; const getCloudSubscriptionSpy = jest.spyOn(actions, 'getCloudSubscription'); mount( <EnhancedComponent isCloud={true} actions={actions} subscription={{}} userIsAdmin={true} />, ); expect(getCloudSubscriptionSpy).toHaveBeenCalledTimes(1); }); test('should NOT call the getCloudSubscription when NOT cloud licenced', () => { const EnhancedComponent = withGetCloudSubscription(TestComponent); const actions = { getCloudSubscription: () => {}, }; const getCloudSubscriptionSpy = jest.spyOn(actions, 'getCloudSubscription'); mount( <EnhancedComponent isCloud={false} actions={actions} subscription={{}} userIsAdmin={true} />, ); expect(getCloudSubscriptionSpy).toHaveBeenCalledTimes(0); }); test('should NOT call the getCloudSubscription when user is NOT admin', () => { const EnhancedComponent = withGetCloudSubscription(TestComponent); const actions = { getCloudSubscription: () => {}, }; const getCloudSubscriptionSpy = jest.spyOn(actions, 'getCloudSubscription'); mount( <EnhancedComponent isCloud={true} actions={actions} subscription={{}} userIsAdmin={false} />, ); expect(getCloudSubscriptionSpy).toHaveBeenCalledTimes(0); }); });
1,870
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hocs
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hocs/cloud/with_use_get_usage_deltas.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import type {ComponentType} from 'react'; import withUseGetUsageDeltas from './with_use_get_usage_deltas'; jest.mock('components/common/hooks/useGetUsageDeltas', () => jest.fn(() => ({ teams: { active: -1, }, }))); describe('/components/common/hocs/cloud/with_use_get_usage_deltas', () => { const TestComponent: ComponentType = jest.fn(() => <div/>); test('should pass the useGetUsageDeltas', () => { const WrappedComponent = withUseGetUsageDeltas(TestComponent); const wrapper = mount( <WrappedComponent/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,872
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hocs/cloud
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hocs/cloud/__snapshots__/with_use_get_usage_deltas.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/common/hocs/cloud/with_use_get_usage_deltas should pass the useGetUsageDeltas 1`] = ` <Component> <mockConstructor usageDeltas={ Object { "teams": Object { "active": -1, }, } } > <div /> </mockConstructor> </Component> `;
1,885
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hooks/useGetHighestThresholdCloudLimit.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {FileSizes} from 'utils/file_utils'; import {limitThresholds, LimitTypes} from 'utils/limits'; import useGetHighestThresholdCloudLimit from './useGetHighestThresholdCloudLimit'; import type {LimitSummary} from './useGetHighestThresholdCloudLimit'; jest.mock('react', () => ({ useMemo: (fn: () => LimitSummary) => fn(), })); const zeroUsage = { files: { totalStorage: 0, totalStorageLoaded: true, }, messages: { history: 0, historyLoaded: true, }, boards: { cards: 0, cardsLoaded: true, }, integrations: { enabled: 0, enabledLoaded: true, }, teams: { active: 0, cloudArchived: 0, teamsLoaded: true, }, }; describe('useGetHighestThresholdCloudLimit', () => { const messageHistoryLimit = 10000; const filesLimit = FileSizes.Gigabyte; const okMessageUsage = Math.floor((limitThresholds.warn / 100) * messageHistoryLimit) - 1; const warnMessageUsage = Math.ceil((limitThresholds.warn / 100) * messageHistoryLimit) + 1; const tests = [ { label: 'reports no highest limit if there are no limits', limits: {}, usage: zeroUsage, expected: false, }, { label: 'reports no highest limit if no limit exceeds the warn threshold', limits: { messages: { history: messageHistoryLimit, }, }, usage: { ...zeroUsage, messages: { ...zeroUsage.messages, history: okMessageUsage, }, }, expected: false, }, { label: 'reports a highest limit if one exceeds a threshold', limits: { messages: { history: messageHistoryLimit, }, }, usage: { ...zeroUsage, messages: { ...zeroUsage.messages, history: warnMessageUsage, }, }, expected: { id: LimitTypes.messageHistory, limit: messageHistoryLimit, usage: warnMessageUsage, }, }, { label: 'messages beats files in tie', limits: { messages: { history: messageHistoryLimit, }, files: { total_storage: filesLimit, }, }, usage: { ...zeroUsage, messages: { ...zeroUsage.messages, history: messageHistoryLimit, }, files: { ...zeroUsage.files, totralStorage: filesLimit, }, }, expected: { id: LimitTypes.messageHistory, limit: messageHistoryLimit, usage: messageHistoryLimit, }, }, { label: 'files beats messages if higher', limits: { messages: { history: messageHistoryLimit, }, files: { total_storage: filesLimit, }, }, usage: { ...zeroUsage, messages: { ...zeroUsage.messages, history: messageHistoryLimit, }, files: { ...zeroUsage.files, totalStorage: filesLimit + FileSizes.Megabyte, }, }, expected: { id: LimitTypes.fileStorage, limit: filesLimit, usage: filesLimit + FileSizes.Megabyte, }, }, ]; tests.forEach((t: typeof tests[0]) => { test(t.label, () => { const actual = useGetHighestThresholdCloudLimit(t.usage, t.limits); expect(t.expected).toEqual(actual); }); }); });
1,888
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hooks/useGetMultiplesExceededCloudLimit.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {FileSizes} from 'utils/file_utils'; import {limitThresholds, LimitTypes} from 'utils/limits'; import useGetMultiplesExceededCloudLimit from './useGetMultiplesExceededCloudLimit'; import type {LimitSummary} from './useGetMultiplesExceededCloudLimit'; jest.mock('react', () => ({ useMemo: (fn: () => LimitSummary) => fn(), })); const zeroUsage = { files: { totalStorage: 0, totalStorageLoaded: true, }, messages: { history: 0, historyLoaded: true, }, boards: { cards: 0, cardsLoaded: true, }, integrations: { enabled: 0, enabledLoaded: true, }, teams: { active: 0, cloudArchived: 0, teamsLoaded: true, }, }; describe('useGetHighestThresholdCloudLimit', () => { const messageHistoryLimit = 10000; const filesLimit = FileSizes.Gigabyte; const exceededMessageUsage = Math.ceil((limitThresholds.exceeded / 100) * messageHistoryLimit) + 1; const tests = [ { label: 'reports no limits surpassed', limits: {}, usage: zeroUsage, expected: [], }, { label: 'reports messages limit surpasded', limits: { messages: { history: messageHistoryLimit, }, }, usage: { ...zeroUsage, messages: { ...zeroUsage.messages, history: exceededMessageUsage, }, }, expected: [LimitTypes.messageHistory], }, { label: 'reports files limit surpassed', limits: { files: { total_storage: filesLimit, }, }, usage: { ...zeroUsage, files: { ...zeroUsage.files, totalStorage: FileSizes.Gigabyte * 2, }, }, expected: [LimitTypes.fileStorage], }, { label: 'reports messages and files limit surpasded', limits: { messages: { history: messageHistoryLimit, }, files: { total_storage: filesLimit, }, }, usage: { ...zeroUsage, messages: { ...zeroUsage.messages, history: exceededMessageUsage, }, files: { ...zeroUsage.files, totalStorage: FileSizes.Gigabyte * 2, }, }, expected: [LimitTypes.messageHistory, LimitTypes.fileStorage], }, ]; tests.forEach((t: typeof tests[0]) => { test(t.label, () => { const actual = useGetMultiplesExceededCloudLimit(t.usage, t.limits); expect(t.expected).toEqual(actual); }); }); });
1,895
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hooks/useGetUsageDeltas.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {withBackupValue} from './useGetUsageDeltas'; describe('withBackupValue', () => { const tests = [ { label: 'if limits not loaded, assumes no limit', maybeLimit: undefined, limitsLoaded: false, expected: Number.MAX_VALUE, }, { label: 'if limits not loaded, assumes no limit even if there is data', maybeLimit: 4, limitsLoaded: false, expected: Number.MAX_VALUE, }, { label: 'if limits loaded and the limit is 0, returns 0', maybeLimit: 0, limitsLoaded: true, expected: 0, }, { label: 'if limits loaded and the limit is non-zero , returns the value', maybeLimit: 5, limitsLoaded: true, expected: 5, }, { label: 'if limits loaded and the limit is undefined, returns max value', maybeLimit: undefined, limitsLoaded: true, expected: Number.MAX_VALUE, }, ]; tests.forEach((t) => { it(t.label, () => { expect(withBackupValue(t.maybeLimit, t.limitsLoaded)).toBe(t.expected); }); }); });
1,907
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common
petrpan-code/mattermost/mattermost/webapp/channels/src/components/common/hooks/useShowAdminLimitReached.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ReactPortal} from 'react'; import * as useGetLimitsHook from 'components/common/hooks/useGetLimits'; import * as useGetUsageHook from 'components/common/hooks/useGetUsage'; import ModalController from 'components/modal_controller'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {Preferences} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import useShowAdminLimitReached from './useShowAdminLimitReached'; function TestComponent() { useShowAdminLimitReached(); return null; } // state in which modal will be opened. const openModalState = { entities: { general: { license: TestHelper.getLicenseMock({ Cloud: 'true', }), }, users: { currentUserId: 'admin', profiles: { admin: TestHelper.getUserMock({ id: 'admin', roles: 'system_admin', }), }, }, cloud: { limits: { limits: { messages: { history: 10000, }, }, limitsLoaded: true, }, }, usage: { messages: { history: 10001, historyLoaded: true, }, files: { totalStorageLoaded: true, }, boards: { cardsLoaded: true, }, integrations: { enabledLoaded: true, }, teams: { teamsLoaded: true, }, }, preferences: { myPreferences: TestHelper.getPreferencesMock( [ { category: Preferences.CATEGORY_CLOUD_LIMITS, name: Preferences.SHOWN_LIMITS_REACHED_ON_LOGIN, value: 'false', }, ], 'admin', ), }, }, views: { admin: { needsLoggedInLimitReachedCheck: true, }, modals: { modalState: { }, showLaunchingWorkspace: false, }, }, }; const modalRegex = /message history.*no longer available.*Upgrade to a paid plan and get unlimited access to your message history/; jest.mock('react-dom', () => ({ ...jest.requireActual('react-dom') as typeof import('react-dom'), createPortal: (node: React.ReactNode) => node as ReactPortal, })); describe('useShowAdminLimitReached', () => { it('opens cloud usage modal if admin has just logged in on a cloud instance, the instance has exceeded its message history limit, and the admin has not been shown the modal on log in before.', () => { const state = JSON.parse(JSON.stringify(openModalState)); renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); screen.getByText(modalRegex); }); it('does not open cloud usage modal if admin has already been shown the modal', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.entities.preferences.myPreferences = TestHelper.getPreferencesMock( [ { category: Preferences.CATEGORY_CLOUD_LIMITS, name: Preferences.SHOWN_LIMITS_REACHED_ON_LOGIN, value: 'true', }, ], 'admin', ); renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); it('does not open cloud usage modal if workspace has not exceeded limit', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.entities.usage.messages.history = 10000; renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); it('does not open cloud usage modal if there is no message limit', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.entities.cloud.limits = {}; renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); it('does not open cloud usage modal if there is no message limit', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.entities.cloud.limits = {}; renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); it('does not open cloud usage modal if admin was already logged in', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.views.admin.needsLoggedInLimitReachedCheck = false; renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); it('does not open cloud usage modal if limits are not yet loaded', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.entities.cloud.limits.limitsLoaded = false; jest.spyOn(useGetLimitsHook, 'default').mockImplementation(() => ([ state.entities.cloud.limits.limits, false, ])); renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); it('does not open cloud usage modal if usage is not yet loaded', () => { const state = JSON.parse(JSON.stringify(openModalState)); state.entities.usage.messages = { history: 0, historyLoaded: false, }; jest.spyOn(useGetUsageHook, 'default').mockImplementation(() => state.entities.usage); renderWithContext( <> <div id='root-portal'/> <ModalController/> <TestComponent/> </>, state, ); expect(screen.queryByText(modalRegex)).not.toBeInTheDocument(); }); });
1,978
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/confirm_modal_redux/confirm_modal_redux.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Modal} from 'react-bootstrap'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import ConfirmModalRedux from './confirm_modal_redux'; describe('ConfirmModalRedux', () => { const baseProps = { onExited: jest.fn(), }; // These tests will time out when failing, so we override the timeout period to make them fail faster. test('should call closeModal after confirming', (done) => { baseProps.onExited.mockImplementation(() => done()); const wrapper = mountWithIntl( <ConfirmModalRedux {...baseProps} />, ); expect(wrapper.find(Modal).prop('show')).toBe(true); expect(baseProps.onExited).not.toHaveBeenCalled(); wrapper.find('#confirmModalButton').simulate('click'); expect(wrapper.find(Modal).prop('show')).toBe(false); }, 5000); test('should call onExited after cancelling', (done) => { baseProps.onExited.mockImplementation(() => done()); const wrapper = mountWithIntl( <ConfirmModalRedux {...baseProps} />, ); expect(wrapper.find(Modal).prop('show')).toBe(true); expect(baseProps.onExited).not.toHaveBeenCalled(); wrapper.find('#cancelModalButton').simulate('click'); expect(wrapper.find(Modal).prop('show')).toBe(false); }, 5000); });
1,984
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/convert_gm_to_channel_modal/convert_gm_to_channel_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {fireEvent, waitFor} from '@testing-library/react'; import nock from 'nock'; import React from 'react'; import {act} from 'react-dom/test-utils'; import type {Channel} from '@mattermost/types/channels'; import type {Team} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import type {DeepPartial} from '@mattermost/types/utilities'; import {Client4} from 'mattermost-redux/client'; import {Preferences} from 'mattermost-redux/constants'; import ConvertGmToChannelModal from 'components/convert_gm_to_channel_modal/convert_gm_to_channel_modal'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import type {GlobalState} from 'types/store'; describe('component/ConvertGmToChannelModal', () => { const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const baseProps = { onExited: jest.fn(), channel: {id: 'channel_id_1', type: 'G'} as Channel, actions: { closeModal: jest.fn(), convertGroupMessageToPrivateChannel: jest.fn(), moveChannelsInSidebar: jest.fn(), }, profilesInChannel: [user1, user2, user3] as UserProfile[], teammateNameDisplaySetting: Preferences.DISPLAY_PREFER_FULL_NAME, channelsCategoryId: 'sidebar_category_1', currentUserId: user1.id, }; const baseState: DeepPartial<GlobalState> = { entities: { teams: { teams: { team_id_1: {id: 'team_id_1', display_name: 'Team 1', name: 'team_1'} as Team, team_id_2: {id: 'team_id_2', display_name: 'Team 2', name: 'team_2'} as Team, }, currentTeamId: 'team_id_1', }, }, }; test('members part of multiple common teams', async () => { TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). get('/channels/channel_id_1/common_teams'). reply(200, [ {id: 'team_id_1', display_name: 'Team 1', name: 'team_1'}, {id: 'team_id_2', display_name: 'Team 2', name: 'team_2'}, ]); renderWithContext( <ConvertGmToChannelModal {...baseProps}/>, baseState, ); // we need to use waitFor for first assertion as we have a minimum 1200 ms loading animation in the dialog // before it's content is rendered. await waitFor( () => expect(screen.queryByText('Conversation history will be visible to any channel members')).toBeInTheDocument(), {timeout: 1500}, ); expect(screen.queryByText('Select Team')).toBeInTheDocument(); expect(screen.queryByPlaceholderText('Channel name')).toBeInTheDocument(); expect(screen.queryByText('Edit')).toBeInTheDocument(); expect(screen.queryByText('URL: http://localhost:8065/team_1/channels/')).toBeInTheDocument(); }); test('members part of single common teams', async () => { TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). get('/channels/channel_id_1/common_teams'). reply(200, [ {id: 'team_id_1', display_name: 'Team 1', name: 'team_1'}, ]); renderWithContext( <ConvertGmToChannelModal {...baseProps}/>, baseState, ); // we need to use waitFor for first assertion as we have a minimum 1200 ms loading animation in the dialog // before it's content is rendered. await waitFor( () => expect(screen.queryByText('Conversation history will be visible to any channel members')).toBeInTheDocument(), {timeout: 1500}, ); expect(screen.queryByText('Select Team')).not.toBeInTheDocument(); expect(screen.queryByPlaceholderText('Channel name')).toBeInTheDocument(); expect(screen.queryByText('Edit')).toBeInTheDocument(); }); test('members part of no common teams', async () => { TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). get('/channels/channel_id_1/common_teams'). reply(200, []); renderWithContext( <ConvertGmToChannelModal {...baseProps}/>, baseState, ); // we need to use waitFor for first assertion as we have a minimum 1200 ms loading animation in the dialog // before it's content is rendered. await waitFor( () => expect(screen.queryByText('Unable to convert to a channel because group members are part of different teams')).toBeInTheDocument(), {timeout: 1500}, ); expect(screen.queryByText('Select Team')).not.toBeInTheDocument(); expect(screen.queryByPlaceholderText('Channel name')).not.toBeInTheDocument(); expect(screen.queryByText('Edit')).not.toBeInTheDocument(); }); test('multiple common teams - trying conversion', async () => { TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). get('/channels/channel_id_1/common_teams'). reply(200, [ {id: 'team_id_1', display_name: 'Team 1', name: 'team_1'}, {id: 'team_id_2', display_name: 'Team 2', name: 'team_2'}, ]); baseProps.actions.convertGroupMessageToPrivateChannel.mockResolvedValueOnce({}); renderWithContext( <ConvertGmToChannelModal {...baseProps}/>, baseState, ); // we need to use waitFor for first assertion as we have a minimum 1200 ms loading animation in the dialog // before it's content is rendered. await waitFor( () => expect(screen.queryByText('Conversation history will be visible to any channel members')).toBeInTheDocument(), {timeout: 1500}, ); const teamDropdown = screen.queryByText('Select Team'); expect(teamDropdown).not.toBeNull(); fireEvent( teamDropdown!, new MouseEvent('mousedown', { bubbles: true, cancelable: true, }), ); const team1Option = screen.queryByText('Team 1'); expect(team1Option).toBeInTheDocument(); fireEvent.click(team1Option!); const channelNameInput = screen.queryByPlaceholderText('Channel name'); expect(channelNameInput).toBeInTheDocument(); fireEvent.change(channelNameInput!, {target: {value: 'Channel name set by me'}}); const confirmButton = screen.queryByText('Convert to private channel'); expect(channelNameInput).toBeInTheDocument(); await act(async () => { fireEvent.click(confirmButton!); }); }); test('duplicate channel names should npt be allowed', async () => { TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). get('/channels/channel_id_1/common_teams'). reply(200, [ {id: 'team_id_1', display_name: 'Team 1', name: 'team_1'}, ]); baseProps.actions.convertGroupMessageToPrivateChannel.mockResolvedValueOnce({ error: { server_error_id: 'store.sql_channel.save_channel.exists.app_error', }, }); renderWithContext( <ConvertGmToChannelModal {...baseProps}/>, baseState, ); await waitFor( () => expect(screen.queryByText('Conversation history will be visible to any channel members')).toBeInTheDocument(), {timeout: 1500}, ); const channelNameInput = screen.queryByPlaceholderText('Channel name'); expect(channelNameInput).toBeInTheDocument(); fireEvent.change(channelNameInput!, {target: {value: 'Channel'}}); const confirmButton = screen.queryByText('Convert to private channel'); expect(channelNameInput).toBeInTheDocument(); await act(async () => { fireEvent.click(confirmButton!); }); expect(screen.queryByText('A channel with that URL already exists')).toBeInTheDocument(); }); });
1,991
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/copy_url_context_menu/copy_url_context_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 CopyUrlContextMenu from 'components/copy_url_context_menu/copy_url_context_menu'; describe('components/CopyUrlContextMenu', () => { test('should copy relative url on click', () => { const props = { siteURL: 'http://example.com', link: '/path/to/resource', menuId: 'resource', actions: { copyToClipboard: jest.fn(), }, }; const wrapper = shallow( <CopyUrlContextMenu {...props}> <span>{'Click'}</span> </CopyUrlContextMenu>, ); expect(wrapper).toMatchSnapshot(); wrapper.find('MenuItem').simulate('click'); expect(props.actions.copyToClipboard).toBeCalledWith('http://example.com/path/to/resource'); }); test('should copy absolute url on click', () => { const props = { siteURL: 'http://example.com', link: 'http://site.example.com/path/to/resource', menuId: 'resource', actions: { copyToClipboard: jest.fn(), }, }; const wrapper = shallow( <CopyUrlContextMenu {...props}> <span>{'Click'}</span> </CopyUrlContextMenu>, ); expect(wrapper).toMatchSnapshot(); wrapper.find('MenuItem').simulate('click'); expect(props.actions.copyToClipboard).toBeCalledWith('http://site.example.com/path/to/resource'); }); });
1,994
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/copy_url_context_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/copy_url_context_menu/__snapshots__/copy_url_context_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/CopyUrlContextMenu should copy absolute url on click 1`] = ` <span> <ContextMenu className="" data={Object {}} hideOnLeave={false} id="copy-url-context-menuresource" onHide={[Function]} onMouseLeave={[Function]} onShow={[Function]} preventHideOnContextMenu={false} preventHideOnResize={false} preventHideOnScroll={false} rtl={false} style={Object {}} > <MenuItem attributes={Object {}} className="" data={Object {}} disabled={false} divider={false} onClick={[Function]} onMouseLeave={[Function]} onMouseMove={[Function]} preventClose={false} selected={false} > <MemoizedFormattedMessage defaultMessage="Copy Link" id="copy_url_context_menu.getChannelLink" /> </MenuItem> </ContextMenu> <ContextMenuTrigger attributes={Object {}} collect={[Function]} disable={false} disableIfShiftIsPressed={false} holdToDisplay={-1} id="copy-url-context-menuresource" mouseButton={2} posX={0} posY={0} renderTag="div" > <span> Click </span> </ContextMenuTrigger> </span> `; exports[`components/CopyUrlContextMenu should copy relative url on click 1`] = ` <span> <ContextMenu className="" data={Object {}} hideOnLeave={false} id="copy-url-context-menuresource" onHide={[Function]} onMouseLeave={[Function]} onShow={[Function]} preventHideOnContextMenu={false} preventHideOnResize={false} preventHideOnScroll={false} rtl={false} style={Object {}} > <MenuItem attributes={Object {}} className="" data={Object {}} disabled={false} divider={false} onClick={[Function]} onMouseLeave={[Function]} onMouseMove={[Function]} preventClose={false} selected={false} > <MemoizedFormattedMessage defaultMessage="Copy Link" id="copy_url_context_menu.getChannelLink" /> </MenuItem> </ContextMenu> <ContextMenuTrigger attributes={Object {}} collect={[Function]} disable={false} disableIfShiftIsPressed={false} holdToDisplay={-1} id="copy-url-context-menuresource" mouseButton={2} posX={0} posY={0} renderTag="div" > <span> Click </span> </ContextMenuTrigger> </span> `;
1,995
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/create_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 {FormattedMessage} from 'react-intl'; import CreateTeam from './create_team'; describe('component/create_team', () => { const baseProps = { currentChannel: {}, currentTeam: {}, customDescriptionText: '', match: { url: '', }, siteName: '', isCloud: false, isFreeTrial: false, usageDeltas: { teams: { active: -1, }, }, history: jest.fn(), location: jest.fn(), } as any; test('should match snapshot default', () => { const wrapper = shallow( <CreateTeam {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should show title and message when cloud and team limit reached', () => { const props = { ...baseProps, isCloud: true, isFreeTrial: false, usageDeltas: { teams: { active: 0, }, }, }; const wrapper = shallow( <CreateTeam {...props}/>, ); expect(wrapper.contains( <FormattedMessage id='create_team.createTeamRestricted.title' tagName='strong' defaultMessage='Professional feature' />, )).toEqual(true); expect(wrapper.contains( <FormattedMessage id='create_team.createTeamRestricted.message' defaultMessage='Your workspace plan has reached the limit on the number of teams. Create unlimited teams with a free 30-day trial. Contact your System Administrator.' />, )).toEqual(true); }); });
1,998
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/__snapshots__/create_team.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/create_team should match snapshot default 1`] = ` <div> <Connect(Component) /> <BackButton url="/undefined/channels/undefined" /> <div className="col-sm-12" > <div className="signup-team__container" > <Memo(SiteNameAndDescription) customDescriptionText="" siteName="" /> <div className="signup__content" > <Switch> <Route path="/display_name" render={[Function]} /> <Route path="/team_url" render={[Function]} /> <Redirect to="/display_name" /> </Switch> </div> </div> </div> </div> `;
1,999
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components/display_name.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import type {ReactWrapper} from 'enzyme'; import React from 'react'; import {FormattedMessage} from 'react-intl'; import DisplayName from 'components/create_team/components/display_name'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import Constants from 'utils/constants'; import {cleanUpUrlable} from 'utils/url'; jest.mock('images/logo.png', () => 'logo.png'); describe('/components/create_team/components/display_name', () => { const defaultProps = { updateParent: jest.fn(), state: { team: {name: 'test-team', display_name: 'test-team'}, wizard: 'display_name', }, actions: { trackEvent: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow(<DisplayName {...defaultProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should run updateParent function', () => { const wrapper = mountWithIntl(<DisplayName {...defaultProps}/>); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.prop('updateParent')).toHaveBeenCalled(); }); test('should pass state to updateParent function', () => { const wrapper = mountWithIntl(<DisplayName {...defaultProps}/>); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.prop('updateParent')).toHaveBeenCalledWith(defaultProps.state); }); test('should pass updated team name to updateParent function', () => { const wrapper = mountWithIntl(<DisplayName {...defaultProps}/>); const teamDisplayName = 'My Test Team'; const newState = { ...defaultProps.state, team: { ...defaultProps.state.team, display_name: teamDisplayName, name: cleanUpUrlable(teamDisplayName), }, }; (wrapper.find('.form-control') as unknown as ReactWrapper<any, any, HTMLInputElement>).instance().value = teamDisplayName; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.prop('updateParent')).toHaveBeenCalledWith(defaultProps.state); expect(wrapper.prop('updateParent').mock.calls[0][0]).toEqual(newState); }); test('should display isRequired error', () => { const wrapper = mountWithIntl(<DisplayName {...defaultProps}/>); (wrapper.find('.form-control') as unknown as ReactWrapper<any, any, HTMLInputElement>).instance().value = ''; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.state('nameError')).toEqual( <FormattedMessage id='create_team.display_name.required' defaultMessage='This field is required' />, ); }); test('should display isRequired error for null team in props', () => { const nullTeamProps = { updateParent: jest.fn(), state: { wizard: 'display_name', }, actions: { trackEvent: jest.fn(), }, }; const wrapper = mountWithIntl(<DisplayName {...nullTeamProps}/>); (wrapper.find('.form-control') as unknown as ReactWrapper<any, any, HTMLInputElement>).instance().value = ''; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.state('nameError')).toEqual( <FormattedMessage id='create_team.display_name.required' defaultMessage='This field is required' />, ); }); test('should display isRequired error for empty team in props', () => { const nullTeamProps = { updateParent: jest.fn(), state: { team: {}, wizard: 'display_name', }, actions: { trackEvent: jest.fn(), }, }; const wrapper = mountWithIntl(<DisplayName {...nullTeamProps}/>); (wrapper.find('.form-control') as unknown as ReactWrapper<any, any, HTMLInputElement>).instance().value = ''; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.state('nameError')).toEqual( <FormattedMessage id='create_team.display_name.required' defaultMessage='This field is required' />, ); }); test('should display charLength error', () => { const wrapper = mountWithIntl(<DisplayName {...defaultProps}/>); const input = (wrapper.find('.form-control') as unknown as ReactWrapper<any, any, HTMLInputElement>).instance(); input.value = 'a'.repeat(Constants.MAX_TEAMNAME_LENGTH + 1); wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.state('nameError')).toEqual( <FormattedMessage id='create_team.display_name.charLength' defaultMessage='Name must be {min} or more characters up to a maximum of {max}. You can add a longer team description later.' values={{ min: Constants.MIN_TEAMNAME_LENGTH, max: Constants.MAX_TEAMNAME_LENGTH, }} />, ); }); });
2,001
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components/__snapshots__/display_name.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/create_team/components/display_name should match snapshot 1`] = ` <div> <form> <img alt="signup logo" className="signup-team-logo" src="logo.png" /> <h5> <MemoizedFormattedMessage defaultMessage="Team Name" id="create_team.display_name.teamName" tagName="strong" /> </h5> <div className="form-group" > <div className="row" > <div className="col-sm-9" > <input autoFocus={true} className="form-control" id="teamNameInput" maxLength={128} onChange={[Function]} onFocus={[Function]} placeholder="" spellCheck="false" type="text" value="test-team" /> </div> </div> </div> <div> <MemoizedFormattedMessage defaultMessage="Name your team in any language. Your team name shows in menus and headings." id="create_team.display_name.nameHelp" /> </div> <button className="btn btn-primary mt-8" id="teamNameNextButton" onClick={[Function]} type="submit" > <MemoizedFormattedMessage defaultMessage="Next" id="create_team.display_name.next" /> <i className="icon icon-chevron-right" /> </button> </form> </div> `;
2,003
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components/team_url/team_url.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 {Button} from 'react-bootstrap'; import {FormattedMessage} from 'react-intl'; import {Provider} from 'react-redux'; import TeamUrl from 'components/create_team/components/team_url/team_url'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import Constants from 'utils/constants'; jest.mock('images/logo.png', () => 'logo.png'); describe('/components/create_team/components/display_name', () => { const defaultProps = { updateParent: jest.fn(), state: { team: {name: 'test-team', display_name: 'test-team'}, wizard: 'display_name', }, actions: { checkIfTeamExists: jest.fn().mockResolvedValue({data: true}), createTeam: jest.fn().mockResolvedValue({data: {name: 'test-team'}}), trackEvent: jest.fn(), }, history: {push: jest.fn()}, }; const chatLengthError = ( <FormattedMessage id='create_team.team_url.charLength' defaultMessage='Name must be {min} or more characters up to a maximum of {max}' values={{ min: Constants.MIN_TEAMNAME_LENGTH, max: Constants.MAX_TEAMNAME_LENGTH, }} /> ); test('should match snapshot', () => { const wrapper = shallow(<TeamUrl {...defaultProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should return to display_name.jsx page', () => { const wrapper = mountWithIntl(<TeamUrl {...defaultProps}/>); wrapper.find('a').simulate('click', { preventDefault: () => jest.fn(), }); expect(wrapper.prop('state').wizard).toBe('display_name'); expect(wrapper.prop('updateParent')).toHaveBeenCalled(); }); test('should successfully submit', async () => { const checkIfTeamExists = jest.fn(). mockResolvedValueOnce({data: true}). mockResolvedValue({data: false}); const actions = {...defaultProps.actions, checkIfTeamExists}; const props = {...defaultProps, actions}; const wrapper = mountWithIntl( <TeamUrl {...props}/>, ); await (wrapper.instance() as unknown as TeamUrl).submitNext({preventDefault: jest.fn()} as unknown as React.MouseEvent<Button, MouseEvent>); expect(actions.checkIfTeamExists).toHaveBeenCalledTimes(1); expect(actions.createTeam).not.toHaveBeenCalled(); await (wrapper.instance() as unknown as TeamUrl).submitNext({preventDefault: jest.fn()} as unknown as React.MouseEvent<Button, MouseEvent>); expect(actions.checkIfTeamExists).toHaveBeenCalledTimes(2); expect(actions.createTeam).toHaveBeenCalledTimes(1); expect(actions.createTeam).toBeCalledWith({display_name: 'test-team', name: 'test-team', type: 'O'}); expect(props.history.push).toHaveBeenCalledTimes(1); expect(props.history.push).toBeCalledWith('/test-team/channels/town-square'); }); test('should display isRequired error', () => { const wrapper = mountWithIntl(<TeamUrl {...defaultProps}/>); (wrapper.find('.form-control').instance() as unknown as HTMLInputElement).value = ''; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', {preventDefault: () => jest.fn()}); expect(wrapper.state('nameError')).toEqual( <FormattedMessage id='create_team.team_url.required' defaultMessage='This field is required' />, ); }); test('should display charLength error', () => { const wrapper = mountWithIntl(<TeamUrl {...defaultProps}/>); (wrapper.find('.form-control').instance() as unknown as HTMLInputElement).value = 'a'; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', {preventDefault: () => jest.fn()}); expect(wrapper.state('nameError')).toEqual(chatLengthError); (wrapper.find('.form-control').instance() as unknown as HTMLInputElement).value = 'a'.repeat(Constants.MAX_TEAMNAME_LENGTH + 1); wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', {preventDefault: () => jest.fn()}); expect(wrapper.state('nameError')).toEqual(chatLengthError); }); test('should display teamUrl regex error', () => { const wrapper = mountWithIntl(<TeamUrl {...defaultProps}/>); (wrapper.find('.form-control').instance() as unknown as HTMLInputElement).value = '!!wrongName1'; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', {preventDefault: () => jest.fn()}); expect(wrapper.state('nameError')).toEqual( <FormattedMessage id='create_team.team_url.regex' defaultMessage="Use only lower case letters, numbers and dashes. Must start with a letter and can't end in a dash." />, ); }); test('should display teamUrl taken error', () => { const store = mockStore({ entities: { general: { config: {}, license: { Cloud: 'false', }, }, users: { currentUserId: 'currentUserId', }, }, }); const wrapper = mountWithIntl(<Provider store={store}><TeamUrl {...defaultProps}/></Provider>); (wrapper.find('.form-control').instance() as unknown as HTMLInputElement).value = 'channel'; wrapper.find('.form-control').simulate('change'); wrapper.find('button').simulate('click', {preventDefault: () => jest.fn()}); expect((wrapper as any).find(TeamUrl).state('nameError').props.id).toEqual('create_team.team_url.taken'); }); });
2,005
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components/team_url
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_team/components/team_url/__snapshots__/team_url.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`/components/create_team/components/display_name should match snapshot 1`] = ` <div> <form> <img alt="signup team logo" className="signup-team-logo" src="logo.png" /> <h5> <MemoizedFormattedMessage defaultMessage="Team URL" id="create_team.team_url.teamUrl" tagName="strong" /> </h5> <div className="form-group" > <div className="row" > <div className="col-sm-11" > <div className="input-group input-group--limit" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="urlTooltip" > http://localhost:8065/ </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <span className="input-group-addon" > http://localhost:8065/ </span> </OverlayTrigger> <input autoFocus={true} className="form-control" id="teamURLInput" maxLength={128} onChange={[Function]} onFocus={[Function]} placeholder="" spellCheck="false" type="text" value="test-team" /> </div> </div> </div> </div> <p> <MemoizedFormattedMessage defaultMessage="Choose the web address of your new team:" id="create_team.team_url.webAddress" /> </p> <ul className="color--light" > <li> <MemoizedFormattedMessage defaultMessage="Short and memorable is best" id="create_team.team_url.hint1" /> </li> <li> <MemoizedFormattedMessage defaultMessage="Use lowercase letters, numbers and dashes" id="create_team.team_url.hint2" /> </li> <li> <MemoizedFormattedMessage defaultMessage="Must start with a letter and can't end in a dash" id="create_team.team_url.hint3" /> </li> </ul> <div className="mt-8" > <Button active={false} block={false} bsClass="btn" bsStyle="primary" disabled={false} id="teamURLFinishButton" onClick={[Function]} type="submit" > <MemoizedFormattedMessage defaultMessage="Finish" id="create_team.team_url.finish" /> </Button> </div> <div className="mt-8" > <a href="#" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Back to previous step" id="create_team.team_url.back" /> </a> </div> </form> </div> `;
2,007
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_user_groups_modal/create_user_groups_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {UserProfile} from '@mattermost/types/users'; import type {Value} from 'components/multiselect/multiselect'; import CreateUserGroupsModal from './create_user_groups_modal'; type UserProfileValue = Value & UserProfile; describe('component/create_user_groups_modal', () => { const users = [{ id: 'user-1', label: 'user-1', value: 'user-1', delete_at: 0, } as UserProfileValue, { id: 'user-2', label: 'user-2', value: 'user-2', delete_at: 0, } as UserProfileValue]; const baseProps = { onExited: jest.fn(), backButtonCallback: jest.fn(), actions: { openModal: jest.fn(), createGroupWithUserIds: jest.fn().mockImplementation(() => Promise.resolve()), }, }; test('should match snapshot with back button', () => { const wrapper = shallow( <CreateUserGroupsModal {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot without back button', () => { const wrapper = shallow( <CreateUserGroupsModal {...baseProps} backButtonCallback={undefined} />, ); expect(wrapper).toMatchSnapshot(); }); test('should create group', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: 'Ursa', mention: 'ursa', usersToAdd: users}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual(''); }); }); test('mention regex error', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: 'Ursa', mention: 'ursa!/'}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(0); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('Invalid character in mention.'); }); }); test('create a mention with special characters', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: 'Ursa', mention: 'ursa.-_'}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual(''); }); }); test('fail to create with empty name', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: '', mention: 'ursa'}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(0); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('nameInputErrorText')).toEqual('Name is a required field.'); }); }); test('fail to create with empty mention', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: 'Ursa', mention: ''}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(0); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('Mention is a required field.'); }); }); test('should create when mention begins with @', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: 'Ursa', mention: '@ursa', usersToAdd: users}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual(''); expect(wrapper.state('nameInputErrorText')).toEqual(''); }); }); test('should fail to create with unknown error', () => { const createGroupWithUserIds = jest.fn().mockImplementation(() => Promise.resolve({error: {message: 'test error', server_error_id: 'insert_error'}})); const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} actions={{ ...baseProps.actions, createGroupWithUserIds, }} />, ); wrapper.setState({name: 'Ursa', mention: '@ursa', usersToAdd: users}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(true); expect(wrapper.state('mentionInputErrorText')).toEqual(''); expect(wrapper.state('nameInputErrorText')).toEqual(''); }); }); test('should fail to create with duplicate mention error', () => { const createGroupWithUserIds = jest.fn().mockImplementation(() => Promise.resolve({error: {message: 'test error', server_error_id: 'app.custom_group.unique_name'}})); const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} actions={{ ...baseProps.actions, createGroupWithUserIds, }} />, ); wrapper.setState({name: 'Ursa', mention: '@ursa', usersToAdd: users}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('Mention needs to be unique.'); expect(wrapper.state('nameInputErrorText')).toEqual(''); }); }); test('fail to create with reserved word for mention', () => { const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} />, ); wrapper.setState({name: 'Ursa', mention: 'all'}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(0); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('Mention contains a reserved word.'); }); wrapper.setState({name: 'Ursa', mention: 'here'}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(0); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('Mention contains a reserved word.'); }); wrapper.setState({name: 'Ursa', mention: 'channel'}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(0); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('Mention contains a reserved word.'); }); }); test('should fail to create with duplicate mention error', () => { const createGroupWithUserIds = jest.fn().mockImplementation(() => Promise.resolve({error: {message: 'test error', server_error_id: 'app.group.username_conflict'}})); const wrapper = shallow<CreateUserGroupsModal>( <CreateUserGroupsModal {...baseProps} actions={{ ...baseProps.actions, createGroupWithUserIds, }} />, ); wrapper.setState({name: 'Ursa', mention: '@ursa', usersToAdd: users}); wrapper.instance().createGroup(users); expect(wrapper.instance().props.actions.createGroupWithUserIds).toHaveBeenCalledTimes(1); process.nextTick(() => { expect(wrapper.state('showUnknownError')).toEqual(false); expect(wrapper.state('mentionInputErrorText')).toEqual('A username already exists with this name. Mention must be unique.'); expect(wrapper.state('nameInputErrorText')).toEqual(''); }); }); });
2,010
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_user_groups_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/create_user_groups_modal/__snapshots__/create_user_groups_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`component/create_user_groups_modal should match snapshot with back button 1`] = ` <Modal animation={true} aria-labelledby="createUserGroupsModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal user-groups-modal-create" dialogComponentClass={[Function]} enforceFocus={true} id="createUserGroupsModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <button aria-label="Back" className="modal-header-back-button btn btn-icon" onClick={[Function]} type="button" > <LocalizedIcon ariaLabel={ Object { "defaultMessage": "Back", "id": "user_groups_modal.goBackLabel", } } className="icon icon-arrow-left" /> </button> <ModalTitle bsClass="modal-title" componentClass="h1" id="createGroupsModalTitleWithBack" > <MemoizedFormattedMessage defaultMessage="Create Group" id="user_groups_modal.createTitle" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="user-groups-modal__content" > <div className="group-name-input-wrapper" > <ForwardRef autoFocus={true} customMessage={ Object { "type": "error", "value": "", } } data-testid="nameInput" maxLength={64} onChange={[Function]} placeholder="Name" type="text" value="" /> </div> <div className="group-mention-input-wrapper" > <ForwardRef customMessage={ Object { "type": "error", "value": "", } } data-testid="mentionInput" maxLength={64} onChange={[Function]} placeholder="Mention" type="text" value="" /> </div> <h2> <MemoizedFormattedMessage defaultMessage="Add People" id="user_groups_modal.addPeople" /> </h2> <div className="group-add-user" > <Connect(AddUserToGroupMultiSelect) addUserCallback={[Function]} backButtonClass="multiselect-back" backButtonClick={[Function]} backButtonText="Cancel" deleteUserCallback={[Function]} focusOnLoad={false} multilSelectKey="addUsersToGroupKey" onSubmitCallback={[Function]} saving={false} savingEnabled={false} /> </div> </div> </ModalBody> </Modal> `; exports[`component/create_user_groups_modal should match snapshot without back button 1`] = ` <Modal animation={true} aria-labelledby="createUserGroupsModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal user-groups-modal-create" dialogComponentClass={[Function]} enforceFocus={true} id="createUserGroupsModal" keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="createGroupsModalTitle" > <MemoizedFormattedMessage defaultMessage="Create Group" id="user_groups_modal.createTitle" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="user-groups-modal__content" > <div className="group-name-input-wrapper" > <ForwardRef autoFocus={true} customMessage={ Object { "type": "error", "value": "", } } data-testid="nameInput" maxLength={64} onChange={[Function]} placeholder="Name" type="text" value="" /> </div> <div className="group-mention-input-wrapper" > <ForwardRef customMessage={ Object { "type": "error", "value": "", } } data-testid="mentionInput" maxLength={64} onChange={[Function]} placeholder="Mention" type="text" value="" /> </div> <h2> <MemoizedFormattedMessage defaultMessage="Add People" id="user_groups_modal.addPeople" /> </h2> <div className="group-add-user" > <Connect(AddUserToGroupMultiSelect) addUserCallback={[Function]} backButtonClass="multiselect-back" backButtonClick={[Function]} backButtonText="Cancel" deleteUserCallback={[Function]} focusOnLoad={false} multilSelectKey="addUsersToGroupKey" onSubmitCallback={[Function]} saving={false} savingEnabled={false} /> </div> </div> </ModalBody> </Modal> `;
2,014
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/custom_status_emoji.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import * as CustomStatusSelectors from 'selectors/views/custom_status'; import mockStore from 'tests/test_store'; import CustomStatusEmoji from './custom_status_emoji'; jest.mock('mattermost-redux/selectors/entities/timezone'); jest.mock('selectors/views/custom_status'); describe('components/custom_status/custom_status_emoji', () => { const store = mockStore({}); const getCustomStatus = () => { return null; }; (CustomStatusSelectors.makeGetCustomStatus as jest.Mock).mockReturnValue(getCustomStatus); (CustomStatusSelectors.isCustomStatusEnabled as any as jest.Mock).mockReturnValue(true); it('should match snapshot', () => { const wrapper = mount(<CustomStatusEmoji/>, {wrappingComponent: Provider, wrappingComponentProps: {store}}); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot with props', () => { const wrapper = mount( <CustomStatusEmoji emojiSize={34} showTooltip={true} tooltipDirection='bottom' />, {wrappingComponent: Provider, wrappingComponentProps: {store}}, ); expect(wrapper).toMatchSnapshot(); }); it('should not render when EnableCustomStatus in config is false', () => { (CustomStatusSelectors.isCustomStatusEnabled as any as jest.Mock).mockReturnValue(false); const wrapper = mount(<CustomStatusEmoji/>, {wrappingComponent: Provider, wrappingComponentProps: {store}}); expect(wrapper.isEmptyRender()).toBeTruthy(); }); it('should not render when custom status is expired', () => { (CustomStatusSelectors.isCustomStatusEnabled as any as jest.Mock).mockReturnValue(true); (CustomStatusSelectors.isCustomStatusExpired as jest.Mock).mockReturnValue(true); const wrapper = mount(<CustomStatusEmoji/>, {wrappingComponent: Provider, wrappingComponentProps: {store}}); expect(wrapper.isEmptyRender()).toBeTruthy(); }); });
2,016
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/custom_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 {Provider} from 'react-redux'; import * as StatusSelectors from 'selectors/views/custom_status'; import mockStore from 'tests/test_store'; import CustomStatusModal from './custom_status_modal'; jest.mock('selectors/views/custom_status'); describe('components/custom_status/custom_status_modal', () => { const store = mockStore({}); const baseProps = { onExited: jest.fn(), }; it('should match snapshot', () => { const wrapper = shallow( <Provider store={store}> <CustomStatusModal {...baseProps}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot when user has custom status set', () => { const customStatus = { emoji: 'speech_balloon', text: 'speaking', }; (StatusSelectors.makeGetCustomStatus as jest.Mock).mockReturnValue(() => customStatus); const wrapper = shallow( <Provider store={store}> <CustomStatusModal {...baseProps}/> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); });
2,018
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/custom_status_suggestion.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {CustomStatusDuration} from '@mattermost/types/users'; import CustomStatusSuggestion from './custom_status_suggestion'; describe('components/custom_status/custom_status_emoji', () => { const baseProps = { handleSuggestionClick: jest.fn(), status: { emoji: '', text: '', duration: CustomStatusDuration.DONT_CLEAR, }, handleClear: jest.fn(), }; it('should match snapshot', () => { const wrapper = shallow( <CustomStatusSuggestion {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot with duration', () => { const props = { ...baseProps, status: { ...baseProps.status, duration: CustomStatusDuration.TODAY, }, }; const wrapper = shallow( <CustomStatusSuggestion {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); it('should call handleSuggestionClick when click occurs on div', () => { const wrapper = shallow( <CustomStatusSuggestion {...baseProps}/>, ); wrapper.find('.statusSuggestion__row').simulate('click'); expect(baseProps.handleSuggestionClick).toBeCalledTimes(1); }); it('should render clearButton when hover occurs on div', () => { const wrapper = shallow( <CustomStatusSuggestion {...baseProps}/>, ); expect(wrapper.find('.suggestion-clear').exists()).toBeFalsy(); wrapper.find('.statusSuggestion__row').simulate('mouseEnter'); expect(wrapper.find('.suggestion-clear').exists()).toBeTruthy(); }); });
2,020
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/custom_status_text.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import {Provider} from 'react-redux'; import * as CustomStatusSelectors from 'selectors/views/custom_status'; import mockStore from 'tests/test_store'; import CustomStatusText from './custom_status_text'; jest.mock('selectors/views/custom_status'); describe('components/custom_status/custom_status_text', () => { const store = mockStore({}); it('should match snapshot', () => { const wrapper = mount(<CustomStatusText/>, {wrappingComponent: Provider, wrappingComponentProps: {store}}); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot with props', () => { const wrapper = mount( <CustomStatusText tooltipDirection='top' text='In a meeting' />, {wrappingComponent: Provider, wrappingComponentProps: {store}}, ); expect(wrapper).toMatchSnapshot(); }); it('should not render when EnableCustomStatus in config is false', () => { (CustomStatusSelectors.isCustomStatusEnabled as any as jest.Mock).mockReturnValue(false); const wrapper = mount(<CustomStatusText/>, {wrappingComponent: Provider, wrappingComponentProps: {store}}); expect(wrapper.isEmptyRender()).toBeTruthy(); }); });
2,022
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/date_time_input.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import moment from 'moment-timezone'; import React from 'react'; import {Provider} from 'react-redux'; import {General} from 'mattermost-redux/constants'; import * as i18Selectors from 'selectors/i18n'; import mockStore from 'tests/test_store'; import DateTimeInput from './date_time_input'; jest.mock('selectors/i18n'); describe('components/custom_status/date_time_input', () => { const store = mockStore({}); (i18Selectors.getCurrentLocale as jest.Mock).mockReturnValue(General.DEFAULT_LOCALE); const baseProps = { time: moment('2021-05-03T14:53:39.127Z'), handleChange: jest.fn(), timezone: 'Australia/Sydney', }; it('should match snapshot', () => { const wrapper = shallow( <Provider store={store}> <DateTimeInput {...baseProps}/> </Provider>, ); expect(wrapper.dive()).toMatchSnapshot(); }); });
2,024
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/expiry_menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {CustomStatusDuration} from '@mattermost/types/users'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import ExpiryMenu from './expiry_menu'; describe('components/custom_status/expiry_menu', () => { const baseProps = { duration: CustomStatusDuration.DONT_CLEAR, handleDurationChange: jest.fn(), }; it('should match snapshot', () => { const wrapper = mountWithIntl(<ExpiryMenu {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot with different props', () => { baseProps.duration = CustomStatusDuration.DATE_AND_TIME; const wrapper = mountWithIntl(<ExpiryMenu {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); });
2,027
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/__snapshots__/custom_status_emoji.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/custom_status/custom_status_emoji should match snapshot 1`] = `<CustomStatusEmoji />`; exports[`components/custom_status/custom_status_emoji should match snapshot with props 1`] = ` <CustomStatusEmoji emojiSize={34} showTooltip={true} tooltipDirection="bottom" /> `;
2,028
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/__snapshots__/custom_status_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/custom_status/custom_status_modal should match snapshot 1`] = ` <ContextProvider value={ Object { "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "subscription": Subscription { "handleChangeWrapper": [Function], "listeners": Object { "notify": [Function], }, "onStateChange": [Function], "parentSub": undefined, "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "unsubscribe": null, }, } } > <CustomStatusModal onExited={[MockFunction]} /> </ContextProvider> `; exports[`components/custom_status/custom_status_modal should match snapshot when user has custom status set 1`] = ` <ContextProvider value={ Object { "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "subscription": Subscription { "handleChangeWrapper": [Function], "listeners": Object { "notify": [Function], }, "onStateChange": [Function], "parentSub": undefined, "store": Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], }, "unsubscribe": null, }, } } > <CustomStatusModal onExited={[MockFunction]} /> </ContextProvider> `;
2,029
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/__snapshots__/custom_status_suggestion.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/custom_status/custom_status_emoji should match snapshot 1`] = ` <button className="statusSuggestion__row cursor--pointer" onClick={[Function]} onMouseEnter={[Function]} onMouseLeave={[Function]} tabIndex={0} > <div className="statusSuggestion__icon" > <Memo(RenderEmoji) emojiName="" size={20} /> </div> <CustomStatusText className="statusSuggestion__text" text="" tooltipDirection="top" /> </button> `; exports[`components/custom_status/custom_status_emoji should match snapshot with duration 1`] = ` <button className="statusSuggestion__row cursor--pointer" onClick={[Function]} onMouseEnter={[Function]} onMouseLeave={[Function]} tabIndex={0} > <div className="statusSuggestion__icon" > <Memo(RenderEmoji) emojiName="" size={20} /> </div> <CustomStatusText className="statusSuggestion__text with_duration" text="" tooltipDirection="top" /> <span className="statusSuggestion__duration" > <MemoizedFormattedMessage defaultMessage="Today" id="custom_status.expiry_dropdown.today" /> </span> </button> `;
2,030
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/__snapshots__/custom_status_text.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/custom_status/custom_status_text should match snapshot 1`] = ` <CustomStatusText className="" text="" tooltipDirection="bottom" /> `; exports[`components/custom_status/custom_status_text should match snapshot with props 1`] = ` <CustomStatusText className="" text="In a meeting" tooltipDirection="top" /> `;
2,031
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/__snapshots__/date_time_input.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/custom_status/date_time_input should match snapshot 1`] = ` <DateTimeInputContainer handleChange={[MockFunction]} time={"2021-05-03T14:53:39.127Z"} timezone="Australia/Sydney" /> `;
2,032
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status
petrpan-code/mattermost/mattermost/webapp/channels/src/components/custom_status/__snapshots__/expiry_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/custom_status/expiry_menu should match snapshot 1`] = ` <ExpiryMenu duration="" handleDurationChange={[MockFunction]} > <div className="statusExpiry" > <div className="statusExpiry__content" > <MenuWrapper animationComponent={[Function]} className="statusExpiry__menu" > <div className="MenuWrapper statusExpiry__menu" onClick={[Function]} > <button className="style--none expiry-wrapper expiry-selector" > <FormattedMessage defaultMessage="Clear after" id="custom_status.expiry_dropdown.clear_after" > <span> Clear after </span> </FormattedMessage> : <span className="expiry-value" > Don't clear </span> <span> <i aria-hidden="true" className="fa fa-angle-down" /> </span> </button> <MenuWrapperAnimation show={false} > <CSSTransition classNames="MenuWrapperAnimation" enter={true} exit={true} in={false} mountOnEnter={true} timeout={80} unmountOnExit={true} > <Transition appear={false} enter={true} exit={true} in={false} mountOnEnter={true} onEnter={[Function]} onEntered={[Function]} onEntering={[Function]} onExit={[Function]} onExited={[Function]} onExiting={[Function]} timeout={80} unmountOnExit={true} /> </CSSTransition> </MenuWrapperAnimation> </div> </MenuWrapper> </div> </div> </ExpiryMenu> `; exports[`components/custom_status/expiry_menu should match snapshot with different props 1`] = ` <ExpiryMenu duration="date_and_time" handleDurationChange={[MockFunction]} > <div className="statusExpiry" > <div className="statusExpiry__content" > <MenuWrapper animationComponent={[Function]} className="statusExpiry__menu" > <div className="MenuWrapper statusExpiry__menu" onClick={[Function]} > <button className="style--none expiry-wrapper expiry-selector" > <FormattedMessage defaultMessage="Clear after" id="custom_status.expiry_dropdown.clear_after" > <span> Clear after </span> </FormattedMessage> : <span className="expiry-value" > Custom Date and Time </span> <span> <i aria-hidden="true" className="fa fa-angle-down" /> </span> </button> <MenuWrapperAnimation show={false} > <CSSTransition classNames="MenuWrapperAnimation" enter={true} exit={true} in={false} mountOnEnter={true} timeout={80} unmountOnExit={true} > <Transition appear={false} enter={true} exit={true} in={false} mountOnEnter={true} onEnter={[Function]} onEntered={[Function]} onEntering={[Function]} onExit={[Function]} onExited={[Function]} onExiting={[Function]} timeout={80} unmountOnExit={true} /> </CSSTransition> </MenuWrapperAnimation> </div> </MenuWrapper> </div> </div> </ExpiryMenu> `;
2,033
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/data_prefetch/actions.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel, ChannelMembership} from '@mattermost/types/channels'; import type {RelationOneToOne} from '@mattermost/types/utilities'; import {TestHelper} from 'utils/test_helper'; import {prefetchQueue} from './actions'; describe('DataPrefetchActions', () => { const unreadChannels: Channel[] = []; const channelMemberships: RelationOneToOne<Channel, ChannelMembership> = {}; for (let i = 0; i < 25; i++) { unreadChannels.push(TestHelper.getChannelMock({id: 'channel' + i})); channelMemberships['channel' + i] = TestHelper.getChannelMembershipMock({channel_id: 'channel' + i}); } const mentionChannels: Channel[] = []; for (let i = 25; i < 50; i++) { mentionChannels.push(TestHelper.getChannelMock({id: 'channel' + i})); channelMemberships['channel' + i] = TestHelper.getChannelMembershipMock({channel_id: 'channel' + i, mention_count_root: 1}); } it('prefetchQueue', () => { // Unread channels only expect(prefetchQueue(unreadChannels, channelMemberships, true)).toEqual({1: [], 2: [], 3: []}); const unreadChannels9 = unreadChannels.slice(0, 9); let unreadQueue = prefetchQueue(unreadChannels9, channelMemberships, true); expect(unreadQueue['1'].length).toBe(0); expect(unreadQueue['2'].length).toBe(9); const unreadChannels10 = unreadChannels.slice(0, 10); unreadQueue = prefetchQueue(unreadChannels10, channelMemberships, true); expect(unreadQueue['1'].length).toBe(0); expect(unreadQueue['2'].length).toBe(0); // Mention channels only expect(prefetchQueue(mentionChannels, channelMemberships, true)).toEqual({1: [], 2: [], 3: []}); const mentionChannels9 = mentionChannels.slice(0, 9); let mentionQueue = prefetchQueue(mentionChannels9, channelMemberships, true); expect(mentionQueue['1'].length).toBe(9); expect(unreadQueue['2'].length).toBe(0); const mentionChannels10 = mentionChannels.slice(0, 10); mentionQueue = prefetchQueue(mentionChannels10, channelMemberships, true); expect(mentionQueue['1'].length).toBe(10); expect(unreadQueue['2'].length).toBe(0); // Mixing unread and mention channels expect(prefetchQueue([...unreadChannels, ...mentionChannels], channelMemberships, true)).toEqual({1: [], 2: [], 3: []}); const mixedQueue = prefetchQueue([...unreadChannels9, ...mentionChannels10], channelMemberships, true); expect(mixedQueue['1'].length).toBe(10); expect(mixedQueue['2'].length).toBe(0); }); });
2,035
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/data_prefetch/data_prefetch.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 {loadProfilesForSidebar} from 'actions/user_actions'; import {TestHelper} from 'utils/test_helper'; import DataPrefetch from './data_prefetch'; const mockQueue: Array<() => Promise<void>> = []; jest.mock('p-queue', () => class PQueueMock { add = (o: () => Promise<void>) => mockQueue.push(o); clear = () => mockQueue.splice(0, mockQueue.length); }); jest.mock('actions/user_actions', () => ({ loadProfilesForSidebar: jest.fn(() => Promise.resolve({})), })); describe('/components/data_prefetch', () => { const defaultProps = { currentChannelId: '', actions: { prefetchChannelPosts: jest.fn(() => Promise.resolve({})), trackPreloadedChannels: jest.fn(), }, prefetchQueueObj: { 1: [], }, prefetchRequestStatus: {}, sidebarLoaded: true, unreadChannels: [TestHelper.getChannelMock({ id: 'mentionChannel', display_name: 'mentionChannel', create_at: 0, update_at: 0, delete_at: 0, team_id: 'team_id', type: 'O' as ChannelType, name: '', header: '', purpose: '', creator_id: '', scheme_id: '', group_constrained: false, last_post_at: 1234, last_root_post_at: 1234, }), TestHelper.getChannelMock({ id: 'unreadChannel', display_name: 'unreadChannel', create_at: 0, update_at: 0, delete_at: 0, team_id: 'team_id', type: 'O' as ChannelType, name: '', header: '', purpose: '', creator_id: '', scheme_id: '', group_constrained: false, last_post_at: 1235, last_root_post_at: 1235, })], }; beforeEach(() => { mockQueue.splice(0, mockQueue.length); }); test('should fetch posts for current channel on first channel load', async () => { const props = defaultProps; const wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); const instance = wrapper.instance(); instance.prefetchPosts = jest.fn(); // Change channels and wait for async componentDidUpdate to resolve wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(mockQueue).toHaveLength(1); expect(instance.prefetchPosts).not.toHaveBeenCalled(); // Manually run queued tasks mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(1); expect(instance.prefetchPosts).toHaveBeenCalledWith('currentChannelId'); }); test('should fetch profiles for sidebar on first channel load', async () => { const props = defaultProps; const wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); expect(loadProfilesForSidebar).not.toHaveBeenCalled(); // Change channels wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(loadProfilesForSidebar).toHaveBeenCalledTimes(1); // Change channels again wrapper.setProps({currentChannelId: 'anotherChannelId'}); await Promise.resolve(true); expect(loadProfilesForSidebar).toHaveBeenCalledTimes(1); }); test('should fetch channels in priority order', async () => { const props = { ...defaultProps, prefetchQueueObj: { 1: ['mentionChannel0', 'mentionChannel1'], 2: ['unreadChannel0', 'unreadChannel1'], 3: [], }, }; const wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); const instance = wrapper.instance(); instance.prefetchPosts = jest.fn(); wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(mockQueue).toHaveLength(5); // current channel, mentioned channels, unread channels expect(instance.prefetchPosts).not.toHaveBeenCalled(); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(1); expect(instance.prefetchPosts).toHaveBeenCalledWith('currentChannelId'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(2); expect(instance.prefetchPosts).toHaveBeenCalledWith('mentionChannel0'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(3); expect(instance.prefetchPosts).toHaveBeenCalledWith('mentionChannel1'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(4); expect(instance.prefetchPosts).toHaveBeenCalledWith('unreadChannel0'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(5); expect(instance.prefetchPosts).toHaveBeenCalledWith('unreadChannel1'); }); test('should cancel fetch and requeue channels when prefetch queue changes', async () => { const props = { ...defaultProps, prefetchQueueObj: { 1: [], 2: ['unreadChannel0', 'unreadChannel1', 'unreadChannel2'], }, }; const wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); const instance = wrapper.instance(); instance.prefetchPosts = jest.fn(); wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(mockQueue).toHaveLength(4); expect(instance.prefetchPosts).not.toHaveBeenCalled(); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(1); expect(instance.prefetchPosts).toHaveBeenCalledWith('currentChannelId'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(2); expect(instance.prefetchPosts).toHaveBeenCalledWith('unreadChannel0'); wrapper.setProps({ prefetchQueueObj: { 1: ['mentionChannel0', 'mentionChannel1'], 2: ['unreadChannel2', 'unreadChannel3'], }, }); // Check queue has been cleared and wait for async componentDidUpdate to complete expect(mockQueue).toHaveLength(0); await Promise.resolve(true); expect(mockQueue).toHaveLength(4); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(3); expect(instance.prefetchPosts).toHaveBeenCalledWith('mentionChannel0'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(4); expect(instance.prefetchPosts).toHaveBeenCalledWith('mentionChannel1'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(5); expect(instance.prefetchPosts).toHaveBeenCalledWith('unreadChannel2'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(6); expect(instance.prefetchPosts).toHaveBeenCalledWith('unreadChannel3'); }); test('should skip making request for posts if a request was made', async () => { const props = { ...defaultProps, prefetchQueueObj: { 1: ['mentionChannel'], 2: ['unreadChannel'], }, prefetchRequestStatus: { unreadChannel: 'success', }, }; const wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); const instance = wrapper.instance(); instance.prefetchPosts = jest.fn(); wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(mockQueue).toHaveLength(2); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(1); expect(instance.prefetchPosts).toHaveBeenCalledWith('currentChannelId'); mockQueue.shift()!(); expect(instance.prefetchPosts).toHaveBeenCalledTimes(2); expect(instance.prefetchPosts).toHaveBeenCalledWith('mentionChannel'); }); test('should add delay if last post is made in last min', async () => { Date.now = jest.fn().mockReturnValue(12346); Math.random = jest.fn().mockReturnValue(0.5); const props = { ...defaultProps, prefetchQueueObj: { 1: ['mentionChannel'], }, unreadChannels: [{ id: 'mentionChannel', display_name: 'mentionChannel', create_at: 0, update_at: 0, delete_at: 0, team_id: 'team_id', type: 'O' as ChannelType, name: '', header: '', purpose: '', creator_id: '', scheme_id: '', group_constrained: false, last_post_at: 12345, last_root_post_at: 12345, }], }; const wrapper = shallow( <DataPrefetch {...props}/>, ); wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(mockQueue).toHaveLength(2); // The first channel is loaded with no delay mockQueue.shift()!(); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledTimes(1); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledWith('currentChannelId', undefined); // And the second is loaded with a half second delay mockQueue.shift()!(); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledTimes(2); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledWith('mentionChannel', 500); }); test('should not add delay if channel is DM even if last post is made in last min', async () => { Date.now = jest.fn().mockReturnValue(12346); Math.random = jest.fn().mockReturnValue(0.5); const props = { ...defaultProps, prefetchQueueObj: { 1: ['mentionChannel'], }, unreadChannels: [{ id: 'mentionChannel', display_name: 'mentionChannel', create_at: 0, update_at: 0, delete_at: 0, team_id: 'team_id', type: 'D' as ChannelType, name: '', header: '', purpose: '', creator_id: '', scheme_id: '', group_constrained: false, last_post_at: 12345, last_root_post_at: 12345, }], }; const wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); wrapper.setProps({currentChannelId: 'currentChannelId'}); await Promise.resolve(true); expect(mockQueue).toHaveLength(2); // The first channel is loaded with no delay mockQueue.shift()!(); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledTimes(1); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledWith('currentChannelId', undefined); // And the second is loaded with no delay either mockQueue.shift()!(); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledTimes(2); expect(props.actions.prefetchChannelPosts).toHaveBeenCalledWith('mentionChannel', undefined); }); test('should load profiles once the current channel and sidebar are both loaded', () => { const props = { ...defaultProps, currentChannelId: '', sidebarLoaded: false, }; let wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); wrapper.setProps({}); expect(loadProfilesForSidebar).not.toHaveBeenCalled(); // With current channel loaded first wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); wrapper.setProps({ currentChannelId: 'channel', }); expect(loadProfilesForSidebar).not.toHaveBeenCalled(); wrapper.setProps({ sidebarLoaded: true, }); expect(loadProfilesForSidebar).toHaveBeenCalled(); jest.clearAllMocks(); // With sidebar loaded first wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); wrapper.setProps({ sidebarLoaded: true, }); expect(loadProfilesForSidebar).not.toHaveBeenCalled(); wrapper.setProps({ currentChannelId: 'channel', }); expect(loadProfilesForSidebar).toHaveBeenCalled(); jest.clearAllMocks(); // With both loaded at once wrapper = shallow<DataPrefetch>( <DataPrefetch {...props}/>, ); wrapper.setProps({ currentChannelId: 'channel', sidebarLoaded: true, }); expect(loadProfilesForSidebar).toHaveBeenCalled(); }); });