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,413
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users/users_to_remove_role.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {IntlProvider} from 'react-intl'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; import UsersToRemoveRole from './users_to_remove_role'; describe('components/admin_console/team_channel_settings/group/UsersToRemoveRole', () => { const groups = [TestHelper.getGroupMock({id: 'group1', display_name: 'group1'})]; const userWithGroups = { ...TestHelper.getUserMock(), groups, }; const adminUserWithGroups = { ...TestHelper.getUserMock({roles: 'system_admin system_user'}), groups, }; const guestUserWithGroups = { ...TestHelper.getUserMock({roles: 'system_guest'}), groups, }; const teamMembership = TestHelper.getTeamMembershipMock({scheme_admin: false}); const adminTeamMembership = TestHelper.getTeamMembershipMock({scheme_admin: true}); const channelMembership = TestHelper.getChannelMembershipMock({scheme_admin: false}, {}); const adminChannelMembership = TestHelper.getChannelMembershipMock({scheme_admin: true}, {}); const guestMembership = TestHelper.getTeamMembershipMock({scheme_admin: false, scheme_user: false}); const scopeTeam: 'team' | 'channel' = 'team'; const scopeChannel: 'team' | 'channel' = 'channel'; test('should match snapshot scope team and regular membership', () => { const wrapper = mountWithIntl( <IntlProvider locale='en' messages={{}} > <UsersToRemoveRole user={userWithGroups} scope={scopeTeam} membership={teamMembership} /> </IntlProvider>, ).childAt(0); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot scope team and admin membership', () => { const wrapper = mountWithIntl( <IntlProvider locale='en' messages={{}} > <UsersToRemoveRole user={userWithGroups} scope={scopeTeam} membership={adminTeamMembership} /> </IntlProvider>, ).childAt(0); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot scope channel and regular membership', () => { const wrapper = mountWithIntl( <IntlProvider locale='en' messages={{}} > <UsersToRemoveRole user={userWithGroups} scope={scopeChannel} membership={channelMembership} /> </IntlProvider>, ).childAt(0); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot scope channel and admin membership', () => { const wrapper = mountWithIntl( <IntlProvider locale='en' messages={{}} > <UsersToRemoveRole user={userWithGroups} scope={scopeChannel} membership={adminChannelMembership} /> </IntlProvider>, ).childAt(0); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot scope channel and admin membership but user is sys admin', () => { const wrapper = mountWithIntl( <IntlProvider locale='en' messages={{}} > <UsersToRemoveRole user={adminUserWithGroups} scope={scopeChannel} membership={adminChannelMembership} /> </IntlProvider>, ).childAt(0); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot guest', () => { const wrapper = mountWithIntl( <IntlProvider locale='en' messages={{}} > <UsersToRemoveRole user={guestUserWithGroups} scope={scopeTeam} membership={guestMembership} /> </IntlProvider>, ).childAt(0); expect(wrapper).toMatchSnapshot(); }); });
1,415
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users/__snapshots__/users_to_remove.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/admin_console/team_channel_settings/group/UsersToRemove should match snapshot loading 1`] = ` <div className="UsersToRemove" > <DataGrid columns={ Array [ Object { "field": "name", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.team_channel_settings.user_list.nameHeader" />, "width": 5, }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.team_channel_settings.user_list.roleHeader" />, "width": 2, }, Object { "field": "groups", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Groups" id="admin.team_channel_settings.user_list.groupsHeader" />, "width": 3, }, ] } endCount={2} filterProps={ Object { "keys": Array [ "role", ], "onFilter": [Function], "options": Object { "role": Object { "keys": Array [ "system_guest", "team_user", "team_admin", "system_admin", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "values": Object { "system_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="System Admin" id="admin.user_grid.system_admin" />, "value": false, }, "system_guest": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Guest" id="admin.user_grid.guest" />, "value": false, }, "team_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Team Admin" id="admin.user_grid.team_admin" />, "value": false, }, "team_user": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Member" id="admin.user_item.member" />, "value": false, }, }, }, }, } } loading={true} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.member_list_group.notFound" /> } previousPage={[Function]} rows={Array []} searchPlaceholder="" startCount={1} term="" total={2} /> </div> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemove should match snapshot searching with filters 1`] = ` <div className="UsersToRemove" > <DataGrid columns={ Array [ Object { "field": "name", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.team_channel_settings.user_list.nameHeader" />, "width": 5, }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.team_channel_settings.user_list.roleHeader" />, "width": 2, }, Object { "field": "groups", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Groups" id="admin.team_channel_settings.user_list.groupsHeader" />, "width": 3, }, ] } endCount={2} filterProps={ Object { "keys": Array [ "role", ], "onFilter": [Function], "options": Object { "role": Object { "keys": Array [ "system_guest", "team_user", "team_admin", "system_admin", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "values": Object { "system_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="System Admin" id="admin.user_grid.system_admin" />, "value": false, }, "system_guest": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Guest" id="admin.user_grid.guest" />, "value": false, }, "team_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Team Admin" id="admin.user_grid.team_admin" />, "value": false, }, "team_user": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Member" id="admin.user_item.member" />, "value": false, }, }, }, }, } } loading={true} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.member_list_group.notFound" /> } previousPage={[Function]} rows={Array []} searchPlaceholder="" startCount={1} term="foo" total={2} /> </div> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemove should match snapshot with 2 users 1`] = ` <div className="UsersToRemove" > <DataGrid columns={ Array [ Object { "field": "name", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.team_channel_settings.user_list.nameHeader" />, "width": 5, }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.team_channel_settings.user_list.roleHeader" />, "width": 2, }, Object { "field": "groups", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Groups" id="admin.team_channel_settings.user_list.groupsHeader" />, "width": 3, }, ] } endCount={2} filterProps={ Object { "keys": Array [ "role", ], "onFilter": [Function], "options": Object { "role": Object { "keys": Array [ "system_guest", "team_user", "team_admin", "system_admin", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "values": Object { "system_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="System Admin" id="admin.user_grid.system_admin" />, "value": false, }, "system_guest": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Guest" id="admin.user_grid.guest" />, "value": false, }, "team_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Team Admin" id="admin.user_grid.team_admin" />, "value": false, }, "team_user": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Member" id="admin.user_item.member" />, "value": false, }, }, }, }, } } loading={true} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.member_list_group.notFound" /> } previousPage={[Function]} rows={Array []} searchPlaceholder="" startCount={1} term="" total={2} /> </div> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemove should match snapshot with guests disabled 1`] = ` <div className="UsersToRemove" > <DataGrid columns={ Array [ Object { "field": "name", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.team_channel_settings.user_list.nameHeader" />, "width": 5, }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.team_channel_settings.user_list.roleHeader" />, "width": 2, }, Object { "field": "groups", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Groups" id="admin.team_channel_settings.user_list.groupsHeader" />, "width": 3, }, ] } endCount={2} filterProps={ Object { "keys": Array [ "role", ], "onFilter": [Function], "options": Object { "role": Object { "keys": Array [ "team_user", "team_admin", "system_admin", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "values": Object { "system_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="System Admin" id="admin.user_grid.system_admin" />, "value": false, }, "team_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Team Admin" id="admin.user_grid.team_admin" />, "value": false, }, "team_user": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Member" id="admin.user_item.member" />, "value": false, }, }, }, }, } } loading={true} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.member_list_group.notFound" /> } previousPage={[Function]} rows={Array []} searchPlaceholder="" startCount={1} term="" total={2} /> </div> `;
1,416
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users/__snapshots__/users_to_remove_groups.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/admin_console/team_channel_settings/group/UsersToRemoveGroups should match snapshot with 0 groups 1`] = ` <div className="UsersToRemoveGroups" > <MemoizedFormattedMessage defaultMessage="{amount, number} {amount, plural, one {Group} other {Groups}}" id="team_channel_settings.group.group_user_row.numberOfGroups" values={ Object { "amount": 0, } } /> </div> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveGroups should match snapshot with 1 group 1`] = ` <div className="UsersToRemoveGroups" > group1 </div> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveGroups should match snapshot with 3 groups 1`] = ` <div className="UsersToRemoveGroups" > <OverlayTrigger defaultOverlayShown={false} overlay={ <Tooltip id="groupsTooltip" > group1, group2, group3 </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <a href="#" > <MemoizedFormattedMessage defaultMessage="{amount, number} {amount, plural, one {Group} other {Groups}}" id="team_channel_settings.group.group_user_row.numberOfGroups" values={ Object { "amount": 3, } } /> </a> </OverlayTrigger> </div> `;
1,417
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/group/group_users/__snapshots__/users_to_remove_role.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/admin_console/team_channel_settings/group/UsersToRemoveRole should match snapshot guest 1`] = ` <UsersToRemoveRole membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": false, "team_id": "team_id", "user_id": "user_id", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "groups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group1", "has_syncables": false, "id": "group1", "member_count": 0, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "system_guest", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } > <div className="UsersToRemoveRole" > Guest </div> </UsersToRemoveRole> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveRole should match snapshot scope channel and admin membership 1`] = ` <UsersToRemoveRole membership={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": true, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } scope="channel" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "groups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group1", "has_syncables": false, "id": "group1", "member_count": 0, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } > <div className="UsersToRemoveRole" > Channel Admin </div> </UsersToRemoveRole> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveRole should match snapshot scope channel and admin membership but user is sys admin 1`] = ` <UsersToRemoveRole membership={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": true, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } scope="channel" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "groups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group1", "has_syncables": false, "id": "group1", "member_count": 0, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "system_admin system_user", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } > <div className="UsersToRemoveRole" > System Admin </div> </UsersToRemoveRole> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveRole should match snapshot scope channel and regular membership 1`] = ` <UsersToRemoveRole membership={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } scope="channel" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "groups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group1", "has_syncables": false, "id": "group1", "member_count": 0, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } > <div className="UsersToRemoveRole" > Member </div> </UsersToRemoveRole> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveRole should match snapshot scope team and admin membership 1`] = ` <UsersToRemoveRole membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": true, "scheme_guest": false, "scheme_user": true, "team_id": "team_id", "user_id": "user_id", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "groups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group1", "has_syncables": false, "id": "group1", "member_count": 0, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } > <div className="UsersToRemoveRole" > Team Admin </div> </UsersToRemoveRole> `; exports[`components/admin_console/team_channel_settings/group/UsersToRemoveRole should match snapshot scope team and regular membership 1`] = ` <UsersToRemoveRole membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team_id", "user_id": "user_id", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "groups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group1", "has_syncables": false, "id": "group1", "member_count": 0, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "id": "user_id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } > <div className="UsersToRemoveRole" > Member </div> </UsersToRemoveRole> `;
1,419
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/team_settings.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 {TeamsSettings} from './team_settings'; describe('admin_console/team_channel_settings/team/TeamSettings', () => { test('should match snapshot', () => { const wrapper = shallow( <TeamsSettings siteName='site' />, ); expect(wrapper).toMatchSnapshot(); }); });
1,421
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/__snapshots__/team_settings.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamSettings should match snapshot 1`] = ` <div className="wrapper--fixed" > <AdminHeader> <MemoizedFormattedMessage defaultMessage="{siteName} Teams" id="admin.team_settings.groupsPageTitle" values={ Object { "siteName": "site", } } /> </AdminHeader> <div className="admin-console__wrapper" > <div className="admin-console__content" > <AdminPanel className="" id="teams" subtitleDefault="Manage team settings." subtitleId="admin.team_settings.description" titleDefault="Teams" titleId="admin.team_settings.title" > <Connect(TeamList) /> </AdminPanel> </div> </div> </div> `;
1,423
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_details.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 TeamDetails from './team_details'; describe('admin_console/team_channel_settings/team/TeamDetails', () => { const groups = [TestHelper.getGroupMock({ id: '123', display_name: 'DN', member_count: 3, })]; const allGroups = { 123: groups[0], }; const testTeam = TestHelper.getTeamMock({ id: '123', allow_open_invite: false, allowed_domains: '', group_constrained: false, display_name: 'team', delete_at: 0, }); const baseProps = { groups, totalGroups: groups.length, team: testTeam, teamID: testTeam.id, allGroups, actions: { getTeam: jest.fn().mockResolvedValue([]), linkGroupSyncable: jest.fn(), patchTeam: jest.fn(), setNavigationBlocked: jest.fn(), unlinkGroupSyncable: jest.fn(), getGroups: jest.fn().mockResolvedValue([]), membersMinusGroupMembers: jest.fn(), patchGroupSyncable: jest.fn(), addUserToTeam: jest.fn(), removeUserFromTeam: jest.fn(), updateTeamMemberSchemeRoles: jest.fn(), deleteTeam: jest.fn(), unarchiveTeam: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <TeamDetails {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with isLocalArchived true', () => { const props = { ...baseProps, team: { ...baseProps.team, delete_at: 16465313, }, }; const wrapper = shallow( <TeamDetails {...props} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,425
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_groups.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 {TeamGroups} from './team_groups'; describe('admin_console/team_channel_settings/team/TeamGroups', () => { test('should match snapshot', () => { const groups = [TestHelper.getGroupMock({ id: '123', display_name: 'DN', member_count: 3, })]; const testTeam = TestHelper.getTeamMock({ id: '123', allow_open_invite: false, allowed_domains: '', group_constrained: false, display_name: 'team', }); const wrapper = shallow( <TeamGroups syncChecked={true} onAddCallback={jest.fn()} onGroupRemoved={jest.fn()} setNewGroupRole={jest.fn()} removedGroups={[]} groups={groups} team={testTeam} totalGroups={1} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,427
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_modes.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 {TeamModes} from './team_modes'; describe('admin_console/team_channel_settings/team/TeamModes', () => { test('should match snapshot', () => { const wrapper = shallow( <TeamModes onToggle={jest.fn()} syncChecked={false} allAllowedChecked={false} allowedDomains={''} allowedDomainsChecked={true} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,430
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_profile.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import * as reactRedux from 'react-redux'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {CloudProducts} from 'utils/constants'; import {FileSizes} from 'utils/file_utils'; import {TestHelper} from 'utils/test_helper'; import {TeamProfile} from './team_profile'; describe('admin_console/team_channel_settings/team/TeamProfile__Cloud', () => { const baseProps = { team: TestHelper.getTeamMock(), onToggleArchive: jest.fn(), isArchived: true, }; const initialState = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin'}, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, }, limits: { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, }, boards: { cards: 500, views: 5, }, }, }, }, usage: { integrations: { enabled: 11, enabledLoaded: true, }, messages: { history: 10000, historyLoaded: true, }, files: { totalStorage: FileSizes.Gigabyte, totalStorageLoaded: true, }, teams: { active: 1, cloudArchived: 0, teamsLoaded: true, }, boards: { cards: 500, cardsLoaded: true, }, }, }, }; test('should match snapshot - archived, at teams limit', () => { const store = mockStore(initialState); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <TeamProfile {...baseProps}/> </reactRedux.Provider>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('OverlayTrigger').exists()).toEqual(true); }); test('should match snapshot - not archived, at teams limit', () => { const props = { ...baseProps, isArchived: false, }; const store = mockStore(initialState); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <TeamProfile {...props}/> </reactRedux.Provider>, ); expect(wrapper).toMatchSnapshot(); // Unarchived will always be archiveable expect(wrapper.find('OverlayTrigger').exists()).toEqual(false); }); test('restore should not be disabled when below teams limit', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.limits = { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 10, }, boards: { cards: 500, views: 5, }, }, }; state.entities.usage = { integrations: { enabled: 11, enabledLoaded: true, }, messages: { history: 10000, historyLoaded: true, }, files: { totalStorage: FileSizes.Gigabyte, totalStorageLoaded: true, }, teams: { active: 1, cloudArchived: 0, teamsLoaded: true, }, boards: { cards: 500, cardsLoaded: true, }, }; const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <TeamProfile {...baseProps}/> </reactRedux.Provider>, ); expect(wrapper).toMatchSnapshot(); // Unarchived will always be archiveable expect(wrapper.find('OverlayTrigger').exists()).toEqual(false); }); }); describe('admin_console/team_channel_settings/team/TeamProfile', () => { const baseProps = { team: TestHelper.getTeamMock(), onToggleArchive: jest.fn(), isArchived: false, }; const initialState = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { general: { license: { IsLicensed: 'true', Cloud: 'false', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin'}, }, }, usage: { integrations: { enabled: 0, enabledLoaded: true, }, messages: { history: 0, historyLoaded: true, }, files: { totalStorage: 0, totalStorageLoaded: true, }, teams: { active: 0, teamsLoaded: true, }, boards: { cards: 0, cardsLoaded: true, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, }, limits: { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, }, boards: { cards: 500, views: 5, }, }, }, }, }, }; const state = JSON.parse(JSON.stringify(initialState)); const store = mockStore(state); test('should match snapshot (not cloud, freemium disabled', () => { const wrapper = shallow( <reactRedux.Provider store={store}> <TeamProfile {...baseProps}/> </reactRedux.Provider>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('OverlayTrigger').exists()).toEqual(false); }); test('should match snapshot with isArchived true', () => { const props = { ...baseProps, isArchived: true, }; const wrapper = shallow( <reactRedux.Provider store={store}> <TeamProfile {...props}/> </reactRedux.Provider>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('OverlayTrigger').exists()).toEqual(false); }); });
1,432
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/__snapshots__/team_details.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamDetails should match snapshot 1`] = ` <div className="wrapper--fixed" > <AdminHeader withBackButton={true} > <div> <Connect(Component) className="fa fa-angle-left back" to="/admin_console/user_management/teams" /> <MemoizedFormattedMessage defaultMessage="Team Configuration" id="admin.team_settings.team_detail.group_configuration" /> </div> </AdminHeader> <div className="admin-console__wrapper" > <div className="admin-console__content" > <TeamProfile isArchived={false} onToggleArchive={[Function]} saveNeeded={false} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "team", "email": "", "group_constrained": false, "id": "123", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } /> <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Archive" id="admin.team_settings.team_detail.archive_confirm.button" /> } message={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving will archive the team and make its contents inaccessible for all users. Are you sure you wish to save and archive this team?" id="admin.team_settings.team_detail.archive_confirm.message" /> } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={false} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Save and Archive Team" id="admin.team_settings.team_detail.archive_confirm.title" /> } /> <RemoveConfirmModal amount={0} inChannel={false} onCancel={[Function]} onConfirm={[Function]} show={false} /> <TeamModes allAllowedChecked={false} allowedDomains="" allowedDomainsChecked={false} onToggle={[Function]} syncChecked={false} /> <Connect(TeamMembers) onAddCallback={[Function]} onRemoveCallback={[Function]} teamId="123" updateRole={[Function]} usersToAdd={Object {}} usersToRemove={Object {}} /> </div> </div> <SaveChangesPanel cancelLink="/admin_console/user_management/teams" onClick={[Function]} saveNeeded={false} saving={false} /> </div> `; exports[`admin_console/team_channel_settings/team/TeamDetails should match snapshot with isLocalArchived true 1`] = ` <div className="wrapper--fixed" > <AdminHeader withBackButton={true} > <div> <Connect(Component) className="fa fa-angle-left back" to="/admin_console/user_management/teams" /> <MemoizedFormattedMessage defaultMessage="Team Configuration" id="admin.team_settings.team_detail.group_configuration" /> </div> </AdminHeader> <div className="admin-console__wrapper" > <div className="admin-console__content" > <TeamProfile isArchived={true} onToggleArchive={[Function]} saveNeeded={false} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 16465313, "description": "", "display_name": "team", "email": "", "group_constrained": false, "id": "123", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } /> <ConfirmModal confirmButtonClass="btn btn-primary" confirmButtonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Archive" id="admin.team_settings.team_detail.archive_confirm.button" /> } message={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving will archive the team and make its contents inaccessible for all users. Are you sure you wish to save and archive this team?" id="admin.team_settings.team_detail.archive_confirm.message" /> } modalClass="" onCancel={[Function]} onConfirm={[Function]} show={false} title={ <Memo(MemoizedFormattedMessage) defaultMessage="Save and Archive Team" id="admin.team_settings.team_detail.archive_confirm.title" /> } /> </div> </div> <SaveChangesPanel cancelLink="/admin_console/user_management/teams" onClick={[Function]} saveNeeded={false} saving={false} /> </div> `;
1,433
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/__snapshots__/team_groups.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamGroups should match snapshot 1`] = ` <AdminPanel button={ <ToggleModalButton className="btn btn-primary" dialogProps={ Object { "excludeGroups": Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "DN", "has_syncables": false, "id": "123", "member_count": 3, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ], "includeGroups": Array [], "onAddCallback": [MockFunction], "skipCommit": true, "team": Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "team", "email": "", "group_constrained": false, "id": "123", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeamToggle" modalId="add_groups_to_team" > <Memo(MemoizedFormattedMessage) defaultMessage="Add Group" id="admin.team_settings.team_details.add_group" /> </ToggleModalButton> } className="" id="team_groups" subtitleDefault="Add and remove team members based on their group membership." subtitleId="admin.team_settings.team_detail.syncedGroupsDescription" titleDefault="Synced Groups" titleId="admin.team_settings.team_detail.syncedGroupsTitle" > <Connect(GroupList) groups={ Array [ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "DN", "has_syncables": false, "id": "123", "member_count": 3, "name": "group_name", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, }, ] } isModeSync={true} onGroupRemoved={[MockFunction]} setNewGroupRole={[MockFunction]} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "team", "email": "", "group_constrained": false, "id": "123", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } totalGroups={1} type="team" /> </AdminPanel> `;
1,434
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/__snapshots__/team_modes.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamModes should match snapshot 1`] = ` <AdminPanel className="" id="team_manage" subtitleDefault="Choose between inviting members manually or syncing members automatically from groups." subtitleId="admin.team_settings.team_detail.manageDescription" titleDefault="Team Management" titleId="admin.team_settings.team_detail.manageTitle" > <div className="group-teams-and-channels" > <div className="group-teams-and-channels--body" > <AllowAllToggle allAllowedChecked={false} allowedDomains="" allowedDomainsChecked={true} onToggle={[MockFunction]} syncChecked={false} /> <AllowedDomainsToggle allAllowedChecked={false} allowedDomains="" allowedDomainsChecked={true} onToggle={[MockFunction]} syncChecked={false} /> </div> </div> </AdminPanel> `;
1,435
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/__snapshots__/team_profile.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamProfile should match snapshot (not cloud, freemium disabled 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, }, } } > <TeamProfile isArchived={false} onToggleArchive={[MockFunction]} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team_id", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } /> </ContextProvider> `; exports[`admin_console/team_channel_settings/team/TeamProfile should match snapshot with isArchived true 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, }, } } > <TeamProfile isArchived={true} onToggleArchive={[MockFunction]} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team_id", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } /> </ContextProvider> `; exports[`admin_console/team_channel_settings/team/TeamProfile__Cloud restore should not be disabled when below teams limit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <TeamProfile isArchived={true} onToggleArchive={[MockFunction]} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team_id", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } > <AdminPanel className="" id="team_profile" subtitleDefault="Summary of the team, including team name and description." subtitleId="admin.team_settings.team_detail.profileDescription" titleDefault="Team Profile" titleId="admin.team_settings.team_detail.profileTitle" > <div className="AdminPanel clearfix " id="team_profile" > <div className="header" > <div> <h3> <FormattedMessage defaultMessage="Team Profile" id="admin.team_settings.team_detail.profileTitle" > <span> Team Profile </span> </FormattedMessage> </h3> <div className="mt-2" > <FormattedMessage defaultMessage="Summary of the team, including team name and description." id="admin.team_settings.team_detail.profileDescription" > <span> Summary of the team, including team name and description. </span> </FormattedMessage> </div> </div> </div> <div className="group-teams-and-channels" > <div className="group-teams-and-channels--body" > <div className="d-flex" > <div className="large-team-image-col" > <injectIntl(TeamIcon) content="name" size="lg" url={null} > <TeamIcon content="name" 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, } } size="lg" url={null} > <div className="TeamIcon TeamIcon__lg no-hover" > <div className="TeamIcon__content no-hover" > <div aria-label="name Team Initials" className="TeamIcon__initials TeamIcon__initials__lg" data-testid="teamIconInitial" role="img" > na </div> </div> </div> </TeamIcon> </injectIntl(TeamIcon)> </div> <div className="team-desc-col" > <div className="row row-bottom-padding" > <FormattedMarkdownMessage defaultMessage="**Team Name**:" id="admin.team_settings.team_detail.teamName" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>Team Name</strong>:", } } /> </FormattedMarkdownMessage> <br /> name </div> <div className="row" > <FormattedMarkdownMessage defaultMessage="**Team Description**:" id="admin.team_settings.team_detail.teamDescription" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>Team Description</strong>:", } } /> </FormattedMarkdownMessage> <br /> <span className="greyed-out" > No team description added. </span> </div> </div> </div> <div className="AdminChannelDetails_archiveContainer" > <button className="btn ArchiveButton ArchiveButton___archived cloud-limits-disabled" disabled={false} onClick={[Function]} type="button" > <i className="icon icon-archive-arrow-up-outline" /> <FormattedMessage defaultMessage="Unarchive Team" id="admin.team_settings.team_details.unarchiveTeam" > <span> Unarchive Team </span> </FormattedMessage> </button> </div> </div> </div> </div> </AdminPanel> </TeamProfile> </Provider> `; exports[`admin_console/team_channel_settings/team/TeamProfile__Cloud should match snapshot - archived, at teams limit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <TeamProfile isArchived={true} onToggleArchive={[MockFunction]} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team_id", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } > <AdminPanel className="" id="team_profile" subtitleDefault="Summary of the team, including team name and description." subtitleId="admin.team_settings.team_detail.profileDescription" titleDefault="Team Profile" titleId="admin.team_settings.team_detail.profileTitle" > <div className="AdminPanel clearfix " id="team_profile" > <div className="header" > <div> <h3> <FormattedMessage defaultMessage="Team Profile" id="admin.team_settings.team_detail.profileTitle" > <span> Team Profile </span> </FormattedMessage> </h3> <div className="mt-2" > <FormattedMessage defaultMessage="Summary of the team, including team name and description." id="admin.team_settings.team_detail.profileDescription" > <span> Summary of the team, including team name and description. </span> </FormattedMessage> </div> </div> </div> <div className="group-teams-and-channels" > <div className="group-teams-and-channels--body" > <div className="d-flex" > <div className="large-team-image-col" > <injectIntl(TeamIcon) content="name" size="lg" url={null} > <TeamIcon content="name" 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, } } size="lg" url={null} > <div className="TeamIcon TeamIcon__lg no-hover" > <div className="TeamIcon__content no-hover" > <div aria-label="name Team Initials" className="TeamIcon__initials TeamIcon__initials__lg" data-testid="teamIconInitial" role="img" > na </div> </div> </div> </TeamIcon> </injectIntl(TeamIcon)> </div> <div className="team-desc-col" > <div className="row row-bottom-padding" > <FormattedMarkdownMessage defaultMessage="**Team Name**:" id="admin.team_settings.team_detail.teamName" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>Team Name</strong>:", } } /> </FormattedMarkdownMessage> <br /> name </div> <div className="row" > <FormattedMarkdownMessage defaultMessage="**Team Description**:" id="admin.team_settings.team_detail.teamDescription" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>Team Description</strong>:", } } /> </FormattedMarkdownMessage> <br /> <span className="greyed-out" > No team description added. </span> </div> </div> </div> <div className="AdminChannelDetails_archiveContainer" > <OverlayTrigger defaultOverlayShown={false} delay={400} disabled={false} overlay={ <Tooltip id="sharedTooltip" > <div className="tooltip-title" > <Memo(MemoizedFormattedMessage) defaultMessage="Upgrade to Unarchive" id="workspace_limits.teams_limit_reached.upgrade_to_unarchive" /> </div> <div className="tooltip-body" > <Memo(MemoizedFormattedMessage) defaultMessage="You've reached the team limit for your current plan. Consider upgrading to unarchive this team or archive your other teams" id="workspace_limits.teams_limit_reached.tool_tip" /> </div> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delay={400} overlay={ <OverlayWrapper id="sharedTooltip" 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, } } > <div className="tooltip-title" > <Memo(MemoizedFormattedMessage) defaultMessage="Upgrade to Unarchive" id="workspace_limits.teams_limit_reached.upgrade_to_unarchive" /> </div> <div className="tooltip-body" > <Memo(MemoizedFormattedMessage) defaultMessage="You've reached the team limit for your current plan. Consider upgrading to unarchive this team or archive your other teams" id="workspace_limits.teams_limit_reached.tool_tip" /> </div> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="disabled-overlay-wrapper" onBlur={[Function]} onClick={null} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <button className="btn btn-danger ArchiveButton ArchiveButton___archived cloud-limits-disabled" disabled={true} onClick={[Function]} style={ Object { "pointerEvents": "none", } } type="button" > <i className="icon icon-archive-arrow-up-outline" /> <FormattedMessage defaultMessage="Unarchive Team" id="admin.team_settings.team_details.unarchiveTeam" > <span> Unarchive Team </span> </FormattedMessage> </button> </div> </OverlayTrigger> </OverlayTrigger> <button className="btn btn-secondary upgrade-options-button" onClick={[Function]} type="button" > <FormattedMessage defaultMessage="View upgrade options" id="workspace_limits.teams_limit_reached.view_upgrade_options" > <span> View upgrade options </span> </FormattedMessage> </button> </div> </div> </div> </div> </AdminPanel> </TeamProfile> </Provider> `; exports[`admin_console/team_channel_settings/team/TeamProfile__Cloud should match snapshot - not archived, at teams limit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <TeamProfile isArchived={false} onToggleArchive={[MockFunction]} team={ Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team_id", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, } } > <AdminPanel className="" id="team_profile" subtitleDefault="Summary of the team, including team name and description." subtitleId="admin.team_settings.team_detail.profileDescription" titleDefault="Team Profile" titleId="admin.team_settings.team_detail.profileTitle" > <div className="AdminPanel clearfix " id="team_profile" > <div className="header" > <div> <h3> <FormattedMessage defaultMessage="Team Profile" id="admin.team_settings.team_detail.profileTitle" > <span> Team Profile </span> </FormattedMessage> </h3> <div className="mt-2" > <FormattedMessage defaultMessage="Summary of the team, including team name and description." id="admin.team_settings.team_detail.profileDescription" > <span> Summary of the team, including team name and description. </span> </FormattedMessage> </div> </div> </div> <div className="group-teams-and-channels" > <div className="group-teams-and-channels--body" > <div className="d-flex" > <div className="large-team-image-col" > <injectIntl(TeamIcon) content="name" size="lg" url={null} > <TeamIcon content="name" 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, } } size="lg" url={null} > <div className="TeamIcon TeamIcon__lg no-hover" > <div className="TeamIcon__content no-hover" > <div aria-label="name Team Initials" className="TeamIcon__initials TeamIcon__initials__lg" data-testid="teamIconInitial" role="img" > na </div> </div> </div> </TeamIcon> </injectIntl(TeamIcon)> </div> <div className="team-desc-col" > <div className="row row-bottom-padding" > <FormattedMarkdownMessage defaultMessage="**Team Name**:" id="admin.team_settings.team_detail.teamName" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>Team Name</strong>:", } } /> </FormattedMarkdownMessage> <br /> name </div> <div className="row" > <FormattedMarkdownMessage defaultMessage="**Team Description**:" id="admin.team_settings.team_detail.teamDescription" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>Team Description</strong>:", } } /> </FormattedMarkdownMessage> <br /> <span className="greyed-out" > No team description added. </span> </div> </div> </div> <div className="AdminChannelDetails_archiveContainer" > <button className="btn ArchiveButton ArchiveButton___unarchived cloud-limits-disabled" disabled={false} onClick={[Function]} type="button" > <i className="icon icon-archive-outline" /> <FormattedMessage defaultMessage="Archive Team" id="admin.team_settings.team_details.archiveTeam" > <span> Archive Team </span> </FormattedMessage> </button> </div> </div> </div> </div> </AdminPanel> </TeamProfile> </Provider> `;
1,437
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_members/team_members.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Team, TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {TestHelper} from 'utils/test_helper'; import TeamMembers from './team_members'; describe('admin_console/team_channel_settings/team/TeamMembers', () => { const user1: UserProfile = Object.assign(TestHelper.getUserMock({id: 'user-1'})); const membership1: TeamMembership = Object.assign(TestHelper.getTeamMembershipMock({user_id: 'user-1'})); const user2: UserProfile = Object.assign(TestHelper.getUserMock({id: 'user-2'})); const membership2: TeamMembership = Object.assign(TestHelper.getTeamMembershipMock({user_id: 'user-2'})); const user3: UserProfile = Object.assign(TestHelper.getUserMock({id: 'user-3'})); const membership3: TeamMembership = Object.assign(TestHelper.getTeamMembershipMock({user_id: 'user-3'})); const team: Team = Object.assign(TestHelper.getTeamMock({id: 'team-1'})); const baseProps = { filters: {}, teamId: 'team-1', team, users: [user1, user2, user3], usersToRemove: {}, usersToAdd: {}, teamMembers: { [user1.id]: membership1, [user2.id]: membership2, [user3.id]: membership3, }, enableGuestAccounts: true, totalCount: 3, loading: false, searchTerm: '', onAddCallback: jest.fn(), onRemoveCallback: jest.fn(), updateRole: jest.fn(), actions: { getTeamStats: jest.fn(), loadProfilesAndReloadTeamMembers: jest.fn(), searchProfilesAndTeamMembers: jest.fn(), getFilteredUsersStats: jest.fn(), setUserGridSearch: jest.fn(), setUserGridFilters: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <TeamMembers {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot loading no users', () => { const wrapper = shallow( <TeamMembers {...baseProps} users={[]} teamMembers={{}} totalCount={0} loading={true} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,439
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_members
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/details/team_members/__snapshots__/team_members.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamMembers should match snapshot 1`] = ` <AdminPanel button={ <ToggleModalButton className="btn btn-primary" dialogProps={ Object { "excludeUsers": Object {}, "filterExcludeGuests": true, "includeUsers": Object {}, "onAddCallback": [Function], "skipCommit": true, "team": Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team-1", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addTeamMembers" modalId="add_user_to_team" > <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="admin.team_settings.team_details.add_members" /> </ToggleModalButton> } className="" id="teamMembers" subtitleDefault="A list of users who are currently in the team right now" subtitleId="admin.team_settings.team_detail.membersDescription" titleDefault="Members" titleId="admin.team_settings.team_detail.membersTitle" > <UserGrid excludeUsers={Object {}} filterProps={ Object { "keys": Array [ "role", ], "onFilter": [Function], "options": Object { "role": Object { "keys": Array [ "system_guest", "team_user", "team_admin", "system_admin", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "values": Object { "system_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="System Admin" id="admin.user_grid.system_admin" />, "value": false, }, "system_guest": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Guest" id="admin.user_grid.guest" />, "value": false, }, "team_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Team Admin" id="admin.user_grid.team_admin" />, "value": false, }, "team_user": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Member" id="admin.user_item.member" />, "value": false, }, }, }, }, } } includeUsers={Object {}} loadPage={[Function]} loading={true} memberships={ Object { "user-1": Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team_id", "user_id": "user-1", }, "user-2": Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team_id", "user_id": "user-2", }, "user-3": Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team_id", "user_id": "user-3", }, } } onSearch={[Function]} removeUser={[Function]} scope="team" term="" totalCount={3} updateMembership={[Function]} users={ Array [ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user-1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user-2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "user-3", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, ] } /> </AdminPanel> `; exports[`admin_console/team_channel_settings/team/TeamMembers should match snapshot loading no users 1`] = ` <AdminPanel button={ <ToggleModalButton className="btn btn-primary" dialogProps={ Object { "excludeUsers": Object {}, "filterExcludeGuests": true, "includeUsers": Object {}, "onAddCallback": [Function], "skipCommit": true, "team": Object { "allow_open_invite": false, "allowed_domains": "", "company_name": "", "create_at": 0, "delete_at": 0, "description": "", "display_name": "name", "email": "", "group_constrained": false, "id": "team-1", "invite_id": "", "name": "DN", "scheme_id": "id", "type": "O", "update_at": 0, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addTeamMembers" modalId="add_user_to_team" > <Memo(MemoizedFormattedMessage) defaultMessage="Add Members" id="admin.team_settings.team_details.add_members" /> </ToggleModalButton> } className="" id="teamMembers" subtitleDefault="A list of users who are currently in the team right now" subtitleId="admin.team_settings.team_detail.membersDescription" titleDefault="Members" titleId="admin.team_settings.team_detail.membersTitle" > <UserGrid excludeUsers={Object {}} filterProps={ Object { "keys": Array [ "role", ], "onFilter": [Function], "options": Object { "role": Object { "keys": Array [ "system_guest", "team_user", "team_admin", "system_admin", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "values": Object { "system_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="System Admin" id="admin.user_grid.system_admin" />, "value": false, }, "system_guest": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Guest" id="admin.user_grid.guest" />, "value": false, }, "team_admin": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Team Admin" id="admin.user_grid.team_admin" />, "value": false, }, "team_user": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Member" id="admin.user_item.member" />, "value": false, }, }, }, }, } } includeUsers={Object {}} loadPage={[Function]} loading={true} memberships={Object {}} onSearch={[Function]} removeUser={[Function]} scope="team" term="" totalCount={0} updateMembership={[Function]} users={Array []} /> </AdminPanel> `;
1,442
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/list/team_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {TestHelper} from 'utils/test_helper'; import TeamList from './team_list'; describe('admin_console/team_channel_settings/team/TeamList', () => { test('should match snapshot', () => { const testTeams = [TestHelper.getTeamMock({ id: '123', display_name: 'DN', name: 'DN', })]; const actions = { getData: jest.fn().mockResolvedValue(testTeams), searchTeams: jest.fn().mockResolvedValue(testTeams), }; const wrapper = shallow( <TeamList data={testTeams} total={testTeams.length} actions={actions} />); wrapper.setState({loading: false}); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with paging', () => { const testTeams = []; for (let i = 0; i < 30; i++) { testTeams.push(TestHelper.getTeamMock({ id: 'id' + i, display_name: 'DN' + i, name: 'DN' + i, })); } const actions = { getData: jest.fn().mockResolvedValue(Promise.resolve(testTeams)), searchTeams: jest.fn().mockResolvedValue(testTeams), }; const wrapper = shallow( <TeamList data={testTeams} total={30} actions={actions} />); wrapper.setState({loading: false}); expect(wrapper).toMatchSnapshot(); }); });
1,444
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/list
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/team_channel_settings/team/list/__snapshots__/team_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admin_console/team_channel_settings/team/TeamList should match snapshot 1`] = ` <div className="TeamsList" > <DataGrid columns={ Array [ Object { "field": "name", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.team_settings.team_list.nameHeader" />, "width": 4, }, Object { "field": "management", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Management" id="admin.team_settings.team_list.mappingHeader" />, }, Object { "field": "edit", "fixed": true, "name": "", "textAlign": "right", }, ] } endCount={1} filterProps={ Object { "keys": Array [ "management", ], "onFilter": [Function], "options": Object { "management": Object { "keys": Array [ "allow_open_invite", "invite_only", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Management" id="admin.team_settings.team_list.mappingHeader" />, "values": Object { "allow_open_invite": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Anyone Can Join" id="admin.team_settings.team_row.managementMethod.anyoneCanJoin" />, "value": false, }, "invite_only": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" />, "value": false, }, }, }, }, } } loading={false} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No teams found" id="admin.team_settings.team_list.no_teams_found" /> } previousPage={[Function]} rows={ Array [ Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DNedit" > <Link to="/admin_console/user_management/teams/123" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "123", "management": <span className="TeamList_managementText" data-testid="DNManagement" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN </b> </div> </div>, }, "onClick": [Function], }, ] } rowsContainerStyles={ Object { "minHeight": "80px", } } searchPlaceholder="" startCount={1} term="" total={1} /> </div> `; exports[`admin_console/team_channel_settings/team/TeamList should match snapshot with paging 1`] = ` <div className="TeamsList" > <DataGrid columns={ Array [ Object { "field": "name", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.team_settings.team_list.nameHeader" />, "width": 4, }, Object { "field": "management", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Management" id="admin.team_settings.team_list.mappingHeader" />, }, Object { "field": "edit", "fixed": true, "name": "", "textAlign": "right", }, ] } endCount={10} filterProps={ Object { "keys": Array [ "management", ], "onFilter": [Function], "options": Object { "management": Object { "keys": Array [ "allow_open_invite", "invite_only", ], "name": <Memo(MemoizedFormattedMessage) defaultMessage="Management" id="admin.team_settings.team_list.mappingHeader" />, "values": Object { "allow_open_invite": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Anyone Can Join" id="admin.team_settings.team_row.managementMethod.anyoneCanJoin" />, "value": false, }, "invite_only": Object { "name": <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" />, "value": false, }, }, }, }, } } loading={false} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No teams found" id="admin.team_settings.team_list.no_teams_found" /> } previousPage={[Function]} rows={ Array [ Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN0edit" > <Link to="/admin_console/user_management/teams/id0" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id0", "management": <span className="TeamList_managementText" data-testid="DN0Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN0" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN0 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN1edit" > <Link to="/admin_console/user_management/teams/id1" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id1", "management": <span className="TeamList_managementText" data-testid="DN1Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN1" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN1 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN2edit" > <Link to="/admin_console/user_management/teams/id2" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id2", "management": <span className="TeamList_managementText" data-testid="DN2Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN2" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN2 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN3edit" > <Link to="/admin_console/user_management/teams/id3" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id3", "management": <span className="TeamList_managementText" data-testid="DN3Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN3" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN3 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN4edit" > <Link to="/admin_console/user_management/teams/id4" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id4", "management": <span className="TeamList_managementText" data-testid="DN4Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN4" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN4 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN5edit" > <Link to="/admin_console/user_management/teams/id5" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id5", "management": <span className="TeamList_managementText" data-testid="DN5Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN5" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN5 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN6edit" > <Link to="/admin_console/user_management/teams/id6" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id6", "management": <span className="TeamList_managementText" data-testid="DN6Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN6" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN6 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN7edit" > <Link to="/admin_console/user_management/teams/id7" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id7", "management": <span className="TeamList_managementText" data-testid="DN7Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN7" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN7 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN8edit" > <Link to="/admin_console/user_management/teams/id8" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id8", "management": <span className="TeamList_managementText" data-testid="DN8Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN8" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN8 </b> </div> </div>, }, "onClick": [Function], }, Object { "cells": Object { "edit": <span className="group-actions TeamList_editText" data-testid="DN9edit" > <Link to="/admin_console/user_management/teams/id9" > <Memo(MemoizedFormattedMessage) defaultMessage="Edit" id="admin.team_settings.team_row.configure" /> </Link> </span>, "id": "id9", "management": <span className="TeamList_managementText" data-testid="DN9Management" > <Memo(MemoizedFormattedMessage) defaultMessage="Invite Only" id="admin.team_settings.team_row.managementMethod.inviteOnly" /> </span>, "name": <div className="TeamList_nameColumn" > <div className="TeamList__lowerOpacity" > <injectIntl(TeamIcon) content="DN9" size="sm" url={null} /> </div> <div className="TeamList_nameText" > <b data-testid="team-display-name" > DN9 </b> </div> </div>, }, "onClick": [Function], }, ] } rowsContainerStyles={ Object { "minHeight": "800px", } } searchPlaceholder="" startCount={1} term="" total={30} /> </div> `;
1,448
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/user_grid/user_grid.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 {TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {TestHelper} from 'utils/test_helper'; import UserGrid from './user_grid'; describe('components/admin_console/user_grid/UserGrid', () => { function createUser(id: string, username: string, bot: boolean): UserProfile { return TestHelper.getUserMock({ id, username, is_bot: bot, }); } function createMembership(userId: string, admin: boolean): TeamMembership { return TestHelper.getTeamMembershipMock({ team_id: 'team', user_id: userId, roles: admin ? 'team_user team_admin' : 'team_user', scheme_admin: admin, }); } const user1 = createUser('userid1', 'user-1', false); const membership1 = createMembership('userId1', false); const user2 = createUser('userid2', 'user-2', false); const membership2 = createMembership('userId2', false); const notSavedUser = createUser('userid-not-saved', 'user-not-saved', false); const scope: 'team' | 'channel' = 'team'; const baseProps = { users: [user1, user2], memberships: {[user1.id]: membership1, [user2.id]: membership2}, excludeUsers: {}, includeUsers: {}, scope, loadPage: jest.fn(), onSearch: jest.fn(), removeUser: jest.fn(), updateMembership: jest.fn(), totalCount: 2, loading: false, term: '', filterProps: { options: {}, keys: [], onFilter: jest.fn(), }, }; test('should match snapshot with 2 users', () => { const wrapper = shallow( <UserGrid {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with 2 users and 1 added included', () => { const wrapper = shallow( <UserGrid {...baseProps} includeUsers={{[notSavedUser.id]: notSavedUser}} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with 2 users and 1 removed user', () => { const wrapper = shallow( <UserGrid {...baseProps} excludeUsers={{[user1.id]: user1}} />, ); expect(wrapper).toMatchSnapshot(); }); test('should return pagination props while taking into account added or removed users when getPaginationProps is called', () => { const wrapper = shallow( <UserGrid {...baseProps}/>, ); const userGrid = wrapper.instance() as UserGrid; let paginationProps = userGrid.getPaginationProps(); expect(paginationProps.startCount).toEqual(1); expect(paginationProps.endCount).toEqual(2); expect(paginationProps.total).toEqual(2); wrapper.setProps({includeUsers: {[notSavedUser.id]: notSavedUser}}); paginationProps = userGrid.getPaginationProps(); expect(paginationProps.startCount).toEqual(1); expect(paginationProps.endCount).toEqual(3); expect(paginationProps.total).toEqual(3); wrapper.setProps({includeUsers: {}, excludeUsers: {[user1.id]: user1}}); paginationProps = userGrid.getPaginationProps(); expect(paginationProps.startCount).toEqual(1); expect(paginationProps.endCount).toEqual(1); expect(paginationProps.total).toEqual(1); }); });
1,453
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/user_grid
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/user_grid/__snapshots__/user_grid.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/admin_console/user_grid/UserGrid should match snapshot with 2 users 1`] = ` <DataGrid columns={ Array [ Object { "field": "name", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.user_grid.name" />, "width": 3, }, Object { "field": "new", "fixed": true, "name": "", }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "overflow": "visible", }, Object { "field": "remove", "fixed": true, "name": "", "textAlign": "right", }, ] } endCount={2} filterProps={ Object { "keys": Array [], "onFilter": [Function], "options": Object {}, } } loading={false} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.user_grid.notFound" /> } previousPage={[Function]} rows={ Array [ Object { "cells": Object { "id": "userid1", "name": <UserGridName user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-1", } } />, "new": null, "remove": <UserGridRemove removeUser={[Function]} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-1", } } />, "role": <UserGridRoleDropdown handleUpdateMembership={[Function]} membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team", "user_id": "userId1", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-1", } } />, }, }, Object { "cells": Object { "id": "userid2", "name": <UserGridName user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, "new": null, "remove": <UserGridRemove removeUser={[Function]} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, "role": <UserGridRoleDropdown handleUpdateMembership={[Function]} membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team", "user_id": "userId2", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, }, }, ] } rowsContainerStyles={ Object { "minHeight": "160px", } } searchPlaceholder="" startCount={1} term="" total={2} /> `; exports[`components/admin_console/user_grid/UserGrid should match snapshot with 2 users and 1 added included 1`] = ` <DataGrid columns={ Array [ Object { "field": "name", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.user_grid.name" />, "width": 3, }, Object { "field": "new", "fixed": true, "name": "", }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "overflow": "visible", }, Object { "field": "remove", "fixed": true, "name": "", "textAlign": "right", }, ] } endCount={3} filterProps={ Object { "keys": Array [], "onFilter": [Function], "options": Object {}, } } loading={false} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.user_grid.notFound" /> } previousPage={[Function]} rows={ Array [ Object { "cells": Object { "id": "userid-not-saved", "name": <UserGridName user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid-not-saved", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-not-saved", } } />, "new": <Memo(Tag) className="NewUserBadge" text={ <Memo(MemoizedFormattedMessage) defaultMessage="New" id="admin.user_grid.new" /> } />, "remove": <UserGridRemove removeUser={[Function]} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid-not-saved", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-not-saved", } } />, "role": <UserGridRoleDropdown handleUpdateMembership={[Function]} membership={ Object { "scheme_admin": false, "scheme_user": true, "user_id": "userid-not-saved", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid-not-saved", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-not-saved", } } />, }, }, Object { "cells": Object { "id": "userid1", "name": <UserGridName user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-1", } } />, "new": null, "remove": <UserGridRemove removeUser={[Function]} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-1", } } />, "role": <UserGridRoleDropdown handleUpdateMembership={[Function]} membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team", "user_id": "userId1", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-1", } } />, }, }, Object { "cells": Object { "id": "userid2", "name": <UserGridName user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, "new": null, "remove": <UserGridRemove removeUser={[Function]} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, "role": <UserGridRoleDropdown handleUpdateMembership={[Function]} membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team", "user_id": "userId2", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, }, }, ] } rowsContainerStyles={ Object { "minHeight": "240px", } } searchPlaceholder="" startCount={1} term="" total={3} /> `; exports[`components/admin_console/user_grid/UserGrid should match snapshot with 2 users and 1 removed user 1`] = ` <DataGrid columns={ Array [ Object { "field": "name", "fixed": true, "name": <Memo(MemoizedFormattedMessage) defaultMessage="Name" id="admin.user_grid.name" />, "width": 3, }, Object { "field": "new", "fixed": true, "name": "", }, Object { "field": "role", "name": <Memo(MemoizedFormattedMessage) defaultMessage="Role" id="admin.user_grid.role" />, "overflow": "visible", }, Object { "field": "remove", "fixed": true, "name": "", "textAlign": "right", }, ] } endCount={1} filterProps={ Object { "keys": Array [], "onFilter": [Function], "options": Object {}, } } loading={false} nextPage={[Function]} onSearch={[Function]} page={0} placeholderEmpty={ <Memo(MemoizedFormattedMessage) defaultMessage="No users found" id="admin.user_grid.notFound" /> } previousPage={[Function]} rows={ Array [ Object { "cells": Object { "id": "userid2", "name": <UserGridName user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, "new": null, "remove": <UserGridRemove removeUser={[Function]} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, "role": <UserGridRoleDropdown handleUpdateMembership={[Function]} membership={ Object { "delete_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "roles": "team_user", "scheme_admin": false, "scheme_guest": false, "scheme_user": true, "team_id": "team", "user_id": "userId2", } } scope="team" user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "userid2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "user-2", } } />, }, }, ] } rowsContainerStyles={ Object { "minHeight": "80px", } } searchPlaceholder="" startCount={1} term="" total={1} /> `;
1,454
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/workspace-optimization/chips_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import ChipsList from 'components/admin_console/workspace-optimization/chips_list'; import type {ChipsInfoType} from 'components/admin_console/workspace-optimization/chips_list'; import {ItemStatus} from './dashboard.type'; describe('components/admin_console/workspace-optimization/chips_list', () => { const overallScoreChips: ChipsInfoType = { [ItemStatus.INFO]: 3, [ItemStatus.WARNING]: 2, [ItemStatus.ERROR]: 1, }; const baseProps = { chipsData: overallScoreChips, hideCountZeroChips: false, }; test('should match snapshot', () => { const wrapper = shallow(<ChipsList {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('test chips list lenght is 3 as defined in baseProps', () => { const wrapper = shallow(<ChipsList {...baseProps}/>); const chips = wrapper.find('Chip'); expect(chips.length).toBe(3); }); test('test chips list lenght is 2 if one of the properties count is 0 and the hide zero count value is TRUE', () => { const zeroErrorProps = { chipsData: {...overallScoreChips, [ItemStatus.ERROR]: 0}, hideCountZeroChips: true, }; const wrapper = shallow(<ChipsList {...zeroErrorProps}/>); const chips = wrapper.find('Chip'); expect(chips.length).toBe(2); }); test('test chips list lenght is 3 even if one of the properties count is 0 BUT the hide zero count value is FALSE', () => { const zeroErrorProps = { chipsData: {...overallScoreChips, [ItemStatus.ERROR]: 0}, hideCountZeroChips: false, }; const wrapper = shallow(<ChipsList {...zeroErrorProps}/>); const chips = wrapper.find('Chip'); expect(chips.length).toBe(3); }); });
1,456
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/workspace-optimization/cta_buttons.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 CtaButtons from 'components/admin_console/workspace-optimization/cta_buttons'; describe('components/admin_console/workspace-optimization/cta_buttons', () => { const baseProps = { learnMoreLink: '/learn_more', learnMoreText: 'Learn More', actionLink: '/action_link', actionText: 'Action Text', }; test('should match snapshot', () => { const wrapper = shallow(<CtaButtons {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('test ctaButtons list lenght is 3 as defined in baseProps', () => { const wrapper = shallow(<CtaButtons {...baseProps}/>); const ctaButtons = wrapper.find('button'); expect(ctaButtons.length).toBe(2); }); });
1,463
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/workspace-optimization
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/workspace-optimization/__snapshots__/chips_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/admin_console/workspace-optimization/chips_list should match snapshot 1`] = ` <Fragment> <Chip additionalMarkup={ <Memo(MemoizedFormattedMessage) defaultMessage="Suggestions: {count}" id="admin.reporting.workspace_optimization.chip_suggestions" values={ Object { "count": 3, } } /> } className="info" key="info" /> <Chip additionalMarkup={ <Memo(MemoizedFormattedMessage) defaultMessage="Warnings: {count}" id="admin.reporting.workspace_optimization.chip_warnings" values={ Object { "count": 2, } } /> } className="warning" key="warning" /> <Chip additionalMarkup={ <Memo(MemoizedFormattedMessage) defaultMessage="Problems: {count}" id="admin.reporting.workspace_optimization.chip_problems" values={ Object { "count": 1, } } /> } className="error" key="error" /> </Fragment> `;
1,464
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/workspace-optimization
petrpan-code/mattermost/mattermost/webapp/channels/src/components/admin_console/workspace-optimization/__snapshots__/cta_buttons.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/admin_console/workspace-optimization/cta_buttons should match snapshot 1`] = ` <div className="ctaButtons" > <button className="actionButton annnouncementBar__purchaseNow" onClick={[Function]} > Action Text </button> <button className="learnMoreButton light-blue-btn" onClick={[Function]} > Learn More </button> </div> `;
1,471
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_create_comment/advanced_create_comment.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 {ServerError} from '@mattermost/types/errors'; import type {FileInfo} from '@mattermost/types/files'; import type {ActionResult} from 'mattermost-redux/types/actions'; import type {Props} from 'components/advanced_create_comment/advanced_create_comment'; import AdvancedCreateComment from 'components/advanced_create_comment/advanced_create_comment'; import {testComponentForLineBreak} from 'tests/helpers/line_break_helpers'; import Constants, {ModalIdentifiers} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import type {PostDraft} from 'types/store/draft'; jest.mock('utils/exec_commands', () => ({ execCommandInsertText: jest.fn(), })); describe('components/AdvancedCreateComment', () => { jest.useFakeTimers(); let spy: jest.SpyInstance; beforeEach(() => { spy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => setTimeout(cb, 16)); }); afterEach(() => { spy.mockRestore(); }); const currentTeamId = 'current-team-id'; const channelId = 'g6139tbospd18cmxroesdk3kkc'; const rootId = ''; const latestPostId = '3498nv24823948v23m4nv34'; const currentUserId = 'zaktnt8bpbgu8mb6ez9k64r7sa'; const emptyDraft: PostDraft = TestHelper.getPostDraftMock({message: ''}); const defaultFileInfo: FileInfo = TestHelper.getFileInfoMock(); const baseProps: Props = { channelId, currentTeamId, currentUserId, rootId, rootDeleted: false, channelMembersCount: 3, draft: TestHelper.getPostDraftMock({ fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo], }), isRemoteDraft: false, enableAddButton: true, ctrlSend: false, latestPostId, locale: 'en', clearCommentDraftUploads: jest.fn(), onUpdateCommentDraft: jest.fn(), updateCommentDraftWithRootId: jest.fn(), onSubmit: jest.fn(), onResetHistoryIndex: jest.fn(), moveHistoryIndexBack: jest.fn(), moveHistoryIndexForward: jest.fn(), onEditLatestPost: jest.fn(), resetCreatePostRequest: jest.fn(), setShowPreview: jest.fn(), searchAssociatedGroupsForReference: jest.fn(), shouldShowPreview: false, enableEmojiPicker: true, enableGifPicker: true, enableConfirmNotificationsToChannel: true, maxPostSize: Constants.DEFAULT_CHARACTER_LIMIT, rhsExpanded: false, badConnection: false, getChannelTimezones: jest.fn(() => Promise.resolve({data: '', error: ''})), selectedPostFocussedAt: 0, canPost: true, canUploadFiles: true, isFormattingBarHidden: false, useChannelMentions: true, getChannelMemberCountsByGroup: jest.fn(), useLDAPGroupMentions: true, useCustomGroupMentions: true, openModal: jest.fn(), postEditorActions: [], emitShortcutReactToLastPostFrom(): void { throw new Error('Function not implemented.'); }, groupsWithAllowReference: null, channelMemberCountsByGroup: undefined as any, savePreferences(): ActionResult { throw new Error('Function not implemented.'); }, }; const submitEvent = { preventDefault: jest.fn(), } as unknown as React.FormEvent; test('should match snapshot, empty comment', () => { const draft: PostDraft = emptyDraft; const isRemoteDraft = false; const enableAddButton = false; const ctrlSend = true; const props: any = {...baseProps, draft, isRemoteDraft, enableAddButton, ctrlSend}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, comment with message', () => { const clearCommentDraftUploads = jest.fn(); const onResetHistoryIndex = jest.fn(); const getChannelMemberCountsByGroup = jest.fn(); const draft: PostDraft = TestHelper.getPostDraftMock(); const isRemoteDraft = false; const ctrlSend = true; const props: any = {...baseProps, ctrlSend, draft, isRemoteDraft, clearCommentDraftUploads, onResetHistoryIndex, getChannelMemberCountsByGroup}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); // should clear draft uploads on mount expect(clearCommentDraftUploads).toHaveBeenCalled(); // should reset message history index on mount expect(onResetHistoryIndex).toHaveBeenCalled(); // should load channel member counts on mount expect(getChannelMemberCountsByGroup).not.toHaveBeenCalled(); expect(wrapper).toMatchSnapshot(); }); test('should call searchAssociatedGroupsForReference if there is one mention in the draft', () => { const draft: PostDraft = TestHelper.getPostDraftMock({ message: '@group', }); const searchAssociatedGroupsForReference: any = jest.fn(); const props: any = {...baseProps, draft, searchAssociatedGroupsForReference}; shallow(<AdvancedCreateComment {...props}/>); expect(searchAssociatedGroupsForReference).toHaveBeenCalled(); }); test('should call getChannelMemberCountsByGroup if there is more than one mention in the draft', () => { const draft: PostDraft = TestHelper.getPostDraftMock({ message: '@group @othergroup', }); const getChannelMemberCountsByGroup = jest.fn(); const props: any = {...baseProps, draft, getChannelMemberCountsByGroup}; shallow(<AdvancedCreateComment {...props}/>); expect(getChannelMemberCountsByGroup).toHaveBeenCalled(); }); test('should not call getChannelMemberCountsByGroup, without group mentions permission or license', () => { const useLDAPGroupMentions = false; const useCustomGroupMentions = false; const draft: PostDraft = TestHelper.getPostDraftMock({ message: '@group @othergroup', }); const getChannelMemberCountsByGroup = jest.fn(); const props: any = {...baseProps, useLDAPGroupMentions, useCustomGroupMentions, getChannelMemberCountsByGroup, draft}; shallow<AdvancedCreateComment>(<AdvancedCreateComment {...props}/>); // should not load channel member counts on mount without useGroupmentions expect(getChannelMemberCountsByGroup).not.toHaveBeenCalled(); }); test('should match snapshot, non-empty message and uploadsInProgress + fileInfos', () => { const draft: PostDraft = TestHelper.getPostDraftMock(); const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); wrapper.setState({draft}); expect(wrapper).toMatchSnapshot(); }); test('should correctly change state when toggleEmojiPicker is called', () => { const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); wrapper.instance().toggleEmojiPicker(); expect(wrapper.state().showEmojiPicker).toBe(true); wrapper.instance().toggleEmojiPicker(); expect(wrapper.state().showEmojiPicker).toBe(false); }); test('should correctly change state when hideEmojiPicker is called', () => { const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); wrapper.instance().hideEmojiPicker(); expect(wrapper.state().showEmojiPicker).toBe(false); }); test('should correctly update draft when handleEmojiClick is called', () => { const onUpdateCommentDraft = jest.fn(); const draft: PostDraft = emptyDraft; const enableAddButton = false; const props: any = {...baseProps, draft, onUpdateCommentDraft, enableAddButton}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const mockImpl = () => { return { setSelectionRange: jest.fn(), getBoundingClientRect: jest.fn(mockTop), focus: jest.fn(), }; }; const mockTop = () => { return document.createElement('div'); }; (wrapper.instance() as any).textboxRef.current = {getInputBox: jest.fn(mockImpl), getBoundingClientRect: jest.fn(), focus: jest.fn()}; wrapper.instance().handleEmojiClick({name: 'smile'} as any); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(onUpdateCommentDraft).toHaveBeenCalled(); // Empty message case expect(onUpdateCommentDraft.mock.calls[0][0]).toEqual( expect.objectContaining({message: ':smile: '}), ); expect(wrapper.state().draft!.message).toBe(':smile: '); wrapper.setState({draft: TestHelper.getPostDraftMock({message: 'test', uploadsInProgress: [], fileInfos: []}), caretPosition: 'test'.length, // cursor is at the end }); wrapper.instance().handleEmojiClick({name: 'smile'} as any); // Message with no space at the end jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(onUpdateCommentDraft.mock.calls[1][0]).toEqual( expect.objectContaining({message: 'test :smile: '}), ); expect(wrapper.state().draft!.message).toBe('test :smile: '); wrapper.setState({draft: TestHelper.getPostDraftMock({message: 'test ', uploadsInProgress: [], fileInfos: []}), caretPosition: 'test '.length, // cursor is at the end }); wrapper.instance().handleEmojiClick({name: 'smile'} as any); // Message with space at the end jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(onUpdateCommentDraft.mock.calls[2][0]).toEqual( expect.objectContaining({message: 'test :smile: '}), ); expect(wrapper.state().draft!.message).toBe('test :smile: '); expect(wrapper.state().showEmojiPicker).toBe(false); }); test('handlePostError should update state with the correct error', () => { const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); wrapper.instance().handlePostError('test error 1'); expect(wrapper.state().postError).toBe('test error 1'); wrapper.instance().handlePostError('test error 2'); expect(wrapper.state().postError).toBe('test error 2'); }); // debug next test('handleUploadError should update state with the correct error', () => { const updateCommentDraftWithRootId = jest.fn(); const fileInfoObject: FileInfo = TestHelper.getFileInfoMock(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: 'Test message', uploadsInProgress: ['1', '2', '3'], fileInfos: [fileInfoObject, fileInfoObject, fileInfoObject], }); const props: any = {...baseProps, draft, updateCommentDraftWithRootId}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const instance = wrapper.instance(); const testError1 = 'test error 1'; wrapper.setState({draft}); instance.draftsForPost[props.rootId] = draft; instance.handleUploadError(testError1, '1', undefined, props.rootId); expect(updateCommentDraftWithRootId).toHaveBeenCalled(); expect(updateCommentDraftWithRootId.mock.calls[0][0]).toEqual(props.rootId); expect(updateCommentDraftWithRootId.mock.calls[0][1]).toEqual( expect.objectContaining({uploadsInProgress: ['2', '3']}), ); expect(wrapper.state().serverError!.message).toBe(testError1); expect(wrapper.state().draft!.uploadsInProgress).toEqual(['2', '3']); const testError2 = 'test error 2'; instance.handleUploadError(testError2, '', undefined, props.rootId); // should not call onUpdateCommentDraft expect(updateCommentDraftWithRootId.mock.calls.length).toBe(1); expect(wrapper.state().serverError!.message).toBe(testError2); }); test('should call openModal when showPostDeletedModal is called', () => { const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); wrapper.instance().showPostDeletedModal(); expect(baseProps.openModal).toHaveBeenCalledTimes(1); }); test('handleUploadStart should update comment draft correctly', () => { const onUpdateCommentDraft = jest.fn(); const draft: PostDraft = TestHelper.getPostDraftMock({ uploadsInProgress: ['1', '2', '3'], fileInfos: [TestHelper.getFileInfoMock(), TestHelper.getFileInfoMock(), TestHelper.getFileInfoMock()], }); const props: any = {...baseProps, onUpdateCommentDraft, draft}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const focusTextbox = jest.fn(); wrapper.setState({draft}); wrapper.instance().focusTextbox = focusTextbox; wrapper.instance().handleUploadStart(['4', '5']); expect(onUpdateCommentDraft).toHaveBeenCalled(); expect(onUpdateCommentDraft.mock.calls[0][0]).toEqual( expect.objectContaining({uploadsInProgress: ['1', '2', '3', '4', '5']}), ); expect(wrapper.state().draft!.uploadsInProgress).toEqual(['1', '2', '3', '4', '5']); expect(focusTextbox).toHaveBeenCalled(); }); test('handleFileUploadComplete should update comment draft correctly', () => { const updateCommentDraftWithRootId: any = jest.fn(); const fileInfos = [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'bbb', create_at: 200}), ]; const draft: PostDraft = TestHelper.getPostDraftMock({ uploadsInProgress: ['1', '2', '3'], fileInfos, }); const props: any = {...baseProps, updateCommentDraftWithRootId, draft}; const wrapper: any = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const instance: any = wrapper.instance(); wrapper.setState({draft}); instance.draftsForPost[props.rootId] = draft; const uploadCompleteFileInfo: any = [{id: '3', name: 'ccc', create_at: 300}]; const expectedNewFileInfos: any = fileInfos.concat(uploadCompleteFileInfo); instance.handleFileUploadComplete(uploadCompleteFileInfo, ['3'], null as any, props.rootId); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(updateCommentDraftWithRootId).toHaveBeenCalled(); expect(updateCommentDraftWithRootId.mock.calls[0][0]).toEqual(props.rootId); expect(updateCommentDraftWithRootId.mock.calls[0][1]).toEqual( expect.objectContaining({uploadsInProgress: ['1', '2'], fileInfos: expectedNewFileInfos}), ); expect(wrapper.state().draft!.uploadsInProgress).toEqual(['1', '2']); expect(wrapper.state().draft!.fileInfos).toEqual(expectedNewFileInfos); }); test('should open PostDeletedModal when createPostErrorId === api.post.create_post.root_id.app_error', () => { const onUpdateCommentDraft = jest.fn(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: 'Test message', uploadsInProgress: ['1', '2', '3'], fileInfos: [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'bbb', create_at: 200}), ], }); const props: any = {...baseProps, onUpdateCommentDraft, draft}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.setProps({createPostErrorId: 'api.post.create_post.root_id.app_error'}); expect(props.openModal).toHaveBeenCalledTimes(1); expect(props.openModal.mock.calls[0][0]).toMatchObject({ modalId: ModalIdentifiers.POST_DELETED_MODAL, }); }); test('should open PostDeletedModal when message is submitted to deleted root', () => { const onUpdateCommentDraft = jest.fn(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: 'Test message', uploadsInProgress: ['1', '2', '3'], fileInfos: [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'bbb', create_at: 200}), ], }); const props: any = {...baseProps, onUpdateCommentDraft, draft}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.setProps({rootDeleted: true}); wrapper.instance().handleSubmit(submitEvent); expect(props.openModal).toHaveBeenCalledTimes(1); expect(props.openModal.mock.calls[0][0]).toMatchObject({ modalId: ModalIdentifiers.POST_DELETED_MODAL, }); }); describe('focusTextbox', () => { const draft: PostDraft = TestHelper.getPostDraftMock({ uploadsInProgress: ['1', '2', '3'], fileInfos: [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'bbb', create_at: 200}), ], }); it('is called when rootId changes', () => { const props: any = {...baseProps, draft}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const focusTextbox = jest.fn(); wrapper.instance().focusTextbox = focusTextbox; const newProps = { ...props, rootId: 'testid123', }; // Note that setProps doesn't actually trigger componentDidUpdate wrapper.setProps(newProps); wrapper.instance().componentDidUpdate(props, newProps); expect(focusTextbox).toHaveBeenCalled(); }); it('is called when selectPostFocussedAt changes', () => { const props: any = {...baseProps, draft, selectedPostFocussedAt: 1000}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const focusTextbox = jest.fn(); wrapper.instance().focusTextbox = focusTextbox; const newProps = { ...props, selectedPostFocussedAt: 2000, }; // Note that setProps doesn't actually trigger componentDidUpdate wrapper.setProps(newProps); wrapper.instance().componentDidUpdate(props, props); expect(focusTextbox).toHaveBeenCalled(); }); it('is not called when rootId and selectPostFocussedAt have not changed', () => { const props: any = {...baseProps, draft, selectedPostFocussedAt: 1000}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const focusTextbox = jest.fn(); wrapper.instance().focusTextbox = focusTextbox; wrapper.instance().handleBlur(); // Note that setProps doesn't actually trigger componentDidUpdate wrapper.setProps(props); wrapper.instance().componentDidUpdate(props, props); expect(focusTextbox).not.toHaveBeenCalled(); }); }); test('handleChange should update comment draft correctly', () => { const draft: PostDraft = TestHelper.getPostDraftMock({ uploadsInProgress: ['1', '2', '3'], fileInfos: [TestHelper.getFileInfoMock(), TestHelper.getFileInfoMock(), TestHelper.getFileInfoMock()], }); const scrollToBottom = jest.fn(); const props: any = {...baseProps, draft, scrollToBottom}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props} />, ); const testMessage = 'new msg'; wrapper.instance().handleChange({target: {value: testMessage}} as any); // The callback won't we called until after a short delay expect(baseProps.onUpdateCommentDraft).not.toHaveBeenCalled(); jest.runOnlyPendingTimers(); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(baseProps.onUpdateCommentDraft).toHaveBeenCalled(); expect((baseProps.onUpdateCommentDraft as jest.Mock).mock.calls[0][0]).toEqual( expect.objectContaining({message: testMessage}), ); expect(wrapper.state().draft!.message).toBe(testMessage); expect(scrollToBottom).toHaveBeenCalled(); }); // debug it('handleChange should throw away invalid command error if user resumes typing', async () => { const onUpdateCommentDraft = jest.fn(); const error: ServerError = {message: 'No command found'}; error.server_error_id = 'api.command.execute_command.not_found.app_error'; const onSubmit = jest.fn(() => Promise.reject(error)); const defaultFileInfo = TestHelper.getFileInfoMock(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: '/fakecommand other text', uploadsInProgress: ['1', '2', '3'], fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo], }); const props: any = {...baseProps, onUpdateCommentDraft, draft, onSubmit}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); await wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalledWith(TestHelper.getPostDraftMock({ message: '/fakecommand other text', uploadsInProgress: [], fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo], }), {ignoreSlash: false}); wrapper.instance().handleChange({ target: {value: 'some valid text'}, } as any); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalledWith(TestHelper.getPostDraftMock({ message: 'some valid text', uploadsInProgress: [], fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo], }), {ignoreSlash: false}); }); test('should scroll to bottom when uploadsInProgress increase', () => { const draft: PostDraft = TestHelper.getPostDraftMock({ uploadsInProgress: ['1', '2', '3'], fileInfos: [TestHelper.getFileInfoMock(), TestHelper.getFileInfoMock(), TestHelper.getFileInfoMock()], }); const scrollToBottom = jest.fn(); const props: any = {...baseProps, draft, scrollToBottom}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props} />, ); wrapper.setState({draft: {...draft, uploadsInProgress: ['1', '2', '3', '4']}}); expect(scrollToBottom).toHaveBeenCalled(); }); test('handleSubmit should call onSubmit prop', () => { const onSubmit = jest.fn(); const defaultFileInfo = TestHelper.getFileInfoMock(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: 'Test message', uploadsInProgress: [], fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo], }); const props: any = {...baseProps, draft, onSubmit}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const preventDefault = jest.fn(); wrapper.instance().handleSubmit({...submitEvent, preventDefault}); expect(onSubmit).toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); }); describe('handleSubmit', () => { let onSubmit: any; let preventDefault: any; beforeEach(() => { onSubmit = jest.fn(); preventDefault = jest.fn(); submitEvent.preventDefault = preventDefault; }); ['channel', 'all', 'here'].forEach((mention: string) => { describe(`should not show Confirm Modal for @${mention} mentions`, () => { it('when channel member count too low', () => { const props: any = { ...baseProps, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, channelMembersCount: 1, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(props.openModal).not.toHaveBeenCalled(); }); it('when feature disabled', () => { const props: any = { ...baseProps, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, channelMembersCount: 8, enableConfirmNotificationsToChannel: false, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(props.openModal).not.toHaveBeenCalled(); }); it('when no mention', () => { const props: any = { ...baseProps, draft: { message: `Test message ${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, channelMembersCount: 8, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(props.openModal).not.toHaveBeenCalled(); }); it('when user has insufficient permissions', () => { const props: any = { ...baseProps, useChannelMentions: false, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, channelMembersCount: 8, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(props.openModal).not.toHaveBeenCalled(); }); }); it(`should show Confirm Modal for @${mention} mentions when needed and timezone notification`, async () => { const props: any = { ...baseProps, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, channelMembersCount: 8, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); await wrapper.instance().handleSubmit(submitEvent); wrapper.setState({channelTimezoneCount: 4} as any); expect(onSubmit).not.toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(wrapper.state('channelTimezoneCount')).toBe(4); expect(baseProps.getChannelTimezones).toHaveBeenCalledTimes(1); expect(props.openModal).toHaveBeenCalled(); }); it(`should show Confirm Modal for @${mention} mentions when needed and no timezone notification`, async () => { const props: any = { ...baseProps, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, channelMembersCount: 8, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); await wrapper.instance().handleSubmit(submitEvent); wrapper.setState({channelTimezoneCount: 0} as any); expect(onSubmit).not.toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(wrapper.state('channelTimezoneCount')).toBe(0); expect(baseProps.getChannelTimezones).toHaveBeenCalledTimes(1); expect(props.openModal).toHaveBeenCalled(); }); }); it('should show Confirm Modal for @group mention when needed and no timezone notification', async () => { const props: any = { ...baseProps, draft: { message: 'Test message @developers', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, groupsWithAllowReference: new Map([ ['@developers', { id: 'developers', name: 'developers', }], ]), channelMemberCountsByGroup: { developers: { channel_member_count: 10, channel_member_timezones_count: 0, }, }, channelMembersCount: 8, useChannelMentions: true, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const showNotifyAllModal = wrapper.instance().showNotifyAllModal; wrapper.instance().showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); await wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).not.toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(baseProps.getChannelTimezones).toHaveBeenCalledTimes(0); expect(wrapper.instance().showNotifyAllModal).toHaveBeenCalledWith(['@developers'], 0, 10); expect(props.openModal).toHaveBeenCalled(); }); it('should show Confirm Modal for @group mentions when needed and no timezone notification', async () => { const props: any = { ...baseProps, draft: { message: 'Test message @developers @boss @love @you @software-developers', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, groupsWithAllowReference: new Map([ ['@developers', { id: 'developers', name: 'developers', }], ['@boss', { id: 'boss', name: 'boss', }], ['@love', { id: 'love', name: 'love', }], ['@you', { id: 'you', name: 'you', }], ['@software-developers', { id: 'softwareDevelopers', name: 'software-developers', }], ]), channelMemberCountsByGroup: { developers: { channel_member_count: 10, channel_member_timezones_count: 0, }, boss: { channel_member_count: 20, channel_member_timezones_count: 0, }, love: { channel_member_count: 30, channel_member_timezones_count: 0, }, you: { channel_member_count: 40, channel_member_timezones_count: 0, }, softwareDevelopers: { channel_member_count: 5, channel_member_timezones_count: 0, }, }, channelMembersCount: 8, useChannelMentions: true, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const showNotifyAllModal = wrapper.instance().showNotifyAllModal; wrapper.instance().showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); await wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).not.toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(baseProps.getChannelTimezones).toHaveBeenCalledTimes(0); expect(wrapper.instance().showNotifyAllModal).toHaveBeenCalledWith(['@developers', '@boss', '@love', '@you', '@software-developers'], 0, 40); expect(props.openModal).toHaveBeenCalled(); }); it('should show Confirm Modal for @group mention with timezone enabled', async () => { const props: any = { ...baseProps, draft: { message: 'Test message @developers', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, groupsWithAllowReference: new Map([ ['@developers', { id: 'developers', name: 'developers', }], ]), channelMemberCountsByGroup: { developers: { channel_member_count: 10, channel_member_timezones_count: 5, }, }, channelMembersCount: 8, useChannelMentions: true, enableConfirmNotificationsToChannel: true, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const showNotifyAllModal = wrapper.instance().showNotifyAllModal; wrapper.instance().showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); await wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).not.toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(baseProps.getChannelTimezones).toHaveBeenCalledTimes(0); expect(wrapper.instance().showNotifyAllModal).toHaveBeenCalledWith(['@developers'], 5, 10); expect(props.openModal).toHaveBeenCalled(); }); it('should allow to force send invalid slash command as a message', async () => { const error: ServerError = {message: 'No command found'}; error.server_error_id = 'api.command.execute_command.not_found.app_error'; const onSubmitWithError = jest.fn(() => Promise.reject(error)); const props: any = { ...baseProps, draft: { message: '/fakecommand other text', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit: onSubmitWithError, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); await wrapper.instance().handleSubmit(submitEvent); expect(onSubmitWithError).toHaveBeenCalledWith({ message: '/fakecommand other text', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, {ignoreSlash: false}); expect(preventDefault).toHaveBeenCalled(); wrapper.setProps({onSubmit}); await wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalledWith({ message: '/fakecommand other text', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, {ignoreSlash: true}); expect(wrapper.find('[id="postServerError"]').exists()).toBe(false); }); it('should update global draft state if invalid slash command error occurs', async () => { const error: ServerError = {message: 'No command found'}; error.server_error_id = 'api.command.execute_command.not_found.app_error'; const onSubmitWithError = jest.fn(() => Promise.reject(error)); const props: any = { ...baseProps, draft: { message: '/fakecommand other text', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit: onSubmitWithError, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); const submitPromise = wrapper.instance().handleSubmit(submitEvent); expect(props.onUpdateCommentDraft).not.toHaveBeenCalled(); await submitPromise; expect(props.onUpdateCommentDraft).toHaveBeenCalledWith(props.draft); }); ['channel', 'all', 'here'].forEach((mention) => { it(`should set mentionHighlightDisabled when user does not have permission and message contains channel @${mention}`, async () => { const props: any = { ...baseProps, useChannelMentions: false, enableConfirmNotificationsToChannel: false, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(wrapper.state('draft')!.props.mentionHighlightDisabled).toBe(true); }); it(`should not set mentionHighlightDisabled when user does have permission and message contains channel channel @${mention}`, async () => { const props: any = { ...baseProps, useChannelMentions: true, enableConfirmNotificationsToChannel: false, draft: { message: `Test message @${mention}`, uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(wrapper.state('draft')!.props).toBe(undefined); }); }); it('should not set mentionHighlightDisabled when user does not have useChannelMentions permission and message contains no mention', async () => { const props: any = { ...baseProps, useChannelMentions: false, draft: { message: 'Test message', uploadsInProgress: [], fileInfos: [{}, {}, {}], }, onSubmit, }; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.instance().handleSubmit(submitEvent); expect(onSubmit).toHaveBeenCalled(); expect(wrapper.state('draft')!.props).toBe(undefined); }); }); test('removePreview should remove file info and upload in progress with corresponding id', () => { const onUpdateCommentDraft = jest.fn(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: 'Test message', uploadsInProgress: ['4', '5', '6'], fileInfos: [ TestHelper.getFileInfoMock({id: '1'}), TestHelper.getFileInfoMock({id: '2'}), TestHelper.getFileInfoMock({id: '3'}), ], }); const props: any = {...baseProps, draft, onUpdateCommentDraft}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); wrapper.setState({draft}); wrapper.instance().removePreview('3'); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(onUpdateCommentDraft).toHaveBeenCalled(); expect(onUpdateCommentDraft.mock.calls[0][0]).toEqual( expect.objectContaining({fileInfos: [ TestHelper.getFileInfoMock({id: '1'}), TestHelper.getFileInfoMock({id: '2'}), ]}), ); expect(wrapper.state().draft!.fileInfos).toEqual([ TestHelper.getFileInfoMock({id: '1'}), TestHelper.getFileInfoMock({id: '2'}), ]); wrapper.instance().removePreview('5'); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(onUpdateCommentDraft.mock.calls[1][0]).toEqual( expect.objectContaining({uploadsInProgress: ['4', '6']}), ); expect(wrapper.state().draft!.uploadsInProgress).toEqual(['4', '6']); }); test('should match draft state on componentWillReceiveProps with change in messageInHistory', () => { const draft: PostDraft = TestHelper.getPostDraftMock({ fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo], }); const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); expect(wrapper.state('draft')).toEqual(draft); const newDraft: PostDraft = TestHelper.getPostDraftMock({...draft, message: 'Test message edited'}); wrapper.setProps({draft: newDraft, messageInHistory: 'Test message edited'}); expect(wrapper.state('draft')).toEqual(newDraft); }); test('should match draft state on componentWillReceiveProps with new rootId', () => { const defaultFileInfo = TestHelper.getFileInfoMock(); const draft: PostDraft = TestHelper.getPostDraftMock({ message: 'Test message', uploadsInProgress: ['4', '5', '6'], fileInfos: [ TestHelper.getFileInfoMock({id: '1'}), TestHelper.getFileInfoMock({id: '2'}), TestHelper.getFileInfoMock({id: '3'}), ], }); const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); wrapper.setState({draft}); expect(wrapper.state('draft')).toEqual(draft); wrapper.setProps({rootId: 'new_root_id'}); expect(wrapper.state('draft')).toEqual(TestHelper.getPostDraftMock({...draft, uploadsInProgress: [], fileInfos: [defaultFileInfo, defaultFileInfo, defaultFileInfo]})); }); test('should match snapshot when cannot post', () => { const props: any = {...baseProps, canPost: false}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, emoji picker disabled', () => { const props: any = {...baseProps, enableEmojiPicker: false}; const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('check for handleFileUploadChange callback for focus', () => { const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); const instance = wrapper.instance(); instance.focusTextbox = jest.fn(); instance.handleFileUploadChange(); expect(instance.focusTextbox).toHaveBeenCalledTimes(1); }); test('should the RHS thread scroll to bottom one time after mount when props.draft.message is not empty', () => { const draft: PostDraft = emptyDraft; const scrollToBottom = jest.fn(); const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps} scrollToBottom={scrollToBottom} />, ); expect(scrollToBottom).toBeCalledTimes(0); expect(wrapper.instance().doInitialScrollToBottom).toEqual(true); // should scroll to bottom on first component update wrapper.setState({draft: {...draft, message: 'new message'}}); expect(scrollToBottom).toBeCalledTimes(1); expect(wrapper.instance().doInitialScrollToBottom).toEqual(false); // but not after the first update wrapper.setState({draft: {...draft, message: 'another message'}}); expect(scrollToBottom).toBeCalledTimes(1); expect(wrapper.instance().doInitialScrollToBottom).toEqual(false); }); test('should the RHS thread scroll to bottom when state.draft.uploadsInProgress increases but not when it decreases', () => { const draft: PostDraft = emptyDraft; const scrollToBottom = jest.fn(); const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps} draft={draft} scrollToBottom={scrollToBottom} />, ); expect(scrollToBottom).toBeCalledTimes(0); wrapper.setState({draft: {...draft, uploadsInProgress: ['1']}}); expect(scrollToBottom).toBeCalledTimes(1); wrapper.setState({draft: {...draft, uploadsInProgress: ['1', '2']}}); expect(scrollToBottom).toBeCalledTimes(2); wrapper.setState({draft: {...draft, uploadsInProgress: ['2']}}); expect(scrollToBottom).toBeCalledTimes(2); }); test('should show preview and edit mode, and return focus on preview disable', () => { const wrapper = shallow<AdvancedCreateComment>( <AdvancedCreateComment {...baseProps}/>, ); const instance = wrapper.instance(); instance.focusTextbox = jest.fn(); expect(instance.focusTextbox).not.toBeCalled(); instance.setShowPreview(true); expect(baseProps.setShowPreview).toHaveBeenCalledWith(true); expect(instance.focusTextbox).not.toBeCalled(); wrapper.setProps({shouldShowPreview: true}); expect(instance.focusTextbox).not.toBeCalled(); wrapper.setProps({shouldShowPreview: false}); expect(instance.focusTextbox).toBeCalled(); }); testComponentForLineBreak((value: any) => ( <AdvancedCreateComment {...baseProps} draft={{ ...baseProps.draft, message: value, }} ctrlSend={true} /> ), (instance: any) => instance.state().draft.message, false); });
1,474
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_create_comment
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_create_comment/__snapshots__/advanced_create_comment.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/AdvancedCreateComment should match snapshot when cannot post 1`] = ` <form onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={false} canUploadFiles={true} caretPosition={12} channelId="g6139tbospd18cmxroesdk3kkc" ctrlSend={false} currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, ], "message": "Test message", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="RHS_COMMENT" maxPostSize={4000} message="Test message" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} removePreview={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/AdvancedCreateComment should match snapshot, comment with message 1`] = ` <form onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={true} caretPosition={12} channelId="g6139tbospd18cmxroesdk3kkc" ctrlSend={true} currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "Test message", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="RHS_COMMENT" maxPostSize={4000} message="Test message" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} removePreview={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/AdvancedCreateComment should match snapshot, emoji picker disabled 1`] = ` <form onSubmit={[Function]} > <FileLimitStickyBanner /> <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={true} caretPosition={12} channelId="g6139tbospd18cmxroesdk3kkc" ctrlSend={false} currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, ], "message": "Test message", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={false} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="RHS_COMMENT" maxPostSize={4000} message="Test message" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} removePreview={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/AdvancedCreateComment should match snapshot, empty comment 1`] = ` <form onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={true} caretPosition={0} channelId="g6139tbospd18cmxroesdk3kkc" ctrlSend={true} currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="RHS_COMMENT" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} removePreview={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/AdvancedCreateComment should match snapshot, non-empty message and uploadsInProgress + fileInfos 1`] = ` <form onSubmit={[Function]} > <FileLimitStickyBanner /> <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={true} caretPosition={12} channelId="g6139tbospd18cmxroesdk3kkc" ctrlSend={false} currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "jpg", "has_preview_image": true, "height": 200, "id": "file_info_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, }, ], "message": "Test message", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="RHS_COMMENT" maxPostSize={4000} message="Test message" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} removePreview={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `;
1,475
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_create_post/advanced_create_post.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 {ChannelMemberCountsByGroup} from '@mattermost/types/channels'; import type {CommandArgs} from '@mattermost/types/integrations'; import type {Post} from '@mattermost/types/posts'; import {PostPriority} from '@mattermost/types/posts'; import type {ActionResult} from 'mattermost-redux/types/actions'; import AdvancedCreatePost from 'components/advanced_create_post/advanced_create_post'; import type {Props} from 'components/advanced_create_post/advanced_create_post'; import type {TextboxElement} from 'components/textbox'; import {testComponentForLineBreak} from 'tests/helpers/line_break_helpers'; import Constants, {StoragePrefixes, ModalIdentifiers} from 'utils/constants'; import EmojiMap from 'utils/emoji_map'; import {TestHelper} from 'utils/test_helper'; jest.mock('actions/global_actions', () => ({ emitLocalUserTypingEvent: jest.fn(), emitUserPostedEvent: jest.fn(), })); jest.mock('actions/post_actions', () => ({ createPost: jest.fn(() => { return new Promise<void>((resolve) => { process.nextTick(() => resolve()); }); }), })); jest.mock('utils/exec_commands', () => ({ execCommandInsertText: jest.fn(), })); const currentTeamIdProp = 'r7rws4y7ppgszym3pdd5kaibfa'; const currentUserIdProp = 'zaktnt8bpbgu8mb6ez9k64r7sa'; const showSendTutorialTipProp = false; const fullWidthTextBoxProp = true; const latestReplyablePostIdProp = 'a'; const localeProp = 'en'; const currentChannelProp = TestHelper.getChannelMock({ id: 'owsyt8n43jfxjpzh9np93mx1wa', type: 'O', }); const currentChannelMembersCountProp = 9; const draftProp = TestHelper.getPostDraftMock({ fileInfos: [], message: '', uploadsInProgress: [], }); const ctrlSendProp = false; const currentUsersLatestPostProp = TestHelper.getPostMock({id: 'b', root_id: 'a', channel_id: currentChannelProp.id}); const baseProp: Props = { currentTeamId: currentTeamIdProp, currentChannelMembersCount: currentChannelMembersCountProp, currentChannel: currentChannelProp, currentUserId: currentUserIdProp, showSendTutorialTip: showSendTutorialTipProp, fullWidthTextBox: fullWidthTextBoxProp, draft: draftProp, isRemoteDraft: false, latestReplyablePostId: latestReplyablePostIdProp, locale: localeProp, actions: { addMessageIntoHistory: jest.fn(), moveHistoryIndexBack: jest.fn(), moveHistoryIndexForward: jest.fn(), submitReaction: jest.fn(), addReaction: jest.fn(), removeReaction: jest.fn(), clearDraftUploads: jest.fn(), onSubmitPost: jest.fn(), selectPostFromRightHandSideSearchByPostId: jest.fn(), setDraft: jest.fn(), setEditingPost: jest.fn(), openModal: jest.fn(), setShowPreview: jest.fn(), savePreferences: jest.fn(), executeCommand: () => { return {data: true}; }, getChannelTimezones: jest.fn(() => { return {data: '', error: ''}; }), runMessageWillBePostedHooks: (post: Post) => { return {data: post}; }, runSlashCommandWillBePostedHooks: (message: string, args: CommandArgs) => { return {data: {message, args}}; }, scrollPostListToBottom: jest.fn(), getChannelMemberCountsByGroup: jest.fn(), emitShortcutReactToLastPostFrom: jest.fn(), searchAssociatedGroupsForReference: jest.fn(), }, ctrlSend: ctrlSendProp, currentUsersLatestPost: currentUsersLatestPostProp, canUploadFiles: false, emojiMap: new EmojiMap(new Map()), enableEmojiPicker: true, enableGifPicker: true, useLDAPGroupMentions: true, useCustomGroupMentions: true, canPost: true, isPostPriorityEnabled: false, enableConfirmNotificationsToChannel: true, maxPostSize: Constants.DEFAULT_CHARACTER_LIMIT, userIsOutOfOffice: false, rhsExpanded: false, rhsOpen: false, badConnection: false, shouldShowPreview: false, useChannelMentions: true, isFormattingBarHidden: false, groupsWithAllowReference: null, channelMemberCountsByGroup: [] as unknown as ChannelMemberCountsByGroup, postEditorActions: [], }; const submitEvent = { preventDefault: jest.fn(), } as unknown as React.FormEvent; function advancedCreatePost(props?: Partial<Props>) { const allProps: Props = {...baseProp, ...props}; return ( <AdvancedCreatePost {...allProps}/> ); } describe('components/advanced_create_post', () => { jest.useFakeTimers({legacyFakeTimers: true}); let spy: jest.SpyInstance; beforeEach(() => { spy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => setTimeout(cb, 16)); }); afterEach(() => { spy.mockRestore(); }); it('should match snapshot, init', () => { const wrapper = shallow(advancedCreatePost({})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot for center textbox', () => { const wrapper = shallow(advancedCreatePost({fullWidthTextBox: false})); expect(wrapper.find('#create_post').hasClass('center')).toBe(true); expect(wrapper).toMatchSnapshot(); }); it('should call clearDraftUploads on mount', () => { const clearDraftUploads = jest.fn(); const actions = { ...baseProp.actions, clearDraftUploads, }; shallow(advancedCreatePost({actions})); expect(clearDraftUploads).toHaveBeenCalled(); }); it('Check for state change on channelId change with useLDAPGroupMentions = true', () => { const wrapper = shallow(advancedCreatePost({})); const draft = { ...draftProp, message: 'test', }; expect(wrapper.state('message')).toBe(''); wrapper.setProps({draft}); expect(wrapper.state('message')).toBe(''); wrapper.setProps({ currentChannel: { ...currentChannelProp, id: 'owsyt8n43jfxjpzh9np93mx1wb', }, }); expect(wrapper.state('message')).toBe('test'); }); it('Check for searchAssociatedGroupsForReference not called on mount when no mentions in the draft', () => { const searchAssociatedGroupsForReference = jest.fn(); const draft = { ...draftProp, message: 'hello', }; const actions = { ...baseProp.actions, searchAssociatedGroupsForReference, }; const wrapper = shallow(advancedCreatePost({draft, actions})); expect(searchAssociatedGroupsForReference).not.toHaveBeenCalled(); wrapper.setProps({ currentChannel: { ...currentChannelProp, id: 'owsyt8n43jfxjpzh9np93mx1wb', }, }); expect(searchAssociatedGroupsForReference).not.toHaveBeenCalled(); }); it('Check for searchAssociatedGroupsForReference called on mount when one @ mention in the draft', () => { const searchAssociatedGroupsForReference = jest.fn(); const draft = { ...draftProp, message: '@group1 hello', }; const actions = { ...baseProp.actions, searchAssociatedGroupsForReference, }; const wrapper = shallow(advancedCreatePost({draft, actions})); expect(searchAssociatedGroupsForReference).toHaveBeenCalled(); wrapper.setProps({ currentChannel: { ...currentChannelProp, id: 'owsyt8n43jfxjpzh9np93mx1wb', }, }); expect(searchAssociatedGroupsForReference).toHaveBeenCalled(); }); it('Check for getChannelMemberCountsByGroup called on mount when more than one @ mention in the draft', () => { const getChannelMemberCountsByGroup = jest.fn(); const draft = { ...draftProp, message: '@group1 @group2 hello', }; const actions = { ...baseProp.actions, getChannelMemberCountsByGroup, }; const wrapper = shallow(advancedCreatePost({draft, actions})); expect(getChannelMemberCountsByGroup).toHaveBeenCalled(); wrapper.setProps({ currentChannel: { ...currentChannelProp, id: 'owsyt8n43jfxjpzh9np93mx1wb', }, }); expect(getChannelMemberCountsByGroup).toHaveBeenCalled(); }); it('Check for getChannelMemberCountsByGroup not called on mount and when channel changed with useLDAPGroupMentions = false', () => { const getChannelMemberCountsByGroup = jest.fn(); const useLDAPGroupMentions = false; const actions = { ...baseProp.actions, getChannelMemberCountsByGroup, }; const wrapper = shallow(advancedCreatePost({actions, useLDAPGroupMentions})); expect(getChannelMemberCountsByGroup).not.toHaveBeenCalled(); wrapper.setProps({ currentChannel: { ...currentChannelProp, id: 'owsyt8n43jfxjpzh9np93mx1wb', }, }); expect(getChannelMemberCountsByGroup).not.toHaveBeenCalled(); }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('click toggleEmojiPicker', () => { // const wrapper = shallow(advancedCreatePost()); // console.log('### debug', wrapper.debug()); // wrapper.find('button[aria-label="select an emoji"]').simulate('click'); // expect(wrapper.state('showEmojiPicker')).toBe(true); // wrapper.find('.emoji-picker__container').simulate('click'); // wrapper.find('EmojiPickerOverlay').prop('onHide')(); // expect(wrapper.state('showEmojiPicker')).toBe(false); // }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('Check for emoji click message states', () => { // const wrapper = shallow(advancedCreatePost()); // const mockImpl = () => { // return { // setSelectionRange: jest.fn(), // focus: jest.fn(), // }; // }; // wrapper.instance().textboxRef.current = {getInputBox: jest.fn(mockImpl), focus: jest.fn(), blur: jest.fn()}; // // wrapper.find('.emoji-picker__container').simulate('click'); // expect(wrapper.state('showEmojiPicker')).toBe(true); // // wrapper.instance().handleEmojiClick({name: 'smile'}); // expect(wrapper.state('message')).toBe(':smile: '); // // wrapper.setState({ // message: 'test', // caretPosition: 'test'.length, // cursor is at the end // }); // // wrapper.instance().handleEmojiClick({name: 'smile'}); // expect(wrapper.state('message')).toBe('test :smile: '); // // wrapper.setState({ // message: 'test ', // }); // // wrapper.instance().handleEmojiClick({name: 'smile'}); // expect(wrapper.state('message')).toBe('test :smile: '); // }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('onChange textbox should call setDraft and change message state', () => { // const setDraft = jest.fn(); // const draft = { // ...draftProp, // message: 'change', // }; // // const wrapper = shallow( // advancedCreatePost({ // actions: { // ...baseProp.actions, // setDraft, // }, // }), // ); // // const postTextbox = wrapper.find('#post_textbox'); // postTextbox.simulate('change', {target: {value: 'change'}}); // expect(setDraft).not.toHaveBeenCalled(); // jest.runOnlyPendingTimers(); // expect(setDraft).toHaveBeenCalledWith(StoragePrefixes.DRAFT + currentChannelProp.id, draft); // }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('onKeyPress textbox should call emitLocalUserTypingEvent', () => { // const wrapper = shallow(advancedCreatePost()); // wrapper.instance().textboxRef.current = {blur: jest.fn()}; // // const postTextbox = wrapper.find('#post_textbox'); // postTextbox.simulate('KeyPress', {key: Constants.KeyCodes.ENTER[0], preventDefault: jest.fn(), persist: jest.fn()}); // expect(GlobalActions.emitLocalUserTypingEvent).toHaveBeenCalledWith(currentChannelProp.id, ''); // }); it('onSubmit test for @all', async () => { const result: ActionResult = { data: [1, 2, 3, 4], }; const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, getChannelTimezones: jest.fn(() => result), }, currentChannelMembersCount: 9, }), ); wrapper.setState({ message: 'test @all', }); const instance = wrapper.instance() as AdvancedCreatePost; const showNotifyAllModal = instance.showNotifyAllModal; instance.showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); const form = wrapper.find('#create_post'); await form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalledTimes(1); expect(instance.showNotifyAllModal).toHaveBeenCalledWith(['@all'], 4, 8); wrapper.setProps({ currentChannelMembersCount: 2, }); form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalledTimes(1); }); it('onSubmit test for @here', async () => { const result: ActionResult = { data: [1, 2, 3, 4], }; const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, getChannelTimezones: jest.fn(() => result), }, currentChannelMembersCount: 9, }), ); wrapper.setState({ message: 'test @here', }); const instance = wrapper.instance() as AdvancedCreatePost; const showNotifyAllModal = instance.showNotifyAllModal; instance.showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); const form = wrapper.find('#create_post'); await form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalledTimes(1); expect(instance.showNotifyAllModal).toHaveBeenCalledWith(['@here'], 4, 8); wrapper.setProps({ currentChannelMembersCount: 2, }); form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalledTimes(1); }); it('onSubmit test for @groups', () => { const wrapper = shallow(advancedCreatePost()); wrapper.setProps({ groupsWithAllowReference: new Map([ ['@developers', { id: 'developers', name: 'developers', }], ]), channelMemberCountsByGroup: { developers: { channel_member_count: 10, channel_member_timezones_count: 0, }, }, }); wrapper.setState({ message: '@developers', }); const instance = wrapper.instance() as AdvancedCreatePost; const showNotifyAllModal = (instance).showNotifyAllModal; instance.showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); const form = wrapper.find('#create_post'); form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalled(); expect(instance.showNotifyAllModal).toHaveBeenCalledWith(['@developers'], 0, 10); }); it('onSubmit test for several @groups', () => { const wrapper = shallow(advancedCreatePost()); wrapper.setProps({ groupsWithAllowReference: new Map([ ['@developers', { id: 'developers', name: 'developers', }], ['@boss', { id: 'boss', name: 'boss', }], ['@love', { id: 'love', name: 'love', }], ['@you', { id: 'you', name: 'you', }], ['@software-developers', { id: 'softwareDevelopers', name: 'software-developers', }], ]), channelMemberCountsByGroup: { developers: { channel_member_count: 10, channel_member_timezones_count: 0, }, boss: { channel_member_count: 20, channel_member_timezones_count: 0, }, love: { channel_member_count: 30, channel_member_timezones_count: 0, }, you: { channel_member_count: 40, channel_member_timezones_count: 0, }, softwareDevelopers: { channel_member_count: 5, channel_member_timezones_count: 0, }, }, }); wrapper.setState({ message: '@developers @boss @love @you @software-developers', }); const instance = wrapper.instance() as AdvancedCreatePost; const showNotifyAllModal = instance.showNotifyAllModal; instance.showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); const form = wrapper.find('#create_post'); form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalled(); expect(instance.showNotifyAllModal).toHaveBeenCalledWith(['@developers', '@boss', '@love', '@you', '@software-developers'], 0, 40); }); it('onSubmit test for several @groups with timezone', () => { const wrapper = shallow(advancedCreatePost()); wrapper.setProps({ groupsWithAllowReference: new Map([ ['@developers', { id: 'developers', name: 'developers', }], ['@boss', { id: 'boss', name: 'boss', }], ['@love', { id: 'love', name: 'love', }], ['@you', { id: 'you', name: 'you', }], ]), channelMemberCountsByGroup: { developers: { channel_member_count: 10, channel_member_timezones_count: 10, }, boss: { channel_member_count: 20, channel_member_timezones_count: 130, }, love: { channel_member_count: 30, channel_member_timezones_count: 2, }, you: { channel_member_count: 40, channel_member_timezones_count: 5, }, }, }); wrapper.setState({ message: '@developers @boss @love @you', }); const instance = wrapper.instance() as AdvancedCreatePost; const showNotifyAllModal = instance.showNotifyAllModal; instance.showNotifyAllModal = jest.fn((mentions, channelTimezoneCount, memberNotifyCount) => showNotifyAllModal(mentions, channelTimezoneCount, memberNotifyCount)); const form = wrapper.find('#create_post'); form.simulate('Submit', {preventDefault: jest.fn()}); expect(instance.props.actions.openModal).toHaveBeenCalled(); expect(instance.showNotifyAllModal).toHaveBeenCalledWith(['@developers', '@boss', '@love', '@you'], 5, 40); }); it('Should set mentionHighlightDisabled prop when useChannelMentions disabled before calling actions.onSubmitPost', async () => { const onSubmitPost = jest.fn(); const wrapper = shallow(advancedCreatePost({ actions: { ...baseProp.actions, onSubmitPost, }, })); wrapper.setProps({ useChannelMentions: false, }); const post = TestHelper.getPostMock({message: 'message with @here mention'}); await (wrapper.instance() as AdvancedCreatePost).sendMessage(post); expect(onSubmitPost).toHaveBeenCalledTimes(1); expect(onSubmitPost.mock.calls[0][0]).toEqual({...post, props: {mentionHighlightDisabled: true}}); }); it('Should not set mentionHighlightDisabled prop when useChannelMentions enabled before calling actions.onSubmitPost', async () => { const onSubmitPost = jest.fn(); const wrapper = shallow(advancedCreatePost({ actions: { ...baseProp.actions, onSubmitPost, }, })); wrapper.setProps({ useChannelMentions: true, }); const post = TestHelper.getPostMock({message: 'message with @here mention'}); await (wrapper.instance() as AdvancedCreatePost).sendMessage(post); expect(onSubmitPost).toHaveBeenCalledTimes(1); expect(onSubmitPost.mock.calls[0][0]).toEqual(post); }); it('Should not set mentionHighlightDisabled prop when useChannelMentions disabled but message does not contain channel metion before calling actions.onSubmitPost', async () => { const onSubmitPost = jest.fn(); const wrapper = shallow(advancedCreatePost({ actions: { ...baseProp.actions, onSubmitPost, }, })); wrapper.setProps({ useChannelMentions: false, }); const post = TestHelper.getPostMock({message: 'message with @here mention'}); await (wrapper.instance() as AdvancedCreatePost).sendMessage(post); expect(onSubmitPost).toHaveBeenCalledTimes(1); expect(onSubmitPost.mock.calls[0][0]).toEqual(post); }); it('onSubmit test for "/header" message', () => { const openModal = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, openModal, }, }), ); wrapper.setState({ message: '/header', }); const form = wrapper.find('#create_post'); form.simulate('Submit', {preventDefault: jest.fn()}); expect(openModal).toHaveBeenCalledTimes(1); expect(openModal.mock.calls[0][0].modalId).toEqual(ModalIdentifiers.EDIT_CHANNEL_HEADER); expect(openModal.mock.calls[0][0].dialogProps.channel).toEqual(currentChannelProp); }); it('onSubmit test for "/purpose" message', () => { const openModal = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, openModal, }, }), ); wrapper.setState({ message: '/purpose', }); const form = wrapper.find('#create_post'); form.simulate('Submit', {preventDefault: jest.fn()}); expect(openModal).toHaveBeenCalledTimes(1); expect(openModal.mock.calls[0][0].modalId).toEqual(ModalIdentifiers.EDIT_CHANNEL_PURPOSE); expect(openModal.mock.calls[0][0].dialogProps.channel).toEqual(currentChannelProp); }); it('onSubmit test for "/unknown" message ', async () => { jest.mock('actions/channel_actions', () => ({ executeCommand: jest.fn((message, _args, resolve) => resolve()), })); const wrapper = shallow(advancedCreatePost()); wrapper.setState({ message: '/unknown', }); await (wrapper.instance() as AdvancedCreatePost).handleSubmit(submitEvent); expect(wrapper.state('submitting')).toBe(false); }); it('onSubmit test for addReaction message', async () => { const submitReaction = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, submitReaction, }, }), ); wrapper.setState({ message: '+:smile:', }); await (wrapper.instance() as AdvancedCreatePost).handleSubmit(submitEvent); expect(submitReaction).toHaveBeenCalledWith('a', '+', 'smile'); }); it('onSubmit test for removeReaction message', async () => { const submitReaction = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, submitReaction, }, }), ); wrapper.setState({ message: '-:smile:', }); await (wrapper.instance() as AdvancedCreatePost).handleSubmit(submitEvent); expect(submitReaction).toHaveBeenCalledWith('a', '-', 'smile'); }); /*it('check for postError state on handlePostError callback', () => { const wrapper = shallow(createPost()); const textBox = wrapper.find('#post_textbox'); const form = wrapper.find('#create_post'); textBox.prop('handlePostError')(true); expect(wrapper.state('postError')).toBe(true); wrapper.setState({ message: 'test', }); form.simulate('Submit', {preventDefault: jest.fn()}); expect(wrapper.update().find('.post-error .animation--highlight').length).toBe(1); expect(wrapper.find('#postCreateFooter').hasClass('post-create-footer has-error')).toBe(true); });*/ it('check for handleFileUploadChange callback for focus', () => { const wrapper = shallow(advancedCreatePost()); const instance: any = wrapper.instance(); const mockImpl = () => { return { setSelectionRange: jest.fn(), focus: jest.fn(), }; }; instance.textboxRef.current = {getInputBox: jest.fn(mockImpl), focus: jest.fn(), blur: jest.fn()}; instance.focusTextbox = jest.fn(); instance.handleFileUploadChange(); expect(instance.focusTextbox).toHaveBeenCalledTimes(1); }); it('check for handleFileUploadStart callback', () => { const setDraft = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, setDraft, }, }), ); const instance = wrapper.instance() as AdvancedCreatePost; const clientIds = ['a']; const draft = { ...draftProp, uploadsInProgress: [ ...draftProp.uploadsInProgress, ...clientIds, ], }; instance.handleUploadStart(clientIds, currentChannelProp.id); expect(setDraft).toHaveBeenCalledWith(StoragePrefixes.DRAFT + currentChannelProp.id, draft, currentChannelProp.id); }); it('check for handleFileUploadComplete callback', () => { const setDraft = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, setDraft, }, }), ); const instance: any = wrapper.instance(); const clientIds = ['a']; const uploadsInProgressDraft = { ...draftProp, uploadsInProgress: [ ...draftProp.uploadsInProgress, 'a', ], }; instance.draftsForChannel[currentChannelProp.id] = uploadsInProgressDraft; wrapper.setProps({draft: uploadsInProgressDraft}); const fileInfos = [TestHelper.getFileInfoMock({id: 'a'})]; const expectedDraft = { ...draftProp, fileInfos: [ ...draftProp.fileInfos, ...fileInfos, ], }; instance.handleFileUploadComplete(fileInfos, clientIds, currentChannelProp.id); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(setDraft).toHaveBeenCalledWith(StoragePrefixes.DRAFT + currentChannelProp.id, expectedDraft, currentChannelProp.id); }); it('check for handleUploadError callback', () => { const setDraft = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, setDraft, }, }), ); const instance: any = wrapper.instance(); const uploadsInProgressDraft = { ...draftProp, uploadsInProgress: [ ...draftProp.uploadsInProgress, 'a', ], }; wrapper.setProps({draft: uploadsInProgressDraft}); instance.draftsForChannel[currentChannelProp.id] = uploadsInProgressDraft; instance.handleUploadError('error message', 'a', currentChannelProp.id); expect(setDraft).toHaveBeenCalledWith(StoragePrefixes.DRAFT + currentChannelProp.id, draftProp, currentChannelProp.id); }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('check for uploadsProgressPercent state on handleUploadProgress callback', () => { // const wrapper = shallow(advancedCreatePost({})); // wrapper.find(FileUpload).prop('onUploadProgress')({clientId: 'clientId', name: 'name', percent: 10, type: 'type'}); // // expect(wrapper.state('uploadsProgressPercent')).toEqual({clientId: {clientId: 'clientId', percent: 10, name: 'name', type: 'type'}}); // }); it('Remove preview from fileInfos', () => { const setDraft = jest.fn(); const fileInfos = TestHelper.getFileInfoMock({ id: 'a', extension: 'jpg', name: 'trimmedFilename', }); const uploadsInProgressDraft = { ...draftProp, fileInfos: [ ...draftProp.fileInfos, fileInfos, ], }; const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, setDraft, }, draft: { ...draftProp, ...uploadsInProgressDraft, }, }), ); const instance = wrapper.instance() as AdvancedCreatePost; instance.handleFileUploadChange = jest.fn(); instance.removePreview('a'); jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT); expect(setDraft).toHaveBeenCalledTimes(1); expect(setDraft).toHaveBeenCalledWith(StoragePrefixes.DRAFT + currentChannelProp.id, draftProp, currentChannelProp.id, false); expect(instance.handleFileUploadChange).toHaveBeenCalledTimes(1); }); it('Show tutorial', () => { const wrapper = shallow(advancedCreatePost({ showSendTutorialTip: true, })); expect(wrapper).toMatchSnapshot(); }); it('Should have called actions.onSubmitPost on sendMessage', async () => { const onSubmitPost = jest.fn(); const wrapper = shallow(advancedCreatePost({ actions: { ...baseProp.actions, onSubmitPost, }, })); const post = TestHelper.getPostMock({message: 'message', file_ids: []}); await (wrapper.instance() as AdvancedCreatePost).sendMessage(post); expect(onSubmitPost).toHaveBeenCalledTimes(1); expect(onSubmitPost.mock.calls[0][0]).toEqual(post); expect(onSubmitPost.mock.calls[0][1]).toEqual([]); }); it('Should have called actions.selectPostFromRightHandSideSearchByPostId on replyToLastPost', () => { const selectPostFromRightHandSideSearchByPostId = jest.fn(); let latestReplyablePostId = ''; const wrapper = shallow(advancedCreatePost({ actions: { ...baseProp.actions, selectPostFromRightHandSideSearchByPostId, }, latestReplyablePostId, })); const event = {preventDefault: jest.fn()} as unknown as React.KeyboardEvent<Element>; (wrapper.instance() as AdvancedCreatePost).replyToLastPost(event); expect(selectPostFromRightHandSideSearchByPostId).not.toBeCalled(); latestReplyablePostId = 'latest_replyablePost_id'; wrapper.setProps({latestReplyablePostId}); (wrapper.instance() as AdvancedCreatePost).replyToLastPost(event); expect(selectPostFromRightHandSideSearchByPostId).toHaveBeenCalledTimes(1); expect(selectPostFromRightHandSideSearchByPostId.mock.calls[0][0]).toEqual(latestReplyablePostId); }); it('should match snapshot when cannot post', () => { const wrapper = shallow(advancedCreatePost({canPost: false})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot when file upload disabled', () => { const wrapper = shallow(advancedCreatePost({canUploadFiles: false})); expect(wrapper).toMatchSnapshot(); }); it('should allow to force send invalid slash command as a message', async () => { const error = { message: 'No command found', server_error_id: 'api.command.execute_command.not_found.app_error', }; const result: ActionResult = { error, }; const executeCommand = jest.fn(() => result); const onSubmitPost = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, executeCommand, onSubmitPost, }, }), ); wrapper.setState({ message: '/fakecommand some text', }); await (wrapper.instance() as AdvancedCreatePost).handleSubmit(submitEvent); expect(executeCommand).toHaveBeenCalled(); expect(onSubmitPost).not.toHaveBeenCalled(); await (wrapper.instance() as AdvancedCreatePost).handleSubmit(submitEvent); expect(onSubmitPost).toHaveBeenCalledWith( expect.objectContaining({ message: '/fakecommand some text', }), expect.anything(), ); }); it('should throw away invalid command error if user resumes typing', async () => { const error = { message: 'No command found', server_error_id: 'api.command.execute_command.not_found.app_error', }; const executeCommand = jest.fn().mockResolvedValue({error}); const onSubmitPost = jest.fn(); const wrapper = shallow( advancedCreatePost({ actions: { ...baseProp.actions, executeCommand, onSubmitPost, }, }), ); wrapper.setState({ message: '/fakecommand some text', }); const instance = wrapper.instance() as AdvancedCreatePost; await instance.handleSubmit(submitEvent); expect(executeCommand).toHaveBeenCalled(); expect(onSubmitPost).not.toHaveBeenCalled(); const event = { target: { value: 'some valid text', }, } as unknown as React.ChangeEvent<TextboxElement>; instance.handleChange(event); await instance.handleSubmit(submitEvent); expect(onSubmitPost).toHaveBeenCalledWith( expect.objectContaining({ message: 'some valid text', }), expect.anything(), ); }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('should not enable the save button when message empty', () => { // const wrapper = shallow(advancedCreatePost()); // const saveButton = wrapper.find('.post-body__actions .send-button'); // // expect(saveButton.hasClass('disabled')).toBe(true); // }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('should enable the save button when message not empty', () => { // const wrapper = shallow(advancedCreatePost({draft: {...draftProp, message: 'a message'}})); // const saveButton = wrapper.find('.post-body__actions .send-button'); // // expect(saveButton.hasClass('disabled')).toBe(false); // }); /** * TODO@all: move this test to advanced_text_editor.test.tsx and rewrite it according to the component * * it is not possible to test for this here since we only shallow render * * @see: https://mattermost.atlassian.net/browse/MM-44343 */ // it('should enable the save button when a file is available for upload', () => { // const wrapper = shallow(advancedCreatePost({draft: {...draftProp, fileInfos: [{id: '1'}]}})); // const saveButton = wrapper.find('.post-body__actions .send-button'); // // expect(saveButton.hasClass('disabled')).toBe(false); // }); testComponentForLineBreak( (value: string) => advancedCreatePost({draft: {...draftProp, message: value}}), (instance: any) => instance.state.message, false, ); it('should match snapshot, can post; preview enabled', () => { const wrapper = shallow(advancedCreatePost({canPost: true})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot, can post; preview disabled', () => { const wrapper = shallow(advancedCreatePost({canPost: true})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot, cannot post; preview enabled', () => { const wrapper = shallow(advancedCreatePost({canPost: false})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot, cannot post; preview disabled', () => { const wrapper = shallow(advancedCreatePost({canPost: false})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot, post priority enabled', () => { const wrapper = shallow(advancedCreatePost({isPostPriorityEnabled: true})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot, post priority enabled, with priority important', () => { const wrapper = shallow(advancedCreatePost({isPostPriorityEnabled: true, draft: {...draftProp, metadata: {priority: {priority: PostPriority.IMPORTANT}}}})); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot, post priority disabled, with priority important', () => { const wrapper = shallow(advancedCreatePost({isPostPriorityEnabled: false, draft: {...draftProp, metadata: {priority: {priority: PostPriority.IMPORTANT}}}})); expect(wrapper).toMatchSnapshot(); }); });
1,480
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_create_post
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_create_post/__snapshots__/advanced_create_post.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/advanced_create_post Show tutorial 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={true} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot for center textbox 1`] = ` <form className="center" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot when cannot post 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={false} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot when file upload disabled 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, can post; preview disabled 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, can post; preview enabled 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, cannot post; preview disabled 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={false} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, cannot post; preview enabled 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={false} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, init 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, post priority disabled, with priority important 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={Array []} applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "metadata": Object { "priority": Object { "priority": "important", }, }, "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, post priority enabled 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={ Array [ <Memo(PostPriorityPickerOverlay) disabled={false} onApply={[Function]} onClose={[Function]} />, ] } applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `; exports[`components/advanced_create_post should match snapshot, post priority enabled, with priority important 1`] = ` <form className="" data-testid="create-post" id="create_post" onSubmit={[Function]} > <AdvanceTextEditor additionalControls={ Array [ <Memo(PostPriorityPickerOverlay) disabled={false} onApply={[Function]} onClose={[Function]} settings={ Object { "priority": "important", } } />, ] } applyMarkdown={[Function]} badConnection={false} canPost={true} canUploadFiles={false} caretPosition={0} channelId="owsyt8n43jfxjpzh9np93mx1wa" ctrlSend={false} currentChannel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "owsyt8n43jfxjpzh9np93mx1wa", "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, } } currentUserId="zaktnt8bpbgu8mb6ez9k64r7sa" disableSend={false} draft={ Object { "channelId": "", "createAt": 0, "fileInfos": Array [], "message": "", "metadata": Object { "priority": Object { "priority": "important", }, }, "rootId": "", "updateAt": 0, "uploadsInProgress": Array [], } } emitTypingEvent={[Function]} enableEmojiPicker={true} enableGifPicker={true} errorClass={null} fileUploadRef={ Object { "current": null, } } getFileUploadTarget={[Function]} handleBlur={[Function]} handleChange={[Function]} handleEmojiClick={[Function]} handleFileUploadChange={[Function]} handleFileUploadComplete={[Function]} handleGifClick={[Function]} handleMouseUpKeyUp={[Function]} handlePostError={[Function]} handleSubmit={[Function]} handleUploadError={[Function]} handleUploadProgress={[Function]} handleUploadStart={[Function]} hideEmojiPicker={[Function]} isFormattingBarHidden={false} labels={ <Memo(PriorityLabels) canRemove={true} hasError={false} onRemove={[Function]} priority="important" specialMentions={ Object { "all": false, "channel": false, "here": false, } } /> } loadNextMessage={[Function]} loadPrevMessage={[Function]} location="CENTER" maxPostSize={4000} message="" onEditLatestPost={[Function]} onMessageChange={[Function]} postId="" postMsgKeyPress={[Function]} prefillMessage={[Function]} removePreview={[Function]} replyToLastPost={[Function]} serverError={null} setShowPreview={[Function]} shouldShowPreview={false} showEmojiPicker={false} showSendTutorialTip={false} textboxRef={ Object { "current": null, } } toggleAdvanceTextEditor={[Function]} toggleEmojiPicker={[Function]} uploadsProgressPercent={Object {}} useChannelMentions={true} /> </form> `;
1,482
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/advanced_text_editor/advanced_text_editor.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {screen} from '@testing-library/react'; import React from 'react'; import type {Channel} from '@mattermost/types/channels'; import Permissions from 'mattermost-redux/constants/permissions'; import type {FileUpload} from 'components/file_upload/file_upload'; import type Textbox from 'components/textbox/textbox'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import {renderWithContext, userEvent} from 'tests/react_testing_utils'; import {TestHelper} from 'utils/test_helper'; import type {PostDraft} from 'types/store/draft'; import AdavancedTextEditor from './advanced_text_editor'; global.ResizeObserver = require('resize-observer-polyfill'); const currentUserId = 'current_user_id'; const channelId = 'current_channel_id'; const initialState = { entities: { general: { config: { EnableConfirmNotificationsToChannel: 'false', EnableCustomGroups: 'false', PostPriority: 'false', ExperimentalTimezone: 'false', EnableCustomEmoji: 'false', AllowSyncedDrafts: 'false', }, license: { IsLicensed: 'false', LDAPGroups: 'false', }, }, channels: { channels: { current_channel_id: TestHelper.getChannelMock({id: 'current_channel_id', team_id: 'current_team_id'}), }, stats: { current_channel_id: { member_count: 1, }, }, roles: { current_channel_id: new Set(['channel_roles']), }, }, teams: { currentTeamId: 'current_team_id', teams: { current_team_id: TestHelper.getTeamMock({id: 'current_team_id'}), }, myMembers: { current_team_id: TestHelper.getTeamMembershipMock({roles: 'team_roles'}), }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: TestHelper.getUserMock({id: 'current_user_id', roles: 'user_roles'}), }, statuses: { current_user_id: 'online', }, }, }, websocket: { connectionId: 'connection_id', }, }; const emptyDraft: PostDraft = { message: '', uploadsInProgress: [], fileInfos: [], channelId, rootId: '', createAt: 0, updateAt: 0, }; const baseProps = { location: 'CENTER', message: '', showEmojiPicker: false, uploadsProgressPercent: {}, currentChannel: initialState.entities.channels.channels.current_channel_id as Channel, channelId, postId: '', errorClass: null, serverError: null, postError: null, isFormattingBarHidden: false, draft: emptyDraft, badConnection: false, handleSubmit: jest.fn(), removePreview: jest.fn(), showSendTutorialTip: false, setShowPreview: jest.fn(), shouldShowPreview: false, maxPostSize: 100, canPost: true, applyMarkdown: jest.fn(), useChannelMentions: false, currentChannelTeammateUsername: '', currentUserId, canUploadFiles: true, enableEmojiPicker: true, enableGifPicker: true, handleBlur: jest.fn(), handlePostError: jest.fn(), emitTypingEvent: jest.fn(), handleMouseUpKeyUp: jest.fn(), postMsgKeyPress: jest.fn(), handleChange: jest.fn(), toggleEmojiPicker: jest.fn(), handleGifClick: jest.fn(), handleEmojiClick: jest.fn(), hideEmojiPicker: jest.fn(), toggleAdvanceTextEditor: jest.fn(), handleUploadProgress: jest.fn(), handleUploadError: jest.fn(), handleFileUploadComplete: jest.fn(), handleUploadStart: jest.fn(), handleFileUploadChange: jest.fn(), getFileUploadTarget: jest.fn(), fileUploadRef: React.createRef<FileUpload>(), prefillMessage: jest.fn(), textboxRef: React.createRef<Textbox>(), isThreadView: false, ctrlSend: true, codeBlockOnCtrlEnter: true, onMessageChange: jest.fn(), onEditLatestPost: jest.fn(), loadPrevMessage: jest.fn(), loadNextMessage: jest.fn(), replyToLastPost: jest.fn(), caretPosition: 0, }; describe('components/avanced_text_editor/advanced_text_editor', () => { describe('keyDown behavior', () => { it('Enter should call postMsgKeyPress', () => { const postMsgKeyPress = jest.fn(); renderWithContext( <AdavancedTextEditor {...baseProps} postMsgKeyPress={postMsgKeyPress} message={'test'} />, mergeObjects(initialState, { entities: { roles: { roles: { user_roles: {permissions: [Permissions.CREATE_POST]}, }, }, }, }), ); userEvent.type(screen.getByTestId('post_textbox'), '{enter}'); expect(postMsgKeyPress).toHaveBeenCalledTimes(1); }); it('Ctrl+up should call loadPrevMessage', () => { const loadPrevMessage = jest.fn(); renderWithContext( <AdavancedTextEditor {...baseProps} loadPrevMessage={loadPrevMessage} />, mergeObjects(initialState, { entities: { roles: { roles: { user_roles: {permissions: [Permissions.CREATE_POST]}, }, }, }, }), ); userEvent.type(screen.getByTestId('post_textbox'), '{ctrl}{arrowup}'); expect(loadPrevMessage).toHaveBeenCalledTimes(1); }); it('up should call onEditLatestPost', () => { const onEditLatestPost = jest.fn(); renderWithContext( <AdavancedTextEditor {...baseProps} onEditLatestPost={onEditLatestPost} />, mergeObjects(initialState, { entities: { roles: { roles: { user_roles: {permissions: [Permissions.CREATE_POST]}, }, }, }, }), ); userEvent.type(screen.getByTestId('post_textbox'), '{arrowup}'); expect(onEditLatestPost).toHaveBeenCalledTimes(1); }); it('ESC should blur the input', () => { renderWithContext( <AdavancedTextEditor {...baseProps} />, mergeObjects(initialState, { entities: { roles: { roles: { user_roles: {permissions: [Permissions.CREATE_POST]}, }, }, }, }), ); const textbox = screen.getByTestId('post_textbox'); userEvent.type(textbox, 'something{esc}'); expect(textbox).not.toHaveFocus(); }); describe('markdown', () => { const ttcc = [ { input: '{ctrl}b', markdownMode: 'bold', }, { input: '{ctrl}i', markdownMode: 'italic', }, { input: '{ctrl}k', markdownMode: 'link', }, { input: '{ctrl}{alt}k', markdownMode: 'link', }, ]; for (const tc of ttcc) { it(`component adds ${tc.markdownMode} markdown`, () => { const applyMarkdown = jest.fn(); const message = 'Some markdown text'; const selectionStart = 5; const selectionEnd = 10; renderWithContext( <AdavancedTextEditor {...baseProps} applyMarkdown={applyMarkdown} message={'Some markdown text'} />, mergeObjects(initialState, { entities: { roles: { roles: { user_roles: {permissions: [Permissions.CREATE_POST]}, }, }, }, }), ); const textbox = screen.getByTestId('post_textbox'); userEvent.type(textbox, tc.input, {initialSelectionStart: selectionStart, initialSelectionEnd: selectionEnd}); expect(applyMarkdown).toHaveBeenCalledWith({ markdownMode: tc.markdownMode, selectionStart, selectionEnd, message, }); }); } }); }); });
1,497
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/doughnut_chart.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Chart, ChartData} from 'chart.js'; import {shallow, mount} from 'enzyme'; import React from 'react'; import DoughnutChart from 'components/analytics/doughnut_chart'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; jest.mock('chart.js'); describe('components/analytics/doughnut_chart.tsx', () => { test('should match snapshot, on loading', () => { const wrapper = shallow( <DoughnutChart title='Test' height={400} width={600} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded without data', () => { const Chart = jest.requireMock('chart.js'); const data: ChartData | undefined = undefined; const wrapper = mountWithIntl( <DoughnutChart title='Test' height={400} width={600} data={data} />, ); expect(Chart).not.toBeCalled(); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded with data', () => { const Chart = jest.requireMock('chart.js'); const data: ChartData = { datasets: [ {data: [1, 2, 3]}, ], }; const wrapper = mount( <DoughnutChart title='Test' height={400} width={600} data={data} />, ); expect(Chart).toBeCalledWith(expect.anything(), {data, options: {}, type: 'doughnut'}); expect(wrapper).toMatchSnapshot(); }); test('should create and destroy the chart on mount and unmount with data', () => { const Chart = jest.requireMock('chart.js'); const data: ChartData = { datasets: [ {data: [1, 2, 3]}, ], labels: ['test1', 'test2', 'test3'], }; const wrapper = mount<DoughnutChart>( <DoughnutChart title='Test' height={400} width={600} data={data} />, ); expect(Chart).toBeCalled(); const chartDestroy = wrapper.instance().chart!.destroy; wrapper.unmount(); expect(chartDestroy).toBeCalled(); }); test('should update the chart on data change', () => { const Chart = jest.requireMock('chart.js'); const oldData: ChartData = { datasets: [ {data: [1, 2, 3]}, ], labels: ['test1', 'test2', 'test3'], }; const newData: ChartData = { datasets: [ {data: [1, 2, 3, 4]}, ], labels: ['test1', 'test2', 'test3', 'test4'], }; const wrapper = mount<DoughnutChart>( <DoughnutChart title='Test' height={400} width={600} data={oldData} />, ); expect(Chart).toBeCalled(); expect((wrapper.instance().chart as Chart).update).not.toBeCalled(); wrapper.setProps({title: 'new title'}); expect((wrapper.instance().chart as Chart).update).not.toBeCalled(); wrapper.setProps({data: newData}); expect((wrapper.instance().chart as Chart).update).toBeCalled(); }); });
1,499
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/format.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {synchronizeChartLabels, formatUsersWithPostsPerDayData} from './format'; describe('components/analytics/format.tsx', () => { test('should create union of all date ranges', () => { const data1 = [{ name: 'date1', value: 1, }, { name: 'date2', value: 2, }]; const data2 = [{ name: 'date1', value: 1, }, { name: 'date3', value: 3, }]; const data3 = [{ name: 'date2', value: 2, }, { name: 'date4', value: 4, }]; const syncData = synchronizeChartLabels(data1, data2, data3); expect(syncData.length).toBe(4); }); test('should synchronize null data', () => { const labels = ['date1', 'date2', 'date3', 'date4']; const chartData = formatUsersWithPostsPerDayData(labels, null); expect(chartData.labels.length).toBe(0); expect(chartData.datasets[0].data.length).toBe(0); }); test('should not add empty data', () => { const data1: any[] = []; const labels = ['date1', 'date2', 'date3', 'date4']; const chartData = formatUsersWithPostsPerDayData(labels, data1); expect(chartData.labels.length).toBe(0); expect(chartData.datasets[0].data.length).toBe(0); }); test('should synchronize all date ranges', () => { const data1 = [{ name: 'date2', value: 1, }, { name: 'date3', value: 2, }]; const labels = ['date1', 'date2', 'date3', 'date4']; const chartData = formatUsersWithPostsPerDayData(labels, data1); expect(chartData.labels.length).toBe(4); expect(chartData.datasets[0].data.length).toBe(4); expect(chartData.datasets[0].data[0]).toBe(0); expect(chartData.datasets[0].data[3]).toBe(0); }); });
1,501
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/line_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 LineChart from 'components/analytics/line_chart'; describe('components/analytics/line_chart.tsx', () => { test('should match snapshot, on loading', () => { const wrapper = shallow( <LineChart id='test' title='Test' height={400} width={600} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded without data', () => { const data = { datasets: [], labels: [], }; const wrapper = shallow( <LineChart id='test' title='Test' height={400} width={600} data={data} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded with data', () => { const data = { datasets: [ {data: [1, 2, 3]}, ], labels: ['test1', 'test2', 'test3'], }; const wrapper = shallow( <LineChart id='test' title='Test' height={400} width={600} data={data} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,503
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/statistic_count.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 StatisticCount from 'components/analytics/statistic_count'; describe('components/analytics/statistic_count.tsx', () => { test('should match snapshot, on loading', () => { const wrapper = shallow( <StatisticCount title='Test' icon='test-icon' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded', () => { const wrapper = shallow( <StatisticCount title='Test' icon='test-icon' count={4} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded with zero value', () => { const wrapper = shallow( <StatisticCount title='Test Zero' icon='test-icon' count={0} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,505
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/table_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 TableChart from 'components/analytics/table_chart'; import type {TableItem} from 'components/analytics/table_chart'; describe('components/analytics/table_chart.tsx', () => { test('should match snapshot, loaded without data', () => { const data: TableItem[] = []; const wrapper = shallow( <TableChart title='Test' data={data} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, loaded with data', () => { const data = [ {name: 'test1', tip: 'test-tip1', value: <p>{'test-value1'}</p>}, {name: 'test2', tip: 'test-tip2', value: <p>{'test-value2'}</p>}, ]; const wrapper = shallow( <TableChart title='Test' data={data} />, ); expect(wrapper).toMatchSnapshot(); }); });
1,508
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/true_up_review.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {GlobalState} from '@mattermost/types/store'; import type {DeepPartial} from '@mattermost/types/utilities'; import * as useCWSAvailabilityCheckAll from 'components/common/hooks/useCWSAvailabilityCheck'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {LicenseSkus} from 'utils/constants'; import {TestHelper as TH} from 'utils/test_helper'; import TrueUpReview from './true_up_review'; describe('TrueUpReview', () => { const showsTrueUpReviewState: DeepPartial<GlobalState> = { entities: { general: { license: TH.getLicenseMock({ IsGovSku: 'false', Cloud: 'false', SkuShortName: LicenseSkus.Enterprise, IsLicensed: 'true', }), config: { EnableDiagnostics: 'false', }, }, users: { currentUserId: 'userId', profiles: { userId: TH.getUserMock({ id: 'userId', roles: 'system_admin', }), }, }, hostedCustomer: { trueUpReviewStatus: { // one day in future so we're sure it will display, // regardless of future changes to "do we show it if it already passed" due_date: Date.now() + (1000 * 60 * 60 * 24), complete: false, getRequestState: 'IDLE', }, trueUpReviewProfile: { getRequestState: 'IDLE', content: '', }, errors: {}, }, }, }; it('regular self hosted license in the true up window sees content', () => { jest.spyOn(useCWSAvailabilityCheckAll, 'default').mockImplementation(() => true); renderWithContext(<TrueUpReview/>, showsTrueUpReviewState); screen.getByText('Share to Mattermost'); }); it('gov sku self-hosted license does not see true up content', () => { const store = JSON.parse(JSON.stringify(showsTrueUpReviewState)); store.entities.general.license.IsGovSku = 'true'; jest.spyOn(useCWSAvailabilityCheckAll, 'default').mockImplementation(() => true); renderWithContext(<TrueUpReview/>, store); expect(screen.queryByText('Share to Mattermost')).not.toBeInTheDocument(); }); });
1,510
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/__snapshots__/doughnut_chart.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/analytics/doughnut_chart.tsx should match snapshot, loaded with data 1`] = ` <DoughnutChart data={ Object { "datasets": Array [ Object { "data": Array [ 1, 2, 3, ], }, ], } } height={400} title="Test" width={600} > <div className="col-sm-6" > <div className="total-count" > <div className="title" > Test </div> <div className="content" > <canvas height={400} width={600} /> </div> </div> </div> </DoughnutChart> `; exports[`components/analytics/doughnut_chart.tsx should match snapshot, loaded without data 1`] = ` <DoughnutChart height={400} title="Test" width={600} > <div className="col-sm-6" > <div className="total-count" > <div className="title" > Test </div> <div className="content" > <FormattedMessage defaultMessage="Loading..." id="analytics.chart.loading" > <span> Loading... </span> </FormattedMessage> </div> </div> </div> </DoughnutChart> `; exports[`components/analytics/doughnut_chart.tsx should match snapshot, on loading 1`] = ` <div className="col-sm-6" > <div className="total-count" > <div className="title" > Test </div> <div className="content" > <MemoizedFormattedMessage defaultMessage="Loading..." id="analytics.chart.loading" /> </div> </div> </div> `;
1,511
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/__snapshots__/line_chart.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/analytics/line_chart.tsx should match snapshot, loaded with data 1`] = ` <div className="col-sm-12" > <div className="total-count by-day" > <div className="title" > Test </div> <div className="content" > <canvas data-labels={ Array [ "test1", "test2", "test3", ] } data-testid="test" height={400} width={600} /> </div> </div> </div> `; exports[`components/analytics/line_chart.tsx should match snapshot, loaded without data 1`] = ` <div className="col-sm-12" > <div className="total-count by-day" > <div className="title" > Test </div> <div className="content" > <h5> <MemoizedFormattedMessage defaultMessage="Not enough data for a meaningful representation." id="analytics.chart.meaningful" /> </h5> </div> </div> </div> `; exports[`components/analytics/line_chart.tsx should match snapshot, on loading 1`] = ` <div className="col-sm-12" > <div className="total-count by-day" > <div className="title" > Test </div> <div className="content" > <MemoizedFormattedMessage defaultMessage="Loading..." id="analytics.chart.loading" /> </div> </div> </div> `;
1,512
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/__snapshots__/statistic_count.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/analytics/statistic_count.tsx should match snapshot, loaded 1`] = ` <div className="grid-statistics__card" > <div className="total-count" > <div className="title" data-testid="undefinedTitle" > Test <i className="fa test-icon" /> </div> <div className="content" > 4 </div> </div> </div> `; exports[`components/analytics/statistic_count.tsx should match snapshot, loaded with zero value 1`] = ` <div className="grid-statistics__card" > <div className="total-count" > <div className="title" data-testid="undefinedTitle" > Test Zero <i className="fa test-icon" /> </div> <div className="content" > 0 </div> </div> </div> `; exports[`components/analytics/statistic_count.tsx should match snapshot, on loading 1`] = ` <div className="grid-statistics__card" > <div className="total-count" > <div className="title" data-testid="undefinedTitle" > Test <i className="fa test-icon" /> </div> <div className="content" > <MemoizedFormattedMessage defaultMessage="Loading..." id="analytics.chart.loading" /> </div> </div> </div> `;
1,513
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics
petrpan-code/mattermost/mattermost/webapp/channels/src/components/analytics/__snapshots__/table_chart.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/analytics/table_chart.tsx should match snapshot, loaded with data 1`] = ` <div className="col-sm-6" > <div className="total-count recent-active-users" > <div className="title" > Test </div> <div className="content" > <table> <tbody> <tr key="table-entry-test1" > <td> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="tip-table-entry-test1" > test-tip1 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <time> test1 </time> </OverlayTrigger> </td> <td> <p> test-value1 </p> </td> </tr> <tr key="table-entry-test2" > <td> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="tip-table-entry-test2" > test-tip2 </Tooltip> } placement="top" trigger={ Array [ "hover", "focus", ] } > <time> test2 </time> </OverlayTrigger> </td> <td> <p> test-value2 </p> </td> </tr> </tbody> </table> </div> </div> </div> `; exports[`components/analytics/table_chart.tsx should match snapshot, loaded without data 1`] = ` <div className="col-sm-6" > <div className="total-count recent-active-users" > <div className="title" > Test </div> <div className="content" > <table> <tbody /> </table> </div> </div> </div> `;
1,519
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/announcement_bar.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 'tests/helpers/localstorage'; import AnnouncementBar from 'components/announcement_bar/default_announcement_bar/announcement_bar'; describe('components/AnnouncementBar', () => { const baseProps = { isLoggedIn: true, canViewSystemErrors: false, canViewAPIv3Banner: false, license: { id: '', }, siteURL: '', sendEmailNotifications: true, enablePreviewMode: false, bannerText: 'Banner text', allowBannerDismissal: true, enableBanner: true, bannerColor: 'green', bannerTextColor: 'black', enableSignUpWithGitLab: false, message: 'text', announcementBarCount: 0, actions: { sendVerificationEmail: jest.fn(), incrementAnnouncementBarCount: jest.fn(), decrementAnnouncementBarCount: jest.fn(), }, }; test('should match snapshot, bar showing', () => { const props = baseProps; const wrapper = shallow<AnnouncementBar>( <AnnouncementBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, bar not showing', () => { const props = {...baseProps, enableBanner: false}; const wrapper = shallow<AnnouncementBar>( <AnnouncementBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, bar showing, no dismissal', () => { const props = {...baseProps, allowBannerDismissal: false}; const wrapper = shallow<AnnouncementBar>( <AnnouncementBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, props change', () => { const props = baseProps; const wrapper = shallow<AnnouncementBar>( <AnnouncementBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); const newProps = {...baseProps, bannerColor: 'yellow', bannerTextColor: 'red'}; wrapper.setProps(newProps as any); expect(wrapper).toMatchSnapshot(); newProps.allowBannerDismissal = false; wrapper.setProps(newProps as any); expect(wrapper).toMatchSnapshot(); newProps.enableBanner = false; wrapper.setProps(newProps as any); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, dismissal', () => { const props = baseProps; const wrapper = shallow<AnnouncementBar>( <AnnouncementBar {...props}/>, ); // Banner should show expect(wrapper).toMatchSnapshot(); // Banner should remain hidden const newProps = {...baseProps, bannerColor: 'yellow', bannerTextColor: 'red'}; wrapper.setProps(newProps as any); expect(wrapper).toMatchSnapshot(); // Banner should return newProps.bannerText = 'Some new text'; wrapper.setProps(newProps as any); expect(wrapper).toMatchSnapshot(); }); });
1,522
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/text_dismissable_bar.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 TextDismissableBar from 'components/announcement_bar/text_dismissable_bar'; describe('components/TextDismissableBar', () => { const baseProps = { allowDismissal: true, text: 'sample text', onDismissal: jest.fn(), extraProp: 'test', }; test('should match snapshot', () => { const props = baseProps; const wrapper = shallow<TextDismissableBar>( <TextDismissableBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, with link but without siteURL', () => { const props = {...baseProps, text: 'A [link](http://testurl.com/admin_console/)'}; const wrapper = shallow<TextDismissableBar>( <TextDismissableBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, with an internal url', () => { const props = {...baseProps, text: 'A [link](http://testurl.com/admin_console/) with an internal url', siteURL: 'http://testurl.com'}; const wrapper = shallow<TextDismissableBar>( <TextDismissableBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, with ean external url', () => { const props = {...baseProps, text: 'A [link](http://otherurl.com/admin_console/) with an external url', siteURL: 'http://testurl.com'}; const wrapper = shallow<TextDismissableBar>( <TextDismissableBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, with an internal and an external link', () => { const props = {...baseProps, text: 'A [link](http://testurl.com/admin_console/) with an internal url and a [link](http://other-url.com/admin_console/) with an external url', siteURL: 'http://testurl.com'}; const wrapper = shallow<TextDismissableBar>( <TextDismissableBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,524
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/__snapshots__/announcement_bar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/AnnouncementBar should match snapshot, bar not showing 1`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, bar showing 1`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, bar showing, no dismissal 1`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, dismissal 1`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, dismissal 2`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, dismissal 3`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, props change 1`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, props change 2`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, props change 3`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `; exports[`components/AnnouncementBar should match snapshot, props change 4`] = ` <_StyledDiv className="announcement-bar announcement-bar-critical" style={ Object { "backgroundColor": "", "color": "", } } > <OverlayTrigger defaultOverlayShown={false} delayHide={0} delayShow={400} overlay={<React.Fragment />} placement="bottom" trigger={ Array [ "hover", "focus", ] } > <div className="announcement-bar__text" > <span onMouseEnter={[Function]} > <FormattedMarkdownMessage id="text" /> </span> <span className="announcement-bar__link" /> </div> </OverlayTrigger> </_StyledDiv> `;
1,525
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/__snapshots__/text_dismissable_bar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/TextDismissableBar should match snapshot 1`] = ` <Connect(AnnouncementBar) extraProp="test" handleClose={[Function]} message={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(Connect(Markdown)) message="sample text" options={ Object { "mentionHighlight": false, "singleline": true, } } /> </React.Fragment> } onDismissal={[MockFunction]} showCloseButton={true} /> `; exports[`components/TextDismissableBar should match snapshot, with an internal and an external link 1`] = ` <Connect(AnnouncementBar) extraProp="test" handleClose={[Function]} message={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(Connect(Markdown)) message="A [link](http://testurl.com/admin_console/) with an internal url and a [link](http://other-url.com/admin_console/) with an external url" options={ Object { "mentionHighlight": false, "singleline": true, } } /> </React.Fragment> } onDismissal={[MockFunction]} showCloseButton={true} siteURL="http://testurl.com" /> `; exports[`components/TextDismissableBar should match snapshot, with an internal url 1`] = ` <Connect(AnnouncementBar) extraProp="test" handleClose={[Function]} message={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(Connect(Markdown)) message="A [link](http://testurl.com/admin_console/) with an internal url" options={ Object { "mentionHighlight": false, "singleline": true, } } /> </React.Fragment> } onDismissal={[MockFunction]} showCloseButton={true} siteURL="http://testurl.com" /> `; exports[`components/TextDismissableBar should match snapshot, with ean external url 1`] = ` <Connect(AnnouncementBar) extraProp="test" handleClose={[Function]} message={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(Connect(Markdown)) message="A [link](http://otherurl.com/admin_console/) with an external url" options={ Object { "mentionHighlight": false, "singleline": true, } } /> </React.Fragment> } onDismissal={[MockFunction]} showCloseButton={true} siteURL="http://testurl.com" /> `; exports[`components/TextDismissableBar should match snapshot, with link but without siteURL 1`] = ` <Connect(AnnouncementBar) extraProp="test" handleClose={[Function]} message={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(Connect(Markdown)) message="A [link](http://testurl.com/admin_console/)" options={ Object { "mentionHighlight": false, "singleline": true, } } /> </React.Fragment> } onDismissal={[MockFunction]} showCloseButton={true} /> `;
1,526
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/cloud_delinquency/cloud_delinquency_announcement_bar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as reactRedux from 'react-redux'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {CloudProducts} from 'utils/constants'; import CloudDelinquencyAnnouncementBar from './index'; describe('components/announcement_bar/cloud_delinquency', () => { const initialState = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin'}, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', delinquent_since: 1652807380, // may 17 2022 }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, test_prod_2: { id: 'test_prod_2', sku: CloudProducts.ENTERPRISE, price_per_seat: 0, }, test_prod_3: { id: 'test_prod_3', sku: CloudProducts.PROFESSIONAL, price_per_seat: 0, }, }, }, }, }; it('Should not show banner when not delinquent', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.subscription = { ...state.entities.cloud.subscription, delinquent_since: null, }; jest.useFakeTimers().setSystemTime(new Date('2022-06-20')); const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudDelinquencyAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('AnnouncementBar').exists()).toEqual(false); }); it('Should not show banner when user is not admin', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.users = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'user'}, }, }; jest.useFakeTimers().setSystemTime(new Date('2022-06-20')); const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudDelinquencyAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('AnnouncementBar').exists()).toEqual(false); }); it('Should match snapshot when delinquent < 90 days', () => { const state = JSON.parse(JSON.stringify(initialState)); const store = mockStore(state); jest.useFakeTimers().setSystemTime(new Date('2022-06-20')); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudDelinquencyAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('.announcement-bar-advisor').exists()).toEqual(true); }); it('Should match snapshot when delinquent > 90 days', () => { const state = JSON.parse(JSON.stringify(initialState)); const store = mockStore(state); jest.useFakeTimers().setSystemTime(new Date('2022-12-20')); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudDelinquencyAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('.announcement-bar-critical').exists()).toEqual(true); }); });
1,530
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/cloud_trial_ended_announcement_bar/cloud_trial_ended_announcement_bar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as reactRedux from 'react-redux'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {CloudProducts, Preferences, CloudBanners} from 'utils/constants'; import {FileSizes} from 'utils/file_utils'; import CloudTrialEndAnnouncementBar from './index'; describe('components/global/CloudTrialEndAnnouncementBar', () => { const useDispatchMock = jest.spyOn(reactRedux, 'useDispatch'); beforeEach(() => { useDispatchMock.mockClear(); }); const initialState = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { preferences: { myPreferences: { category: Preferences.CLOUD_TRIAL_END_BANNER, name: CloudBanners.HIDE, user_id: 'current_user_id', value: 'false', }, }, general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin'}, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, test_prod_2: { id: 'test_prod_2', sku: CloudProducts.ENTERPRISE, price_per_seat: 0, }, test_prod_3: { id: 'test_prod_3', sku: CloudProducts.PROFESSIONAL, price_per_seat: 0, }, }, limits: { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, }, boards: { cards: 500, views: 5, }, }, }, }, usage: { integrations: { enabled: 11, enabledLoaded: true, }, messages: { history: 10000, historyLoaded: true, }, files: { totalStorage: FileSizes.Gigabyte, totalStorageLoaded: true, }, teams: { active: 1, cloudArchived: 0, teamsLoaded: true, }, boards: { cards: 500, cardsLoaded: true, }, }, }, }; it('Should show banner when not on free trial with a trial_end_at in the past', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.subscription = { ...state.entities.cloud.subscription, trial_end_at: 1655577344000, }; // Set the system time to be June 20th, since this banner won't show for trial's ending prior to June 15 jest.useFakeTimers().setSystemTime(new Date('2022-06-20')); const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect( wrapper.find('AnnouncementBar').exists(), ).toEqual(true); }); it('Should show banner cloudArchived teams exist', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.subscription = { ...state.entities.cloud.subscription, trial_end_at: 1655577344000, }; state.entities.usage.teams = { cloudArchived: 2, active: -1, teamsLoaded: true, }; // Set the system time to be June 20th, since this banner won't show for trial's ending prior to June 15 jest.useFakeTimers().setSystemTime(new Date('2022-06-20')); const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('AnnouncementBar').exists()).toEqual(true); }); it('should not show banner if on free trial', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud = { subscription: { product_id: 'test_prod_2', is_free_trial: 'true', trial_end_at: new Date( new Date().getTime() + (2 * 24 * 60 * 60 * 1000), ), }, products: { test_prod_2: { id: 'test_prod_2', sku: CloudProducts.ENTERPRISE, price_per_seat: 10, }, }, limits: { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, }, boards: { cards: 500, views: 5, }, }, }, usage: { integrations: { enabled: 11, enabledLoaded: true, }, messages: { history: 10000, historyLoaded: true, }, files: { totalStorage: FileSizes.Gigabyte, totalStorageLoaded: true, }, teams: { active: 1, teamsLoaded: true, }, boards: { cards: 500, cardsLoaded: true, }, }, }; const store = mockStore(state); const dummyDispatch = jest.fn(); useDispatchMock.mockReturnValue(dummyDispatch); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect( wrapper.find('AnnouncementBar').exists(), ).toEqual(false); }); it('should not show for non-admins', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.users = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'user'}, }, }; const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect( wrapper.find('AnnouncementBar').exists(), ).toEqual(false); }); it('should not show for enterprise workspaces', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.subscription.product_id = 'test_prod_2'; const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('AnnouncementBar').exists()).toEqual(false); }); it('should not show for professional workspaces', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.subscription.product_id = 'test_prod_3'; const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect(wrapper.find('AnnouncementBar').exists()).toEqual(false); }); it('Should not show banner if preference is set to hidden', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.preferences = { myPreferences: { [getPreferenceKey( Preferences.CLOUD_TRIAL_END_BANNER, CloudBanners.HIDE, )]: {name: CloudBanners.HIDE, value: 'true'}, }, }; const store = mockStore(state); const wrapper = mountWithIntl( <reactRedux.Provider store={store}> <CloudTrialEndAnnouncementBar/> </reactRedux.Provider>, ); expect( wrapper.find('AnnouncementBar').exists(), ).toEqual(false); }); });
1,532
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/configuration_bar/configuration_bar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import ConfigurationBar from 'components/announcement_bar/configuration_bar/configuration_bar'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; describe('components/ConfigurationBar', () => { const millisPerDay = 24 * 60 * 60 * 1000; const baseProps = { isLoggedIn: true, canViewSystemErrors: true, license: { Id: '1234', IsLicensed: 'true', ExpiresAt: Date.now() + millisPerDay, ShortSkuName: 'skuShortName', }, config: { sendEmailNotifications: false, }, dismissedExpiringLicense: false, dismissedExpiredLicense: false, siteURL: '', totalUsers: 100, actions: { dismissNotice: jest.fn(), savePreferences: jest.fn(), }, currentUserId: 'user-id', }; test('should match snapshot, expired, in grace period', () => { const props = {...baseProps, license: {Id: '1234', IsLicensed: 'true', ExpiresAt: Date.now() - millisPerDay}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, expired', () => { const props = {...baseProps, license: {Id: '1234', IsLicensed: 'true', ExpiresAt: Date.now() - (11 * millisPerDay)}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, expired, regular user', () => { const props = {...baseProps, canViewSystemErrors: false, license: {Id: '1234', IsLicensed: 'true', ExpiresAt: Date.now() - (11 * millisPerDay)}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, expired, cloud license, show nothing', () => { const props = {...baseProps, canViewSystemErrors: false, license: {Id: '1234', IsLicensed: 'true', Cloud: 'true', ExpiresAt: Date.now() - (11 * millisPerDay)}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, expiring, cloud license, show nothing', () => { const props = {...baseProps, canViewSystemErrors: false, license: {Id: '1234', IsLicensed: 'true', Cloud: 'true', ExpiresAt: Date.now()}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, show nothing', () => { const props = {...baseProps, license: {Id: '1234', IsLicensed: 'true', ExpiresAt: Date.now() + (61 * millisPerDay)}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, expiring, trial license, mobile viewport', () => { Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 150, }); window.dispatchEvent(new Event('500')); const props = {...baseProps, canViewSystemErrors: true, license: {Id: '1234', IsLicensed: 'true', IsTrial: 'true', ExpiresAt: Date.now() + 1}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, expiring, trial license', () => { Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1000, }); window.dispatchEvent(new Event('500')); const props = {...baseProps, canViewSystemErrors: true, license: {Id: '1234', IsLicensed: 'true', IsTrial: 'true', ExpiresAt: Date.now() + 1}}; const wrapper = shallowWithIntl( <ConfigurationBar {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,535
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/configuration_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/configuration_bar/__snapshots__/configuration_bar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ConfigurationBar should match snapshot, expired 1`] = ` <Connect(AnnouncementBar) handleClose={[Function]} message={ <div className="announcement-bar__configuration" > <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(MemoizedFormattedMessage) defaultMessage="{licenseSku} license is expired and some features may be disabled." id="announcement_bar.error.license_expired" values={ Object { "licenseSku": "Enterprise", } } /> </React.Fragment> <Memo(Connect(RenewalLink)) telemetryInfo={ Object { "error": "renew_license_banner_fail", "success": "renew_license_banner_success", } } /> </div> } showCloseButton={true} tooltipMsg={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(MemoizedFormattedMessage) defaultMessage="{licenseSku} license is expired and some features may be disabled." id="announcement_bar.error.license_expired" values={ Object { "licenseSku": "Enterprise", } } /> </React.Fragment> } type="critical" /> `; exports[`components/ConfigurationBar should match snapshot, expired, cloud license, show nothing 1`] = `""`; exports[`components/ConfigurationBar should match snapshot, expired, in grace period 1`] = ` <Connect(AnnouncementBar) handleClose={[Function]} message={ <div className="announcement-bar__configuration" > <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(MemoizedFormattedMessage) defaultMessage="{licenseSku} license is expired and some features may be disabled." id="announcement_bar.error.license_expired" values={ Object { "licenseSku": "Enterprise", } } /> </React.Fragment> <Memo(Connect(RenewalLink)) telemetryInfo={ Object { "error": "renew_license_banner_fail", "success": "renew_license_banner_success", } } /> </div> } showCloseButton={true} tooltipMsg={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(MemoizedFormattedMessage) defaultMessage="{licenseSku} license is expired and some features may be disabled." id="announcement_bar.error.license_expired" values={ Object { "licenseSku": "Enterprise", } } /> </React.Fragment> } type="critical" /> `; exports[`components/ConfigurationBar should match snapshot, expired, regular user 1`] = ` <Connect(AnnouncementBar) message={ <React.Fragment> <img className="advisor-icon" src={null} /> <Memo(MemoizedFormattedMessage) defaultMessage="{licenseSku} license is expired and some features may be disabled. Please contact your System Administrator for details." id="announcement_bar.error.past_grace" values={ Object { "licenseSku": "Enterprise", } } /> </React.Fragment> } type="critical" /> `; exports[`components/ConfigurationBar should match snapshot, expiring, cloud license, show nothing 1`] = `""`; exports[`components/ConfigurationBar should match snapshot, expiring, trial license 1`] = ` <Connect(AnnouncementBar) handleClose={[Function]} message={ <div className="announcement-bar__configuration" > <React.Fragment> <img className="advisor-icon" src={null} /> This is the last day of your free trial. Purchase a license now to continue using Mattermost Professional and Enterprise features. </React.Fragment> <PurchaseLink buttonTextElement={ <Memo(MemoizedFormattedMessage) defaultMessage="Purchase a License Now" id="announcement_bar.error.purchase_a_license_now" /> } /> </div> } showCloseButton={true} tooltipMsg={ <React.Fragment> <img className="advisor-icon" src={null} /> This is the last day of your free trial. Purchase a license now to continue using Mattermost Professional and Enterprise features. </React.Fragment> } type="critical" /> `; exports[`components/ConfigurationBar should match snapshot, expiring, trial license, mobile viewport 1`] = ` <Connect(AnnouncementBar) handleClose={[Function]} message={ <div className="announcement-bar__configuration" > <React.Fragment> <img className="advisor-icon" src={null} /> This is the last day of your free trial. </React.Fragment> <PurchaseLink buttonTextElement={ <Memo(MemoizedFormattedMessage) defaultMessage="Purchase a License Now" id="announcement_bar.error.purchase_a_license_now" /> } /> </div> } showCloseButton={true} tooltipMsg={ <React.Fragment> <img className="advisor-icon" src={null} /> This is the last day of your free trial. </React.Fragment> } type="critical" /> `; exports[`components/ConfigurationBar should match snapshot, show nothing 1`] = `""`;
1,544
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/notify_admin_downgrade_delinquency_bar/notify_admin_downgrade_delinquency_bar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {savePreferences} from 'mattermost-redux/actions/preferences'; import {Client4} from 'mattermost-redux/client'; import {trackEvent} from 'actions/telemetry_actions'; import { fireEvent, renderWithContext, screen, waitFor, } from 'tests/react_testing_utils'; import {CloudProducts, Preferences, TELEMETRY_CATEGORIES} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import NotifyAdminDowngradeDeliquencyBar, {BannerPreferenceName} from './index'; jest.mock('actions/telemetry_actions', () => ({ trackEvent: jest.fn(), })); jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn().mockReturnValue(() => {}), })); jest.mock('mattermost-redux/actions/preferences', () => ({ savePreferences: jest.fn(), })); describe('components/announcement_bar/notify_admin_downgrade_delinquency_bar', () => { const initialState = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, preferences: { myPreferences: {}, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {id: 'id', roles: 'system_user'}, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', delinquent_since: 1652807380, // may 17 2022 }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, test_prod_2: { id: 'test_prod_2', sku: CloudProducts.ENTERPRISE, price_per_seat: 0, }, test_prod_3: { id: 'test_prod_3', sku: CloudProducts.PROFESSIONAL, price_per_seat: 0, }, }, }, }, }; beforeEach(() => { jest.clearAllMocks(); }); it('Should not show banner when there isn\'t delinquency', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.cloud.subscription = { product_id: 'test_prod_1', trial_end_at: 1652807380, is_free_trial: 'false', }; renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, state); expect(screen.queryByText('Your workspace has been downgraded. Notify your admin to fix billing issues')).not.toBeInTheDocument(); }); it('Should not show banner when deliquency is less than 90 days', () => { jest.useFakeTimers().setSystemTime(new Date('2022-06-20')); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, initialState); expect(screen.queryByText('Your workspace has been downgraded. Notify your admin to fix billing issues')).not.toBeInTheDocument(); }); it('Should not show banner when the user has notify their admin', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.preferences.myPreferences = TestHelper.getPreferencesMock( [ { category: Preferences.NOTIFY_ADMIN_REVOKE_DOWNGRADED_WORKSPACE, name: BannerPreferenceName, value: 'adminNotified', }, ], ); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, state); expect(screen.queryByText('Your workspace has been downgraded. Notify your admin to fix billing issues')).not.toBeInTheDocument(); }); it('Should not show banner when the user closed the banner', () => { const state = JSON.parse(JSON.stringify(initialState)); state.entities.preferences.myPreferences = TestHelper.getPreferencesMock( [ { category: Preferences.NOTIFY_ADMIN_REVOKE_DOWNGRADED_WORKSPACE, name: BannerPreferenceName, value: 'dismissBanner', }, ], ); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, state); expect(screen.queryByText('Your workspace has been downgraded. Notify your admin to fix billing issues')).not.toBeInTheDocument(); }); it('Should not show banner when the user is an admin', () => { jest.useFakeTimers().setSystemTime(new Date('2022-08-17')); const state = JSON.parse(JSON.stringify(initialState)); state.entities.users.profiles.current_user_id = {roles: 'system_admin'}; renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, state); expect(screen.queryByText('Your workspace has been downgraded. Notify your admin to fix billing issues')).not.toBeInTheDocument(); }); it('Should not save the preferences if the user can\'t notify', () => { jest.useFakeTimers().setSystemTime(new Date('2022-08-17')); Client4.notifyAdmin = jest.fn(); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, initialState); expect(savePreferences).not.toBeCalled(); }); it('Should show banner when deliquency is higher than 90 days', () => { jest.useFakeTimers().setSystemTime(new Date('2022-08-17')); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, initialState); expect(screen.getByText('Your workspace has been downgraded. Notify your admin to fix billing issues')).toBeInTheDocument(); }); it('Should save the preferences if the user close the banner', async () => { jest.useFakeTimers().setSystemTime(new Date('2022-08-17')); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, initialState); fireEvent.click(screen.getByRole('link')); expect(savePreferences).toBeCalledTimes(1); expect(savePreferences).toBeCalledWith(initialState.entities.users.profiles.current_user_id.id, [{ category: Preferences.NOTIFY_ADMIN_REVOKE_DOWNGRADED_WORKSPACE, name: BannerPreferenceName, user_id: initialState.entities.users.profiles.current_user_id.id, value: 'dismissBanner', }]); }); it('Should save the preferences and track event after notify their admin', async () => { jest.useFakeTimers().setSystemTime(new Date('2022-08-17')); Client4.notifyAdmin = jest.fn(); renderWithContext(<NotifyAdminDowngradeDeliquencyBar/>, initialState); fireEvent.click(screen.getByText('Notify admin')); await waitFor(() => { expect(savePreferences).toBeCalledTimes(1); expect(savePreferences).toBeCalledWith(initialState.entities.users.profiles.current_user_id.id, [{ category: Preferences.NOTIFY_ADMIN_REVOKE_DOWNGRADED_WORKSPACE, name: BannerPreferenceName, user_id: initialState.entities.users.profiles.current_user_id.id, value: 'adminNotified', }]); expect(trackEvent).toBeCalledTimes(2); expect(trackEvent).toHaveBeenNthCalledWith(1, TELEMETRY_CATEGORIES.CLOUD_DELINQUENCY, 'click_notify_admin_upgrade_workspace_banner'); expect(trackEvent).toHaveBeenNthCalledWith(2, TELEMETRY_CATEGORIES.CLOUD_DELINQUENCY, 'notify_admin_downgrade_delinquency_bar', undefined); }); }); });
1,547
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/overage_users_banner/overage_users_banner.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {DeepPartial} from '@mattermost/types/utilities'; import {getLicenseSelfServeStatus} from 'mattermost-redux/actions/cloud'; import {savePreferences} from 'mattermost-redux/actions/preferences'; import {General} from 'mattermost-redux/constants'; import {trackEvent} from 'actions/telemetry_actions'; import {fireEvent, renderWithContext, screen} from 'tests/react_testing_utils'; import {OverActiveUserLimits, Preferences, SelfHostedProducts, StatTypes} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import {generateId} from 'utils/utils'; import type {GlobalState} from 'types/store'; import OverageUsersBanner from './index'; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn().mockReturnValue(() => {}), })); jest.mock('mattermost-redux/actions/preferences', () => ({ savePreferences: jest.fn(), })); jest.mock('mattermost-redux/actions/cloud', () => ({ getLicenseSelfServeStatus: jest.fn(), })); jest.mock('actions/telemetry_actions', () => ({ trackEvent: jest.fn(), })); const seatsPurchased = 40; const email = '[email protected]'; const seatsMinimumFor5PercentageState = (Math.ceil(seatsPurchased * OverActiveUserLimits.MIN)) + seatsPurchased; const seatsMinimumFor10PercentageState = (Math.ceil(seatsPurchased * OverActiveUserLimits.MAX)) + seatsPurchased; const text5PercentageState = `(Only visible to admins) Your workspace user count has exceeded your paid license seat count by ${seatsMinimumFor5PercentageState - seatsPurchased} seats. Purchase additional seats to remain compliant.`; const text10PercentageState = `(Only visible to admins) Your workspace user count has exceeded your paid license seat count by ${seatsMinimumFor10PercentageState - seatsPurchased} seats. Purchase additional seats to remain compliant.`; const contactSalesTextLink = 'Contact Sales'; const expandSeatsTextLink = 'Purchase additional seats'; const licenseId = generateId(); describe('components/overage_users_banner', () => { const initialState: DeepPartial<GlobalState> = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { users: { currentUserId: 'current_user', profiles: { current_user: { roles: General.SYSTEM_ADMIN_ROLE, id: 'currentUser', email, }, }, }, admin: { analytics: { [StatTypes.TOTAL_USERS]: 1, }, }, general: { config: { CWSURL: 'http://testing', }, license: { IsLicensed: 'true', IssuedAt: '1517714643650', StartsAt: '1517714643650', ExpiresAt: '1620335443650', SkuShortName: 'Enterprise', Name: 'LicenseName', Company: 'Mattermost Inc.', Users: String(seatsPurchased), Email: '[email protected]', Id: licenseId, }, }, preferences: { myPreferences: {}, }, cloud: { subscriptionStats: { is_expandable: false, getRequestState: 'IDLE', }, }, hostedCustomer: { products: { productsLoaded: true, products: { prod_professional: TestHelper.getProductMock({ id: 'prod_professional', name: 'Professional', sku: SelfHostedProducts.PROFESSIONAL, price_per_seat: 7.5, }), }, }, }, }, }; let windowSpy: jest.SpyInstance; beforeAll(() => { windowSpy = jest.spyOn(window, 'open'); windowSpy.mockImplementation(() => {}); }); afterAll(() => { windowSpy.mockRestore(); }); it('should not render the banner because we are not on overage state', () => { renderWithContext(<OverageUsersBanner/>); expect(screen.queryByText('(Only visible to admins) Your workspace user count has exceeded your paid license seat count by', {exact: false})).not.toBeInTheDocument(); expect(getLicenseSelfServeStatus).not.toBeCalled(); }); it('should not render the banner because we are not admins', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.users = { ...store.entities.users, profiles: { ...store.entities.users.profiles, current_user: { ...store.entities.users.profiles.current_user, roles: General.SYSTEM_USER_ROLE, }, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.queryByText('Your workspace user count has exceeded your paid license seat count by', {exact: false})).not.toBeInTheDocument(); expect(getLicenseSelfServeStatus).not.toBeCalled(); }); it('should not render the banner because it\'s cloud licenese', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.general.license = { ...store.entities.general.license, Cloud: 'true', }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.queryByText('Your workspace user count has exceeded your paid license seat count by', {exact: false})).not.toBeInTheDocument(); expect(getLicenseSelfServeStatus).not.toBeCalled(); }); it('should not render the 5% banner because we have dissmised it', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.preferences.myPreferences = TestHelper.getPreferencesMock( [ { category: Preferences.OVERAGE_USERS_BANNER, value: 'Overage users banner watched', name: `warn_overage_seats_${licenseId.substring(0, 8)}`, }, ], ); store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.queryByText(text5PercentageState)).not.toBeInTheDocument(); expect(getLicenseSelfServeStatus).not.toBeCalled(); }); it('should render the banner because we are over 5% and we don\'t have any preferences', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { is_expandable: false, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.getByText(text5PercentageState)).toBeInTheDocument(); expect(screen.getByText(contactSalesTextLink)).toBeInTheDocument(); }); it('should track if the admin click Contact Sales CTA in a 10% overage state', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { is_expandable: false, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); fireEvent.click(screen.getByText(contactSalesTextLink)); expect(windowSpy).toBeCalledTimes(1); // only the email is encoded and other params are empty. See logic for useOpenSalesLink hook const salesLinkWithEncodedParams = 'https://mattermost.com/contact-sales/?qk=&qp=&qw=&qx=dGVzdEBtYXR0ZXJtb3N0LmNvbQ==&utm_source=mattermost&utm_medium=in-product'; expect(windowSpy).toBeCalledWith(salesLinkWithEncodedParams, '_blank'); expect(trackEvent).toBeCalledTimes(1); expect(trackEvent).toBeCalledWith('insights', 'click_true_up_warning', { cta: 'Contact Sales', banner: 'global banner', }); }); it('should render the banner because we are over 5% and we have preferences from one old banner', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { is_expandable: false, getRequestState: 'OK', }, }; store.entities.preferences.myPreferences = TestHelper.getPreferencesMock( [ { category: Preferences.OVERAGE_USERS_BANNER, value: 'Overage users banner watched', name: `warn_overage_seats_${10}`, }, ], ); store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.getByText(text5PercentageState)).toBeInTheDocument(); expect(screen.getByText(contactSalesTextLink)).toBeInTheDocument(); }); it('should save the preferences for 5% banner if admin click on close', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); fireEvent.click(screen.getByRole('link')); expect(savePreferences).toBeCalledTimes(1); expect(savePreferences).toBeCalledWith(store.entities.users.profiles.current_user.id, [{ category: Preferences.OVERAGE_USERS_BANNER, name: `warn_overage_seats_${licenseId.substring(0, 8)}`, user_id: store.entities.users.profiles.current_user.id, value: 'Overage users banner watched', }]); }); it('should render the banner because we are over 10%', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { is_expandable: false, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor10PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.getByText(text10PercentageState)).toBeInTheDocument(); expect(screen.getByText(contactSalesTextLink)).toBeInTheDocument(); }); it('should track if the admin click Contact Sales CTA in a 10% overage state', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { is_expandable: false, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor10PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); fireEvent.click(screen.getByText(contactSalesTextLink)); expect(windowSpy).toBeCalledTimes(1); // only the email is encoded and other params are empty. See logic for useOpenSalesLink hook const salesLinkWithEncodedParams = 'https://mattermost.com/contact-sales/?qk=&qp=&qw=&qx=dGVzdEBtYXR0ZXJtb3N0LmNvbQ==&utm_source=mattermost&utm_medium=in-product'; expect(windowSpy).toBeCalledWith(salesLinkWithEncodedParams, '_blank'); expect(trackEvent).toBeCalledTimes(1); expect(trackEvent).toBeCalledWith('insights', 'click_true_up_error', { cta: 'Contact Sales', banner: 'global banner', }); }); it('should render the warning banner with expansion seats CTA if the license is expandable', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { ...store.entities.cloud.subscriptionStats, is_expandable: true, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.getByText(expandSeatsTextLink)).toBeInTheDocument(); }); it('should track if the admin click expansion seats CTA in a 5% overage state', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { ...store.entities.cloud.subscriptionStats, is_expandable: true, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor5PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); fireEvent.click(screen.getByText(expandSeatsTextLink)); expect(windowSpy).toBeCalledTimes(1); expect(windowSpy).toBeCalledWith(`http://testing/subscribe/expand?licenseId=${licenseId}`, '_blank'); expect(trackEvent).toBeCalledTimes(1); expect(trackEvent).toBeCalledWith('insights', 'click_true_up_warning', { cta: 'Self Serve', banner: 'global banner', }); }); it('should render the error banner with expansion seats CTA if the license is be expandable', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { ...store.entities.cloud.subscriptionStats, is_expandable: true, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor10PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); expect(screen.getByText(expandSeatsTextLink)).toBeInTheDocument(); }); it('should track if the admin click expansion seats CTA in a 10% overage state', () => { const store = JSON.parse(JSON.stringify(initialState)); store.entities.cloud = { ...store.entities.cloud, subscriptionStats: { ...store.entities.cloud.subscriptionStats, is_expandable: true, getRequestState: 'OK', }, }; store.entities.admin = { ...store.entities.admin, analytics: { [StatTypes.TOTAL_USERS]: seatsMinimumFor10PercentageState, }, }; renderWithContext(<OverageUsersBanner/>, store); fireEvent.click(screen.getByText(expandSeatsTextLink)); expect(windowSpy).toBeCalledTimes(1); expect(windowSpy).toBeCalledWith(`http://testing/subscribe/expand?licenseId=${licenseId}`, '_blank'); expect(trackEvent).toBeCalledTimes(1); expect(trackEvent).toBeCalledWith('insights', 'click_true_up_error', { cta: 'Self Serve', banner: 'global banner', }); }); });
1,548
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/payment_announcement_bar/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import * as cloudActions from 'mattermost-redux/actions/cloud'; import {renderWithContext, screen} from 'tests/react_testing_utils'; import {CloudProducts} from 'utils/constants'; import PaymentAnnouncementBar from './'; jest.mock('mattermost-redux/actions/cloud', () => { const original = jest.requireActual('mattermost-redux/actions/cloud'); return { ...original, __esModule: true, // just testing that it fired, not that the result updated or anything like that getCloudCustomer: jest.fn(() => ({type: 'bogus'})), }; }); describe('PaymentAnnouncementBar', () => { const happyPathStore = { entities: { users: { currentUserId: 'me', profiles: { me: { roles: 'system_admin', }, }, }, general: { license: { Cloud: 'true', }, }, cloud: { subscription: { product_id: 'prod_something', last_invoice: { status: 'failed', }, }, customer: { payment_method: { exp_month: 12, exp_year: (new Date()).getFullYear() + 1, }, }, products: { prod_something: { id: 'prod_something', sku: CloudProducts.PROFESSIONAL, }, }, }, }, views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, }; it('when most recent payment failed, shows that', () => { renderWithContext(<PaymentAnnouncementBar/>, happyPathStore); screen.getByText('Your most recent payment failed'); }); it('when card is expired, shows that', () => { const store = JSON.parse(JSON.stringify(happyPathStore)); store.entities.cloud.customer.payment_method.exp_year = (new Date()).getFullYear() - 1; store.entities.cloud.subscription.last_invoice.status = 'success'; renderWithContext(<PaymentAnnouncementBar/>, store); screen.getByText('Your credit card has expired', {exact: false}); }); it('when needed, fetches, customer', () => { const store = JSON.parse(JSON.stringify(happyPathStore)); store.entities.cloud.customer = null; store.entities.cloud.subscription.last_invoice.status = 'success'; renderWithContext(<PaymentAnnouncementBar/>, store); expect(cloudActions.getCloudCustomer).toHaveBeenCalled(); }); it('when not an admin, does not fetch customer', () => { const store = JSON.parse(JSON.stringify(happyPathStore)); store.entities.users.profiles.me.roles = ''; renderWithContext(<PaymentAnnouncementBar/>, store); expect(cloudActions.getCloudCustomer).not.toHaveBeenCalled(); }); });
1,554
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/renewal_link/renewal_link.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 {act} from 'react-dom/test-utils'; import {Provider} from 'react-redux'; import {Client4} from 'mattermost-redux/client'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import RenewalLink from './renewal_link'; const initialState = { views: { announcementBar: { announcementBarState: { announcementBarCount: 1, }, }, }, entities: { general: { config: { CWSURL: '', }, license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_user'}, }, }, preferences: { myPreferences: {}, }, cloud: {}, }, }; const actImmediate = (wrapper: ReactWrapper) => act( () => new Promise<void>((resolve) => { setImmediate(() => { wrapper.update(); resolve(); }); }), ); describe('components/RenewalLink', () => { afterEach(() => { jest.clearAllMocks(); }); const props = { actions: { openModal: jest.fn, }, }; test('should show Renew now when a renewal link is successfully returned', async () => { const getRenewalLinkSpy = jest.spyOn(Client4, 'getRenewalLink'); const promise = new Promise<{renewal_link: string}>((resolve) => { resolve({ renewal_link: 'https://testrenewallink', }); }); getRenewalLinkSpy.mockImplementation(() => promise); const store = mockStore(initialState); const wrapper = mountWithIntl(<Provider store={store}><RenewalLink {...props}/></Provider>); // wait for the promise to resolve and component to update await actImmediate(wrapper); expect(wrapper.find('.btn').text().includes('Renew license now')).toBe(true); }); test('should show Contact sales when a renewal link is not returned', async () => { const getRenewalLinkSpy = jest.spyOn(Client4, 'getRenewalLink'); const promise = new Promise<{renewal_link: string}>((resolve, reject) => { reject(new Error('License cannot be renewed from portal')); }); getRenewalLinkSpy.mockImplementation(() => promise); const store = mockStore(initialState); const wrapper = mountWithIntl(<Provider store={store}><RenewalLink {...props}/></Provider>); // wait for the promise to resolve and component to update await actImmediate(wrapper); expect(wrapper.find('.btn').text().includes('Contact sales')).toBe(true); }); });
1,556
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/show_start_trial_modal/show_start_trial_modal.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 ShowStartTrialModal from 'components/announcement_bar/show_start_trial_modal/show_start_trial_modal'; import * as getTotalUsersHook from 'components/common/hooks/useGetTotalUsersNoBots'; let mockState: any; const mockDispatch = jest.fn(); jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); describe('components/sidebar/show_start_trial_modal', () => { beforeEach(() => { const now = new Date().getTime(); // required state to mount using the provider mockState = { entities: { admin: { prevTrialLicense: { IsLicensed: 'false', }, }, preferences: { myPreferences: { 'start_trial_modal--trial_modal_auto_shown': { name: 'trial_modal_auto_shown', value: 'false', }, }, }, general: { config: { InstallationDate: now, }, license: { IsLicensed: 'false', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_user'}, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission', 'add_user_to_team', 'invite_guest']}, team_role: {permissions: ['test_team_no_permission']}, }, }, }, views: { modals: { modalState: { trial_benefits_modal: { open: false, }, }, }, }, }; }); test('should match snapshot', () => { const wrapper = shallow( <ShowStartTrialModal/>, ); expect(wrapper).toMatchSnapshot(); }); test('should NOT dispatch the modal when there are less than 10 users', () => { const lessThan10Users = 9; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => lessThan10Users); const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }; const moreThan6Hours = { config: { // installation date is set to be 10 hours before current time InstallationDate: new Date().getTime() - ((10 * 60 * 60) * 1000), }, }; mockState = {...mockState, entities: {...mockState.entities, users: isAdminUser, general: moreThan6Hours}}; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT dispatch the modal when the env has less than 6 hours of creation', () => { const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }; const moreThan10Users = 11; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => moreThan10Users); const lessThan6Hours = { config: { // installation date is set to be 5 hours before current time InstallationDate: new Date().getTime() - ((5 * 60 * 60) * 1000), }, }; mockState = {...mockState, entities: {...mockState.entities, users: isAdminUser, general: lessThan6Hours}}; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT dispatch the modal when the env has previous license', () => { const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }; const moreThan10UsersAndPrevLicensed = { prevTrialLicense: { IsLicensed: 'true', }, }; const moreThan10Users = 11; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => moreThan10Users); mockState = {...mockState, entities: {...mockState.entities, users: isAdminUser, admin: moreThan10UsersAndPrevLicensed}}; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT dispatch the modal when the env is currently licensed', () => { const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }; const moreThan10Users = 11; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => moreThan10Users); const moreThan6HoursAndLicensed = { config: { // installation date is set to be 10 hours before current time InstallationDate: new Date().getTime() - ((10 * 60 * 60) * 1000), }, license: { IsLicensed: 'true', }, }; mockState = {...mockState, entities: {...mockState.entities, users: isAdminUser, general: moreThan6HoursAndLicensed}}; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT dispatch the modal when the modal has been already dismissed', () => { const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }; const moreThan10Users = 11; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => moreThan10Users); const moreThan6Hours = { config: { // installation date is set to be 10 hours before current time InstallationDate: new Date().getTime() - ((10 * 60 * 60) * 1000), }, }; const modalDismissed = { myPreferences: { 'start_trial_modal--trial_modal_auto_shown': { name: 'trial_modal_auto_shown', value: 'true', }, }, }; mockState = { ...mockState, entities: { ...mockState.entities, users: isAdminUser, general: moreThan6Hours, preferences: modalDismissed, }, }; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT dispatch the modal when user is not an admin', () => { const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_user'}, }, }; const moreThan10Users = 11; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => moreThan10Users); const notPreviouslyLicensed = { prevTrialLicense: { IsLicensed: 'false', }, }; const moreThan6Hours = { config: { // installation date is set to be 10 hours before current time InstallationDate: new Date().getTime() - ((10 * 60 * 60) * 1000), }, license: { IsLicensed: 'false', }, }; mockState = {...mockState, entities: {...mockState.entities, users: isAdminUser, admin: notPreviouslyLicensed, general: moreThan6Hours}}; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should dispatch the modal when there are more than 10 users', () => { const isAdminUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }; const moreThan10Users = 11; jest.spyOn(getTotalUsersHook, 'default').mockImplementation(() => moreThan10Users); const notPreviouslyLicensed = { prevTrialLicense: { IsLicensed: 'false', }, }; const moreThan6Hours = { config: { // installation date is set to be 10 hours before current time InstallationDate: new Date().getTime() - ((10 * 60 * 60) * 1000), }, license: { IsLicensed: 'false', }, }; mockState = {...mockState, entities: {...mockState.entities, users: isAdminUser, admin: notPreviouslyLicensed, general: moreThan6Hours}}; mount( <ShowStartTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(1); }); });
1,558
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/show_start_trial_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/show_start_trial_modal/__snapshots__/show_start_trial_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/sidebar/show_start_trial_modal should match snapshot 1`] = `""`;
1,559
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/show_tree_days_left_trial_modal/show_three_days_left_trial_modal.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 ShowThreeDaysLeftTrialModal from 'components/announcement_bar/show_tree_days_left_trial_modal/show_three_days_left_trial_modal'; import {CloudProducts} from 'utils/constants'; import {FileSizes} from 'utils/file_utils'; let mockState: any; const mockDispatch = jest.fn(); const nowMiliseconds = new Date().getTime(); const oneDayMs = 24 * 60 * 60 * 1000; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); describe('components/sidebar/show_three_days_left_trial_modal', () => { beforeEach(() => { // required state to mount using the provider mockState = { entities: { admin: {}, preferences: { myPreferences: { 'cloud_trial_banner--dismiss_3_days_left_trial_modal': { name: 'dismiss_3_days_left_trial_modal', value: 'false', }, }, }, general: { license: { IsLicensed: 'true', Cloud: 'true', }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_admin system_user'}, }, }, cloud: { subscription: { product_id: 'test_prod_1', trial_end_at: nowMiliseconds + (2 * oneDayMs), is_free_trial: 'true', }, products: { test_prod_1: { id: 'test_prod_1', sku: CloudProducts.STARTER, price_per_seat: 0, }, test_prod_2: { id: 'test_prod_2', sku: CloudProducts.ENTERPRISE, price_per_seat: 0, }, test_prod_3: { id: 'test_prod_3', sku: CloudProducts.PROFESSIONAL, price_per_seat: 0, }, }, limits: { limitsLoaded: true, limits: { integrations: { enabled: 10, }, messages: { history: 10000, }, files: { total_storage: FileSizes.Gigabyte, }, teams: { active: 1, }, boards: { cards: 500, views: 5, }, }, }, }, roles: { roles: { system_role: {permissions: ['test_system_permission', 'add_user_to_team', 'invite_guest']}, team_role: {permissions: ['test_team_no_permission']}, }, }, usage: { files: { totalStorage: 0, totalStorageLoaded: true, }, messages: { history: 0, historyLoaded: true, }, boards: { cards: 0, cardsLoaded: true, }, integrations: { enabled: 3, enabledLoaded: true, }, teams: { active: 0, cloudArchived: 0, teamsLoaded: true, }, }, }, views: { modals: { modalState: { show_three_days_left_trial_modal: { open: false, }, }, }, }, }; }); test('should show the modal when is cloud, free trial, admin, have not dimissed previously and there are less than 3 days in the trial, ', () => { mount( <ShowThreeDaysLeftTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(1); }); test('should NOT show the modal when user is not Admin', () => { const endUser = { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_user'}, }, }; mockState = { ...mockState, entities: { ...mockState.entities, users: endUser, }, }; mount( <ShowThreeDaysLeftTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT show the modal when is not Cloud', () => { mockState = {...mockState, entities: {...mockState.entities, general: {...mockState.general, license: {Cloud: 'false'}}}}; mount( <ShowThreeDaysLeftTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT show the modal when is not Free Trial', () => { mockState = { ...mockState, entities: { ...mockState.entities, cloud: { ...mockState.entities.cloud, subscription: { ...mockState.entities.cloud.subscription, is_free_trial: 'false', }, }, }, }; mount( <ShowThreeDaysLeftTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT show the modal when there are MORE than three days left in the trial', () => { mockState = { ...mockState, entities: { ...mockState.entities, general: { ...mockState.general, license: { Cloud: 'true', }, }, cloud: { ...mockState.entities.cloud, subscription: { ...mockState.entities.cloud.subscription, is_free_trial: 'true', trial_end_at: nowMiliseconds + (6 * oneDayMs), }, }, }, }; mount( <ShowThreeDaysLeftTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); test('should NOT show the modal when admin have already dismissed the modal', () => { const modalDismissedPreference = { myPreferences: { 'cloud_trial_banner--dismiss_3_days_left_trial_modal': { name: 'dismiss_3_days_left_trial_modal', value: 'true', }, }, }; mockState = { ...mockState, entities: { ...mockState.entities, preferences: modalDismissedPreference, }, }; mount( <ShowThreeDaysLeftTrialModal/>, ); expect(mockDispatch).toHaveBeenCalledTimes(0); }); });
1,562
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/version_bar/version_bar.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 AnnouncementBar from 'components/announcement_bar/default_announcement_bar'; import VersionBar from 'components/announcement_bar/version_bar/version_bar'; describe('components/VersionBar', () => { test('should match snapshot - bar rendered after build hash change', () => { const wrapper = shallow( <VersionBar buildHash='844f70a08ead47f06232ecb6fcad63d2'/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(AnnouncementBar).exists()).toBe(false); wrapper.setProps({buildHash: '83ea110da12da84442f92b4634a1e0e2'}); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(AnnouncementBar).exists()).toBe(true); }); });
1,564
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/version_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/announcement_bar/version_bar/__snapshots__/version_bar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/VersionBar should match snapshot - bar rendered after build hash change 1`] = `""`; exports[`components/VersionBar should match snapshot - bar rendered after build hash change 2`] = ` <Connect(AnnouncementBar) message={ <React.Fragment> <Memo(MemoizedFormattedMessage) defaultMessage="A new version of Mattermost is available." id="version_bar.new" /> <a onClick={[Function]} style={ Object { "marginLeft": ".5rem", } } > <Memo(MemoizedFormattedMessage) defaultMessage="Refresh the app now" id="version_bar.refresh" /> </a> . </React.Fragment> } type="announcement" /> `;
1,566
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/app_bar/app_bar.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 type {AppBinding} from '@mattermost/types/apps'; import {Permissions} from 'mattermost-redux/constants'; import {AppBindingLocations} from 'mattermost-redux/constants/apps'; import type {GlobalState} from 'types/store'; import type {PluginComponent} from 'types/store/plugins'; import AppBar from './app_bar'; import 'jest-styled-components'; const mockDispatch = jest.fn(); let mockState: GlobalState; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useSelector: (selector: (state: typeof mockState) => unknown) => selector(mockState), useDispatch: () => mockDispatch, })); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom') as typeof import('react-router-dom'), useLocation: () => { return { pathname: '', }; }, })); describe('components/app_bar/app_bar', () => { beforeEach(() => { mockState = { views: { rhs: { isSidebarOpen: true, rhsState: 'plugin', pluggableId: 'the_rhs_plugin_component', }, }, plugins: { components: { AppBar: channelHeaderComponents, RightHandSidebarComponent: rhsComponents, Product: [], } as {[componentName: string]: PluginComponent[]}, }, entities: { apps: { main: { bindings: channelHeaderAppBindings, } as {bindings: AppBinding[]}, pluginEnabled: true, }, general: { config: { DisableAppBar: 'false', FeatureFlagAppsEnabled: 'true', } as any, }, channels: { currentChannelId: 'currentchannel', channels: { currentchannel: { id: 'currentchannel', }, } as any, myMembers: { currentchannel: { id: 'memberid', }, } as any, }, teams: { currentTeamId: 'currentteam', }, preferences: { myPreferences: { }, } as any, users: { currentUserId: 'user1', profiles: { user1: { roles: 'system_user', }, }, } as any, roles: { roles: { system_user: { permissions: [], }, }, } as any, }, } as GlobalState; }); const channelHeaderComponents: PluginComponent[] = [ { id: 'the_component_id', pluginId: 'playbooks', icon: 'fallback_component' as any, tooltipText: 'Playbooks Tooltip', action: jest.fn(), }, ]; const rhsComponents: PluginComponent[] = [ { id: 'the_rhs_plugin_component_id', pluginId: 'playbooks', icon: <div/>, action: jest.fn(), }, ]; const channelHeaderAppBindings: AppBinding[] = [ { location: AppBindingLocations.CHANNEL_HEADER_ICON, bindings: [ { app_id: 'com.mattermost.zendesk', label: 'Create Subscription', }, ], }, ] as AppBinding[]; test('should match snapshot on mount', async () => { const wrapper = mount( <AppBar/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot on mount when App Bar is disabled', async () => { mockState.entities.general.config.DisableAppBar = 'false'; const wrapper = mount( <AppBar/>, ); expect(wrapper).toMatchSnapshot(); }); test('should not show marketplace if disabled or user does not have SYSCONSOLE_WRITE_PLUGINS permission', async () => { mockState.entities.general = { config: { DisableAppBar: 'true', FeatureFlagAppsEnabled: 'true', EnableMarketplace: 'true', PluginsEnabled: 'true', }, } as any; const wrapper = shallow( <AppBar/>, ); expect(wrapper.find('AppBarMarketplace').exists()).toEqual(false); }); test('should show marketplace if enabled and user has SYSCONSOLE_WRITE_PLUGINS permission', async () => { mockState.entities.general = { config: { DisableAppBar: 'false', FeatureFlagAppsEnabled: 'true', EnableMarketplace: 'true', PluginsEnabled: 'true', }, } as any; mockState.entities.roles = { roles: { system_user: { permissions: [ Permissions.SYSCONSOLE_WRITE_PLUGINS, ], }, }, } as any; const wrapper = shallow( <AppBar/>, ); expect(wrapper.find('AppBarMarketplace').exists()).toEqual(true); }); });
1,572
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/app_bar
petrpan-code/mattermost/mattermost/webapp/channels/src/components/app_bar/__snapshots__/app_bar.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/app_bar/app_bar should match snapshot on mount 1`] = ` <AppBar> <div className="app-bar" > <div className="app-bar__top" > <AppBarPluginComponent component={ Object { "action": [MockFunction], "icon": "fallback_component", "id": "the_component_id", "pluginId": "playbooks", "tooltipText": "Playbooks Tooltip", } } key="the_component_id" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="pluginTooltip-app-bar-icon-playbooks" placement="right" > <span> Playbooks Tooltip </span> </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="pluginTooltip-app-bar-icon-playbooks" intl={null} placement="right" > <span> Playbooks Tooltip </span> </OverlayWrapper> } placement="left" trigger={ Array [ "hover", "focus", ] } > <div className="app-bar__icon" id="app-bar-icon-playbooks" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <div className="app-bar__old-icon app-bar__icon-inner app-bar__icon-inner--centered" role="button" tabIndex={0} > fallback_component </div> </div> </OverlayTrigger> </OverlayTrigger> </AppBarPluginComponent> <hr className="app-bar__divider" key="divider" /> <AppBarBinding binding={ Object { "app_id": "com.mattermost.zendesk", "label": "Create Subscription", } } key="com.mattermost.zendesk_Create Subscription" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="tooltip-app-bar-icon-com.mattermost.zendesk" placement="right" > <span> Create Subscription </span> </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="tooltip-app-bar-icon-com.mattermost.zendesk" intl={null} placement="right" > <span> Create Subscription </span> </OverlayWrapper> } placement="left" trigger={ Array [ "hover", "focus", ] } > <div aria-label="Create Subscription" className="app-bar__icon" id="app-bar-icon-com.mattermost.zendesk" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <div className="app-bar__icon-inner" > <img /> </div> </div> </OverlayTrigger> </OverlayTrigger> </AppBarBinding> </div> </div> </AppBar> `; exports[`components/app_bar/app_bar should match snapshot on mount when App Bar is disabled 1`] = ` <AppBar> <div className="app-bar" > <div className="app-bar__top" > <AppBarPluginComponent component={ Object { "action": [MockFunction], "icon": "fallback_component", "id": "the_component_id", "pluginId": "playbooks", "tooltipText": "Playbooks Tooltip", } } key="the_component_id" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="pluginTooltip-app-bar-icon-playbooks" placement="right" > <span> Playbooks Tooltip </span> </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="pluginTooltip-app-bar-icon-playbooks" intl={null} placement="right" > <span> Playbooks Tooltip </span> </OverlayWrapper> } placement="left" trigger={ Array [ "hover", "focus", ] } > <div className="app-bar__icon" id="app-bar-icon-playbooks" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <div className="app-bar__old-icon app-bar__icon-inner app-bar__icon-inner--centered" role="button" tabIndex={0} > fallback_component </div> </div> </OverlayTrigger> </OverlayTrigger> </AppBarPluginComponent> <hr className="app-bar__divider" key="divider" /> <AppBarBinding binding={ Object { "app_id": "com.mattermost.zendesk", "label": "Create Subscription", } } key="com.mattermost.zendesk_Create Subscription" > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip bsClass="tooltip" id="tooltip-app-bar-icon-com.mattermost.zendesk" placement="right" > <span> Create Subscription </span> </Tooltip> } placement="left" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper bsClass="tooltip" id="tooltip-app-bar-icon-com.mattermost.zendesk" intl={null} placement="right" > <span> Create Subscription </span> </OverlayWrapper> } placement="left" trigger={ Array [ "hover", "focus", ] } > <div aria-label="Create Subscription" className="app-bar__icon" id="app-bar-icon-com.mattermost.zendesk" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <div className="app-bar__icon-inner" > <img /> </div> </div> </OverlayTrigger> </OverlayTrigger> </AppBarBinding> </div> </div> </AppBar> `;
1,574
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/apps_form_component.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 {Provider} from 'react-redux'; import {AppCallResponseTypes} from 'mattermost-redux/constants/apps'; import Markdown from 'components/markdown'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import {AppsForm} from './apps_form_component'; import type {Props} from './apps_form_component'; describe('AppsFormComponent', () => { const baseProps: Props = { intl: {} as any, onExited: jest.fn(), isEmbedded: false, actions: { performLookupCall: jest.fn(), refreshOnSelect: jest.fn(), submit: jest.fn().mockResolvedValue({ data: { type: 'ok', }, }), }, form: { title: 'Title', footer: 'Footer', header: 'Header', icon: 'Icon', submit: { path: '/create', }, fields: [ { name: 'bool1', type: 'bool', }, { name: 'bool2', type: 'bool', value: false, }, { name: 'bool3', type: 'bool', value: true, }, { name: 'text1', type: 'text', value: 'initial text', }, { name: 'select1', type: 'static_select', options: [ {label: 'Label1', value: 'Value1'}, {label: 'Label2', value: 'Value2'}, ], value: {label: 'Label1', value: 'Value1'}, }, ], }, }; test('should set match snapshot', () => { const wrapper = shallow<AppsForm>( <AppsForm {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should set initial form values', () => { const wrapper = shallow<AppsForm>( <AppsForm {...baseProps} />, ); expect(wrapper.state().values).toEqual({ bool1: false, bool2: false, bool3: true, text1: 'initial text', select1: {label: 'Label1', value: 'Value1'}, }); }); test('it should submit and close the modal', async () => { const submit = jest.fn().mockResolvedValue({data: {type: 'ok'}}); const props: Props = { ...baseProps, actions: { ...baseProps.actions, submit, }, }; const wrapper = shallow<AppsForm>( <AppsForm {...props} />, ); const hide = jest.fn(); wrapper.instance().handleHide = hide; await wrapper.instance().handleSubmit({preventDefault: jest.fn()} as any); expect(submit).toHaveBeenCalledWith({ values: { bool1: false, bool2: false, bool3: true, text1: 'initial text', select1: {label: 'Label1', value: 'Value1'}, }, }); expect(hide).toHaveBeenCalled(); }); describe('generic error message', () => { test('should appear when submit returns an error', async () => { const props = { ...baseProps, actions: { ...baseProps.actions, submit: jest.fn().mockResolvedValue({ error: {text: 'This is an error.', type: AppCallResponseTypes.ERROR}, }), }, }; const wrapper = shallow<AppsForm>(<AppsForm {...props}/>); await wrapper.instance().handleSubmit({preventDefault: jest.fn()} as any); const expected = ( <div className='error-text'> <Markdown message={'This is an error.'}/> </div> ); expect(wrapper.find(Modal.Footer).containsMatchingElement(expected)).toBe(true); }); test('should not appear when submit does not return an error', async () => { const wrapper = shallow<AppsForm>(<AppsForm {...baseProps}/>); await wrapper.instance().handleSubmit({preventDefault: jest.fn()} as any); expect(wrapper.find(Modal.Footer).find('.error-text').exists()).toBeFalsy(); }); }); describe('default select element', () => { test('should be enabled by default', () => { const selectField = { type: 'static_select', value: {label: 'Option3', value: 'opt3'}, modal_label: 'Option Selector', name: 'someoptionselector', is_required: true, options: [ {label: 'Option1', value: 'opt1'}, {label: 'Option2', value: 'opt2'}, {label: 'Option3', value: 'opt3'}, ], min_length: 2, max_length: 1024, hint: '', subtype: '', description: '', }; const fields = [selectField]; const props = { ...baseProps, context: {}, form: { fields, }, }; const state = { entities: { general: { config: {}, license: {}, }, channels: { channels: {}, roles: {}, }, teams: { teams: {}, }, posts: { posts: {}, }, users: { profiles: {}, }, groups: { myGroups: [], }, emojis: {}, preferences: { myPreferences: {}, }, }, }; const store = mockStore(state); const wrapper = mountWithIntl( <Provider store={store}> <AppsForm {...props}/> </Provider>, ); expect(wrapper.find(Modal.Body).find('div.react-select__single-value').text()).toEqual('Option3'); }); }); });
1,576
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/apps_form_container.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 {AppCallResponseTypes} from 'mattermost-redux/constants/apps'; import EmojiMap from 'utils/emoji_map'; import {RawAppsFormContainer} from './apps_form_container'; describe('components/apps_form/AppsFormContainer', () => { const emojiMap = new EmojiMap(new Map()); const context = { app_id: 'app', channel_id: 'channel', team_id: 'team', post_id: 'post', }; const intl = { formatMessage: (message: {id: string; defaultMessage: string}) => { return message.defaultMessage; }, } as any; const baseProps = { emojiMap, form: { title: 'Form Title', header: 'Form Header', fields: [ { type: 'text', name: 'field1', value: 'initial_value_1', }, { type: 'dynamic_select', name: 'field2', value: 'initial_value_2', refresh: true, lookup: { path: '/form_lookup', }, }, ], submit: { path: '/form_url', }, }, context, actions: { doAppSubmit: jest.fn().mockResolvedValue({}), doAppFetchForm: jest.fn(), doAppLookup: jest.fn(), postEphemeralCallResponseForContext: jest.fn(), }, onExited: jest.fn(), intl, }; test('should match snapshot', () => { const props = baseProps; const wrapper = shallow(<RawAppsFormContainer {...props}/>); expect(wrapper).toMatchSnapshot(); }); describe('submitForm', () => { test('should handle form submission result', async () => { const response = { data: { type: AppCallResponseTypes.OK, }, }; const props = { ...baseProps, actions: { ...baseProps.actions, doAppSubmit: jest.fn().mockResolvedValue(response), }, }; const wrapper = shallow<RawAppsFormContainer>(<RawAppsFormContainer {...props}/>); const result = await wrapper.instance().submitForm({ values: { field1: 'value1', field2: {label: 'label2', value: 'value2'}, }, }); expect(props.actions.doAppSubmit).toHaveBeenCalledWith({ context: { app_id: 'app', channel_id: 'channel', post_id: 'post', team_id: 'team', }, path: '/form_url', expand: {}, values: { field1: 'value1', field2: { label: 'label2', value: 'value2', }, }, }, expect.any(Object)); expect(result).toEqual({ data: { type: AppCallResponseTypes.OK, }, }); }); }); describe('performLookupCall', () => { test('should handle form user input', async () => { const response = { data: { type: AppCallResponseTypes.OK, data: { items: [{ label: 'Fetched Label', value: 'fetched_value', }], }, }, }; const props = { ...baseProps, actions: { ...baseProps.actions, doAppLookup: jest.fn().mockResolvedValue(response), }, }; const form = props.form; const wrapper = shallow<RawAppsFormContainer>(<RawAppsFormContainer {...props}/>); const result = await wrapper.instance().performLookupCall( form.fields[1], { field1: 'value1', field2: {label: 'label2', value: 'value2'}, }, 'My search', ); expect(props.actions.doAppLookup).toHaveBeenCalledWith({ context: { app_id: 'app', channel_id: 'channel', post_id: 'post', team_id: 'team', }, path: '/form_lookup', expand: {}, query: 'My search', raw_command: undefined, selected_field: 'field2', values: { field1: 'value1', field2: { label: 'label2', value: 'value2', }, }, }, expect.any(Object)); expect(result).toEqual(response); }); }); });
1,578
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/apps_form_header.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import AppsFormHeader from './apps_form_header'; describe('components/apps_form/AppsFormHeader', () => { test('should render message with supported values', () => { const props = { id: 'testsupported', value: '**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)', }; const wrapper = shallow(<AppsFormHeader {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should not fail on empty value', () => { const props = { id: 'testblankvalue', value: '', }; const wrapper = shallow(<AppsFormHeader {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
1,581
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/__snapshots__/apps_form_component.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`AppsFormComponent should set match snapshot 1`] = ` <Modal animation={true} aria-labelledby="appsModalLabel" autoFocus={true} backdrop="static" bsClass="modal" dialogClassName="a11y__modal about-modal" dialogComponentClass={[Function]} enforceFocus={true} id="appsModal" 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} > <form autoComplete="off" onSubmit={[Function]} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" style={ Object { "borderBottom": "", } } > <ModalTitle bsClass="modal-title" componentClass="h1" id="appsModalLabel" > <img alt="modal title icon" className="more-modal__image" height="36" id="appsModalIconUrl" src="Icon" width="36" /> Title </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <Fade appear={false} in={false} mountOnEnter={false} timeout={300} unmountOnExit={false} > <div className="apps-form-modal-body-common apps-form-modal-body-loaded" > <Memo(LoadingSpinner) style={ Object { "fontSize": "24px", } } /> </div> </Fade> <AppsFormHeader id="appsModalHeader" value="Header" /> <Connect(AppsFormField) autoFocus={true} field={ Object { "name": "bool1", "type": "bool", } } key="bool1" listComponent={[Function]} name="bool1" onChange={[Function]} performLookup={[Function]} value={false} /> <Connect(AppsFormField) autoFocus={false} field={ Object { "name": "bool2", "type": "bool", "value": false, } } key="bool2" listComponent={[Function]} name="bool2" onChange={[Function]} performLookup={[Function]} value={false} /> <Connect(AppsFormField) autoFocus={false} field={ Object { "name": "bool3", "type": "bool", "value": true, } } key="bool3" listComponent={[Function]} name="bool3" onChange={[Function]} performLookup={[Function]} value={true} /> <Connect(AppsFormField) autoFocus={false} field={ Object { "name": "text1", "type": "text", "value": "initial text", } } key="text1" listComponent={[Function]} name="text1" onChange={[Function]} performLookup={[Function]} value="initial text" /> <Connect(AppsFormField) autoFocus={false} field={ Object { "name": "select1", "options": Array [ Object { "label": "Label1", "value": "Value1", }, Object { "label": "Label2", "value": "Value2", }, ], "type": "static_select", "value": Object { "label": "Label1", "value": "Value1", }, } } key="select1" listComponent={[Function]} name="select1" onChange={[Function]} performLookup={[Function]} value={ Object { "label": "Label1", "value": "Value1", } } /> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <div> <button className="btn btn-tertiary cancel-button" id="appsModalCancel" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Cancel" id="interactive_dialog.cancel" /> </button> <Memo(SpinnerButton) autoFocus={false} className="btn btn-primary save-button" id="appsModalSubmit" key="submit" spinning={false} spinningText="Submitting..." type="submit" > <MemoizedFormattedMessage defaultMessage="Submit" id="interactive_dialog.submit" /> </Memo(SpinnerButton)> </div> </ModalFooter> </form> </Modal> `;
1,582
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/__snapshots__/apps_form_container.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/apps_form/AppsFormContainer should match snapshot 1`] = ` <injectIntl(AppsForm) actions={ Object { "performLookupCall": [Function], "refreshOnSelect": [Function], "submit": [Function], } } form={ Object { "fields": Array [ Object { "name": "field1", "type": "text", "value": "initial_value_1", }, Object { "lookup": Object { "path": "/form_lookup", }, "name": "field2", "refresh": true, "type": "dynamic_select", "value": "initial_value_2", }, ], "header": "Form Header", "submit": Object { "path": "/form_url", }, "title": "Form Title", } } onExited={[MockFunction]} /> `;
1,583
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/__snapshots__/apps_form_header.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/apps_form/AppsFormHeader should not fail on empty value 1`] = ` <Connect(Markdown) message="" options={ Object { "mentionHighlight": false, "singleline": false, } } /> `; exports[`components/apps_form/AppsFormHeader should render message with supported values 1`] = ` <Connect(Markdown) message="**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)" options={ Object { "mentionHighlight": false, "singleline": false, } } /> `;
1,584
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form
petrpan-code/mattermost/mattermost/webapp/channels/src/components/apps_form/apps_form_field/apps_form_field.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 {AppField} from '@mattermost/types/apps'; import TextSetting from 'components/widgets/settings/text_setting'; import AppsFormField from './apps_form_field'; import type {Props} from './apps_form_field'; import AppsFormSelectField from './apps_form_select_field'; describe('components/apps_form/apps_form_field/AppsFormField', () => { describe('Text elements', () => { const textField: AppField = { name: 'field1', type: 'text', max_length: 100, modal_label: 'The Field', hint: 'The hint', description: 'The description', is_required: true, }; const baseDialogTextProps: Props = { name: 'testing', actions: { autocompleteChannels: jest.fn(), autocompleteUsers: jest.fn(), }, field: textField, value: '', onChange: () => {}, performLookup: jest.fn(), }; it('subtype blank - optional field', () => { const wrapper = shallow( <AppsFormField {...baseDialogTextProps} field={{ ...textField, label: '', is_required: false, }} />, ); expect(wrapper.find(TextSetting).props().type).toEqual('text'); }); it('subtype blank', () => { const wrapper = shallow( <AppsFormField {...baseDialogTextProps} />, ); expect(wrapper.find(TextSetting).props().type).toEqual('text'); }); it('subtype email', () => { const wrapper = shallow( <AppsFormField {...baseDialogTextProps} field={{ ...textField, subtype: 'email', }} />, ); expect(wrapper.find(TextSetting).props().type).toEqual('email'); }); it('subtype password', () => { const wrapper = shallow( <AppsFormField {...baseDialogTextProps} field={{ ...textField, subtype: 'password', }} />, ); expect(wrapper.find(TextSetting).props().type).toEqual('password'); }); }); describe('Select elements', () => { const selectField: AppField = { name: 'field1', type: 'static_select', max_length: 100, modal_label: 'The Field', hint: 'The hint', description: 'The description', is_required: true, options: [], }; const baseDialogSelectProps: Props = { name: 'testing', actions: { autocompleteChannels: jest.fn(), autocompleteUsers: jest.fn(), }, field: selectField, value: null, onChange: () => {}, performLookup: jest.fn(), }; const options = [ {value: 'foo', label: 'foo-text'}, {value: 'bar', label: 'bar-text'}, ]; test('AppsFormSelectField is rendered when type is static_select', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options, }} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppsFormSelectField is rendered when type is dynamic_select', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'dynamic_select', options, }} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppsFormSelectField is used when field type is user', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'user', }} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppsFormSelectField is used when field type is channel', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'channel', }} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppSelectForm is rendered when options are undefined', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options: undefined, }} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppsFormSelectField is rendered when options are null and value is null', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options: undefined, }} value={null} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppsFormSelectField is rendered when options are null and value is not null', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options: undefined, }} value={options[0]} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('AppsFormSelectField is rendered when value is not one of the options', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options, }} value={{label: 'Other', value: 'other'}} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).exists()).toBe(true); }); test('No default value is selected from the options list', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options, }} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).prop('value')).toBeNull(); }); test('The default value can be specified from the list', () => { const wrapper = shallow( <AppsFormField {...baseDialogSelectProps} field={{ ...selectField, type: 'static_select', options, }} value={options[1]} onChange={jest.fn()} />, ); expect(wrapper.find(AppsFormSelectField).prop('value')).toBe(options[1]); }); }); });
1,590
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/at_mention/at_mention.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {General} from 'mattermost-redux/constants'; import AtMention from 'components/at_mention/at_mention'; import {TestHelper} from 'utils/test_helper'; /* eslint-disable global-require */ describe('components/AtMention', () => { const baseProps = { currentUserId: 'abc1', teammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_NICKNAME_FULLNAME, usersByUsername: { currentuser: TestHelper.getUserMock( {id: 'abc1', username: 'currentuser', first_name: 'First', last_name: 'Last'}, ), user1: TestHelper.getUserMock({id: 'abc2', username: 'user1', first_name: 'Other', last_name: 'User', nickname: 'Nick'}), 'userdot.': TestHelper.getUserMock({id: 'abc3', username: 'userdot.', first_name: 'Dot', last_name: 'Matrix'}), }, groupsByName: { developers: TestHelper.getGroupMock({id: 'qwerty1', name: 'developers', allow_reference: true}), marketing: TestHelper.getGroupMock({id: 'qwerty2', name: 'marketing', allow_reference: false}), accounting: TestHelper.getGroupMock({id: 'qwerty3', name: 'accounting', allow_reference: true}), }, }; test('should match snapshot when mentioning user', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='user1' > {'(at)-user1'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning user with different teammate name display setting', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='user1' teammateNameDisplay={General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME} > {'(at)-user1'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning user followed by punctuation', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='user1...' > {'(at)-user1'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning user containing punctuation', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='userdot.' > {'(at)-userdot.'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning user containing and followed by punctuation', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='userdot..' > {'(at)-userdot..'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning user with mixed case', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='USeR1' > {'(at)-USeR1'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning current user', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='currentUser' > {'(at)-currentUser'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning all', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='all' > {'(at)-all'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning all with mixed case', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='aLL' > {'(at)-aLL'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when not mentioning a user', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='notauser' > {'(at)-notauser'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when not mentioning a user with mixed case', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='NOTAuser' > {'(at)-NOTAuser'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning a group that is allowed reference', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='developers' > {'(at)-developers'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning a group that is allowed reference with group highlight disabled', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='developers' disableGroupHighlight={true} > {'(at)-developers'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning a group that is not allowed reference', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='marketing' > {'(at)-marketing'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when mentioning a group followed by punctuation', () => { const wrapper = shallow( <AtMention {...baseProps} mentionName='developers.' > {'(at)-developers.'} </AtMention>, ); expect(wrapper).toMatchSnapshot(); }); });
1,593
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/at_mention
petrpan-code/mattermost/mattermost/webapp/channels/src/components/at_mention/__snapshots__/at_mention.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/AtMention should match snapshot when mentioning a group followed by punctuation 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(Component) group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "qwerty1", "member_count": 0, "name": "developers", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[Function]} returnFocus={[Function]} showUserOverlay={[Function]} /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="group-mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @developers </a> </span> . </Fragment> `; exports[`components/AtMention should match snapshot when mentioning a group that is allowed reference 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(Component) group={ Object { "allow_reference": true, "create_at": 1, "delete_at": 0, "description": "", "display_name": "group_display_name", "has_syncables": false, "id": "qwerty1", "member_count": 0, "name": "developers", "remote_id": "", "scheme_admin": false, "source": "", "update_at": 1, } } hide={[Function]} returnFocus={[Function]} showUserOverlay={[Function]} /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="group-mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @developers </a> </span> </Fragment> `; exports[`components/AtMention should match snapshot when mentioning a group that is allowed reference with group highlight disabled 1`] = ` <Fragment> (at)-developers </Fragment> `; exports[`components/AtMention should match snapshot when mentioning a group that is not allowed reference 1`] = ` <Fragment> (at)-marketing </Fragment> `; exports[`components/AtMention should match snapshot when mentioning all 1`] = ` <Fragment> (at)-all </Fragment> `; exports[`components/AtMention should match snapshot when mentioning all with mixed case 1`] = ` <Fragment> (at)-aLL </Fragment> `; exports[`components/AtMention should match snapshot when mentioning current user 1`] = ` <Fragment> <span className="mention--highlight" > <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc1/image" userId="abc1" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @First Last </a> </span> </Fragment> `; exports[`components/AtMention should match snapshot when mentioning user 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc2/image" userId="abc2" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @Nick </a> </span> </Fragment> `; exports[`components/AtMention should match snapshot when mentioning user containing and followed by punctuation 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc3/image" userId="abc3" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @Dot Matrix </a> </span> . </Fragment> `; exports[`components/AtMention should match snapshot when mentioning user containing punctuation 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc3/image" userId="abc3" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @Dot Matrix </a> </span> </Fragment> `; exports[`components/AtMention should match snapshot when mentioning user followed by punctuation 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc2/image" userId="abc2" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @Nick </a> </span> ... </Fragment> `; exports[`components/AtMention should match snapshot when mentioning user with different teammate name display setting 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc2/image" userId="abc2" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @user1 </a> </span> </Fragment> `; exports[`components/AtMention should match snapshot when mentioning user with mixed case 1`] = ` <Fragment> <span> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <Connect(injectIntl(ProfilePopover)) className="user-profile-popover" hide={[Function]} src="/api/v4/users/abc2/image" userId="abc2" /> </Overlay> <Overlay animation={[Function]} onHide={[Function]} placement="right" rootClose={true} show={false} > <span /> </Overlay> <a aria-haspopup="dialog" className="mention-link" onClick={[Function]} onKeyDown={[Function]} role="button" tabIndex={0} > @Nick </a> </span> </Fragment> `; exports[`components/AtMention should match snapshot when not mentioning a user 1`] = ` <Fragment> (at)-notauser </Fragment> `; exports[`components/AtMention should match snapshot when not mentioning a user with mixed case 1`] = ` <Fragment> (at)-NOTAuser </Fragment> `;
1,594
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/at_plan_mention/at_plan_mention.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import * as useOpenPricingModal from 'components/common/hooks/useOpenPricingModal'; import AtPlanMention from './index'; describe('components/AtPlanMention', () => { it('should open pricing modal when plan mentioned is trial', () => { const openPricingModal = jest.fn(); jest.spyOn(useOpenPricingModal, 'default').mockImplementation(() => openPricingModal); const wrapper = shallow(<AtPlanMention plan='Enterprise trial'/>); wrapper.find('a').simulate('click', { preventDefault: () => { }, }); expect(openPricingModal).toHaveBeenCalledTimes(1); }); it('should open pricing modal when plan mentioned is Enterprise', () => { const openPricingModal = jest.fn(); jest.spyOn(useOpenPricingModal, 'default').mockImplementation(() => openPricingModal); const wrapper = shallow(<AtPlanMention plan='Enterprise plan'/>); wrapper.find('a').simulate('click', { preventDefault: () => { }, }); expect(openPricingModal).toHaveBeenCalledTimes(1); }); it('should open purchase modal when plan mentioned is professional', () => { const openPricingModal = jest.fn(); jest.spyOn(useOpenPricingModal, 'default').mockImplementation(() => openPricingModal); const wrapper = shallow(<AtPlanMention plan='Professional plan'/>); wrapper.find('a').simulate('click', { preventDefault: () => { }, }); expect(openPricingModal).toHaveBeenCalledTimes(1); }); });
1,599
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audio_video_preview/audio_video_preview.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {TestHelper} from 'utils/test_helper'; import AudioVideoPreview from './audio_video_preview'; describe('AudioVideoPreview', () => { const baseProps = { fileInfo: TestHelper.getFileInfoMock({ extension: 'mov', id: 'file_id', }), fileUrl: '/api/v4/files/file_id', isMobileView: false, }; test('should match snapshot without children', () => { const wrapper = shallow( <AudioVideoPreview {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, cannot play', () => { const wrapper = shallow( <AudioVideoPreview {...baseProps}/>, ); wrapper.setState({canPlay: false}); expect(wrapper).toMatchSnapshot(); }); });
1,602
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audio_video_preview
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audio_video_preview/__snapshots__/audio_video_preview.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`AudioVideoPreview should match snapshot without children 1`] = ` <video controls={true} data-setup="{}" height={480} key="file_id" width={640} > <source src="/api/v4/files/file_id" /> </video> `; exports[`AudioVideoPreview should match snapshot, cannot play 1`] = ` <Connect(FileInfoPreview) fileInfo={ Object { "archived": false, "clientId": "client_id", "create_at": 1, "delete_at": 1, "extension": "mov", "has_preview_image": true, "height": 200, "id": "file_id", "mime_type": "mime_type", "name": "name", "size": 1, "update_at": 1, "user_id": "user_id", "width": 350, } } fileUrl="/api/v4/files/file_id" /> `;
1,603
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/audit_table.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import AuditTable from 'components/audit_table/audit_table'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; describe('components/audit_table/AuditTable', () => { const actions = { getMissingProfilesByIds: () => jest.fn(), }; const baseProps = { audits: [], showUserId: true, showIp: true, showSession: true, currentUser: TestHelper.getUserMock({id: 'user-1'}), actions, }; test('should match snapshot with no audits', () => { const wrapper = shallowWithIntl( <AuditTable {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with audits', () => { const audits = [ { action: '/api/v4/channels', create_at: 50778112674, extra_info: 'name=yeye', id: 'id_2', ip_address: '::1', session_id: 'hb8febm9ytdiz8zqaxj18efqhy', user_id: 'user_id_1', }, { action: '/api/v4/users/login', create_at: 51053522355, extra_info: 'success', id: 'id_1', ip_address: '::1', session_id: '', user_id: 'user_id_1', }, ]; const props = {...baseProps, audits}; const wrapper = shallowWithIntl( <AuditTable {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,605
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/format_audit.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 {Audit} from '@mattermost/types/audits'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import FormatAudit from './format_audit'; import type {Props} from './format_audit'; describe('components/audit_table/audit_row/AuditRow', () => { const baseProps = { actionURL: '/dummy/url', showUserId: true, showIp: true, showSession: true, }; const channelName = 'default-name'; const userId = 'user_id_1'; const store = mockStore({ entities: { channels: { channels: { current_channel_id: { id: 'current_channel_id', name: channelName, display_name: 'Default', delete_at: 0, type: 'O', team_id: 'team_id', }, }, }, users: { profiles: { [userId]: { email: '[email protected]', }, }, }, }, }); const wrapper = (props: Props) => { return mountWithIntl( <Provider store={store}> <table> <tbody> <FormatAudit {...props}/> </tbody> </table> </Provider>, ); }; test('should match snapshot with channel audit', () => { const audit: Audit = { action: '/api/v4/channels', create_at: 50778112674, extra_info: `name=${channelName}`, id: 'id_2', ip_address: '::1', session_id: 'hb8febm9ytdiz8zqaxj18efqhy', user_id: userId, }; const props = {...baseProps, audit}; expect(wrapper(props)).toMatchSnapshot(); }); test('should match snapshot with user audit', () => { const audit: Audit = { action: '/api/v4/users/login', create_at: 51053522355, extra_info: 'success', id: 'id_1', ip_address: '::1', session_id: '', user_id: userId, }; const props = {...baseProps, audit}; expect(wrapper(props)).toMatchSnapshot(); }); test('should match snapshot with user audit', () => { const audit: Audit = { action: '/api/v4/oauth/register', create_at: 51053522355, extra_info: 'client_id=client_id', id: 'id_1', ip_address: '::1', session_id: '', user_id: userId, }; const props = {...baseProps, audit}; const wrapper = mountWithIntl( <Provider store={store}> <table> <tbody> <FormatAudit {...props}/> </tbody> </table> </Provider>, ); expect(wrapper).toMatchSnapshot(); }); });
1,609
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/__snapshots__/audit_table.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/audit_table/AuditTable should match snapshot with audits 1`] = ` <table className="table" > <thead> <tr> <th> <MemoizedFormattedMessage defaultMessage="Timestamp" id="audit_table.timestamp" /> </th> <th> <MemoizedFormattedMessage defaultMessage="User ID" id="audit_table.userId" /> </th> <th> <MemoizedFormattedMessage defaultMessage="Action" id="audit_table.action" /> </th> <th> <MemoizedFormattedMessage defaultMessage="IP Address" id="audit_table.ip" /> </th> <th> <MemoizedFormattedMessage defaultMessage="Session ID" id="audit_table.session" /> </th> </tr> </thead> <tbody data-testid="auditTableBody" > <FormatAudit audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=yeye", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } key="id_2" showIp={true} showSession={true} showUserId={true} /> <FormatAudit audit={ Object { "action": "/api/v4/users/login", "create_at": 51053522355, "extra_info": "success", "id": "id_1", "ip_address": "::1", "session_id": "", "user_id": "user_id_1", } } key="id_1" showIp={true} showSession={true} showUserId={true} /> </tbody> </table> `; exports[`components/audit_table/AuditTable should match snapshot with no audits 1`] = ` <table className="table" > <thead> <tr> <th> <MemoizedFormattedMessage defaultMessage="Timestamp" id="audit_table.timestamp" /> </th> <th> <MemoizedFormattedMessage defaultMessage="User ID" id="audit_table.userId" /> </th> <th> <MemoizedFormattedMessage defaultMessage="Action" id="audit_table.action" /> </th> <th> <MemoizedFormattedMessage defaultMessage="IP Address" id="audit_table.ip" /> </th> <th> <MemoizedFormattedMessage defaultMessage="Session ID" id="audit_table.session" /> </th> </tr> </thead> <tbody data-testid="auditTableBody" /> </table> `;
1,610
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/__snapshots__/format_audit.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/audit_table/audit_row/AuditRow should match snapshot with channel audit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <table> <tbody> <FormatAudit actionURL="/dummy/url" audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=default-name", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } showIp={true} showSession={true} showUserId={true} > <ChannelRow actionURL="/channels" audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=default-name", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } showIp={true} showSession={true} showUserId={true} > <ChannelDefaultRow actionURL="/channels" audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=default-name", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } channelInfo={ Array [ "name=default-name", ] } channelName="Default" channelURL="default-name" showIp={true} showSession={true} showUserId={true} > <AuditRow actionURL="/channels" audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=default-name", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } desc="" showIp={true} showSession={true} showUserId={true} > <tr key="id_2" > <td className="whitespace--nowrap word-break--all" > <div> <div> <FormattedDate day="2-digit" month="short" value={1971-08-11T17:01:52.674Z} year="numeric" > <span> Aug 11, 1971 </span> </FormattedDate> </div> <div> <FormattedTime hour="2-digit" minute="2-digit" value={1971-08-11T17:01:52.674Z} > <span> 05:01 PM </span> </FormattedTime> </div> </div> </td> <td className="word-break--all" > [email protected] </td> <td className="word-break--all" > Channels default-name </td> <td className="whitespace--nowrap word-break--all" > ::1 </td> <td className="whitespace--nowrap word-break--all" > hb8febm9ytdiz8zqaxj18efqhy </td> </tr> </AuditRow> </ChannelDefaultRow> </ChannelRow> </FormatAudit> </tbody> </table> </Provider> `; exports[`components/audit_table/audit_row/AuditRow should match snapshot with user audit 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <table> <tbody> <FormatAudit actionURL="/dummy/url" audit={ Object { "action": "/api/v4/users/login", "create_at": 51053522355, "extra_info": "success", "id": "id_1", "ip_address": "::1", "session_id": "", "user_id": "user_id_1", } } showIp={true} showSession={true} showUserId={true} > <UserRow actionURL="/users/login" audit={ Object { "action": "/api/v4/users/login", "create_at": 51053522355, "extra_info": "success", "id": "id_1", "ip_address": "::1", "session_id": "", "user_id": "user_id_1", } } showIp={true} showSession={true} showUserId={true} > <AuditRow actionURL="/users/login" audit={ Object { "action": "/api/v4/users/login", "create_at": 51053522355, "extra_info": "success", "id": "id_1", "ip_address": "::1", "session_id": "", "user_id": "user_id_1", } } desc="Successfully logged in" showIp={true} showSession={true} showUserId={true} > <tr key="id_1" > <td className="whitespace--nowrap word-break--all" > <div> <div> <FormattedDate day="2-digit" month="short" value={1971-08-14T21:32:02.355Z} year="numeric" > <span> Aug 14, 1971 </span> </FormattedDate> </div> <div> <FormattedTime hour="2-digit" minute="2-digit" value={1971-08-14T21:32:02.355Z} > <span> 09:32 PM </span> </FormattedTime> </div> </div> </td> <td className="word-break--all" > [email protected] </td> <td className="word-break--all" > Successfully logged in </td> <td className="whitespace--nowrap word-break--all" > ::1 </td> <td className="whitespace--nowrap word-break--all" /> </tr> </AuditRow> </UserRow> </FormatAudit> </tbody> </table> </Provider> `; exports[`components/audit_table/audit_row/AuditRow should match snapshot with user audit 2`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <table> <tbody> <FormatAudit actionURL="/dummy/url" audit={ Object { "action": "/api/v4/oauth/register", "create_at": 51053522355, "extra_info": "client_id=client_id", "id": "id_1", "ip_address": "::1", "session_id": "", "user_id": "user_id_1", } } showIp={true} showSession={true} showUserId={true} > <AuditRow actionURL="/oauth/register" audit={ Object { "action": "/api/v4/oauth/register", "create_at": 51053522355, "extra_info": "client_id=client_id", "id": "id_1", "ip_address": "::1", "session_id": "", "user_id": "user_id_1", } } desc="Attempted to register a new OAuth Application with ID client_id" showIp={true} showSession={true} showUserId={true} > <tr key="id_1" > <td className="whitespace--nowrap word-break--all" > <div> <div> <FormattedDate day="2-digit" month="short" value={1971-08-14T21:32:02.355Z} year="numeric" > <span> Aug 14, 1971 </span> </FormattedDate> </div> <div> <FormattedTime hour="2-digit" minute="2-digit" value={1971-08-14T21:32:02.355Z} > <span> 09:32 PM </span> </FormattedTime> </div> </div> </td> <td className="word-break--all" > [email protected] </td> <td className="word-break--all" > Attempted to register a new OAuth Application with ID client_id </td> <td className="whitespace--nowrap word-break--all" > ::1 </td> <td className="whitespace--nowrap word-break--all" /> </tr> </AuditRow> </FormatAudit> </tbody> </table> </Provider> `;
1,611
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/audit_row/audit_row.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 {Audit} from '@mattermost/types/audits'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import mockStore from 'tests/test_store'; import AuditRow from './audit_row'; import type {Props} from './audit_row'; describe('components/audit_table/audit_row/AuditRow', () => { const audit: Audit = { action: '/api/v4/channels', create_at: 50778112674, extra_info: 'name=yeye', id: 'id_2', ip_address: '::1', session_id: 'hb8febm9ytdiz8zqaxj18efqhy', user_id: 'user_id_1', }; const baseProps = { audit, actionURL: '/dummy/url', showUserId: true, showIp: true, showSession: true, }; const store = mockStore({ entities: { users: { profiles: { [audit.user_id]: { email: '[email protected]', }, }, }, }, }); const wrapper = (props: Props) => { return mountWithIntl( <Provider store={store}> <table> <tbody> <AuditRow {...props}/> </tbody> </table> </Provider>, ); }; test('should match snapshot with no desc', () => { expect(wrapper(baseProps)).toMatchSnapshot(); }); test('should match snapshot with desc', () => { const props = {...baseProps, desc: 'Successfully authenticated'}; expect(wrapper(props)).toMatchSnapshot(); }); });
1,613
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/audit_row
petrpan-code/mattermost/mattermost/webapp/channels/src/components/audit_table/audit_row/__snapshots__/audit_row.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/audit_table/audit_row/AuditRow should match snapshot with desc 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <table> <tbody> <AuditRow actionURL="/dummy/url" audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=yeye", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } desc="Successfully authenticated" showIp={true} showSession={true} showUserId={true} > <tr key="id_2" > <td className="whitespace--nowrap word-break--all" > <div> <div> <FormattedDate day="2-digit" month="short" value={1971-08-11T17:01:52.674Z} year="numeric" > <span> Aug 11, 1971 </span> </FormattedDate> </div> <div> <FormattedTime hour="2-digit" minute="2-digit" value={1971-08-11T17:01:52.674Z} > <span> 05:01 PM </span> </FormattedTime> </div> </div> </td> <td className="word-break--all" > [email protected] </td> <td className="word-break--all" > Successfully authenticated </td> <td className="whitespace--nowrap word-break--all" > ::1 </td> <td className="whitespace--nowrap word-break--all" > hb8febm9ytdiz8zqaxj18efqhy </td> </tr> </AuditRow> </tbody> </table> </Provider> `; exports[`components/audit_table/audit_row/AuditRow should match snapshot with no desc 1`] = ` <Provider store={ Object { "clearActions": [Function], "dispatch": [Function], "getActions": [Function], "getState": [Function], "replaceReducer": [Function], "subscribe": [Function], } } > <table> <tbody> <AuditRow actionURL="/dummy/url" audit={ Object { "action": "/api/v4/channels", "create_at": 50778112674, "extra_info": "name=yeye", "id": "id_2", "ip_address": "::1", "session_id": "hb8febm9ytdiz8zqaxj18efqhy", "user_id": "user_id_1", } } showIp={true} showSession={true} showUserId={true} > <tr key="id_2" > <td className="whitespace--nowrap word-break--all" > <div> <div> <FormattedDate day="2-digit" month="short" value={1971-08-11T17:01:52.674Z} year="numeric" > <span> Aug 11, 1971 </span> </FormattedDate> </div> <div> <FormattedTime hour="2-digit" minute="2-digit" value={1971-08-11T17:01:52.674Z} > <span> 05:01 PM </span> </FormattedTime> </div> </div> </td> <td className="word-break--all" > [email protected] </td> <td className="word-break--all" > Url yeye </td> <td className="whitespace--nowrap word-break--all" > ::1 </td> <td className="whitespace--nowrap word-break--all" > hb8febm9ytdiz8zqaxj18efqhy </td> </tr> </AuditRow> </tbody> </table> </Provider> `;
1,619
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/authorize/authorize.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 Authorize from './authorize'; describe('components/user_settings/display/UserSettingsDisplay', () => { const oauthApp = { id: 'facxd9wpzpbpfp8pad78xj75pr', name: 'testApp', client_secret: '88cxd9wpzpbpfp8pad78xj75pr', create_at: 1501365458934, creator_id: '88oybd1dwfdoxpkpw1h5kpbyco', description: 'testing', homepage: 'https://test.com', icon_url: 'https://test.com/icon', is_trusted: true, update_at: 1501365458934, callback_urls: ['https://test.com/callback', 'https://test.com/callback2'], }; const requiredProps = { location: {search: ''}, actions: { getOAuthAppInfo: jest.fn().mockResolvedValue({data: true}), allowOAuth2: jest.fn().mockResolvedValue({data: true}), }, }; test('UNSAFE_componentWillMount() should have called getOAuthAppInfo', () => { const props = {...requiredProps, location: {search: 'client_id=1234abcd'}}; shallow(<Authorize {...props}/>); expect(requiredProps.actions.getOAuthAppInfo).toHaveBeenCalled(); expect(requiredProps.actions.getOAuthAppInfo).toHaveBeenCalledWith('1234abcd'); }); test('UNSAFE_componentWillMount() should have updated state.app', async () => { const expected = oauthApp; const promise = Promise.resolve({data: expected}); const actions = {...requiredProps.actions, getOAuthAppInfo: () => promise}; const props = {...requiredProps, actions, location: {search: 'client_id=1234abcd'}}; const wrapper = shallow<Authorize>(<Authorize {...props}/>); await promise; expect(wrapper.state().app).toEqual(expected); }); test('handleAllow() should have called allowOAuth2', () => { const props = {...requiredProps, location: {search: 'client_id=1234abcd'}}; const wrapper = shallow<Authorize>(<Authorize {...props}/>); wrapper.instance().handleAllow(); const expected = { clientId: '1234abcd', responseType: null, redirectUri: null, state: null, scope: null, }; expect(requiredProps.actions.allowOAuth2).toHaveBeenCalled(); expect(requiredProps.actions.allowOAuth2).toHaveBeenCalledWith(expected); }); test('handleAllow() should have updated state.error', async () => { const error = new Error('error'); const promise = Promise.resolve({error}); const actions = {...requiredProps.actions, allowOAuth2: () => promise}; const props = {...requiredProps, actions, location: {search: 'client_id=1234abcd'}}; const wrapper = shallow<Authorize>(<Authorize {...props}/>); wrapper.instance().handleAllow(); await promise; expect(wrapper.state().error).toEqual(error.message); }); });
1,625
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/backstage
petrpan-code/mattermost/mattermost/webapp/channels/src/components/backstage/components/backstage_header.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import BackstageHeader from 'components/backstage/components/backstage_header'; describe('components/backstage/components/BackstageHeader', () => { test('should match snapshot without children', () => { const wrapper = shallow( <BackstageHeader/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with children', () => { const wrapper = shallow( <BackstageHeader> <div>{'Child 1'}</div> <div>{'Child 2'}</div> </BackstageHeader>, ); expect(wrapper).toMatchSnapshot(); }); });
1,630
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/backstage
petrpan-code/mattermost/mattermost/webapp/channels/src/components/backstage/components/backstage_sidebar.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ComponentProps} from 'react'; import {TestHelper} from 'utils/test_helper'; import BackstageCategory from './backstage_category'; import BackstageSidebar from './backstage_sidebar'; describe('components/backstage/components/BackstageSidebar', () => { const defaultProps: ComponentProps<typeof BackstageSidebar> = { team: TestHelper.getTeamMock({ id: 'team-id', name: 'team_name', }), user: TestHelper.getUserMock({}), enableCustomEmoji: false, enableIncomingWebhooks: false, enableOutgoingWebhooks: false, enableCommands: false, enableOAuthServiceProvider: false, canCreateOrDeleteCustomEmoji: false, canManageIntegrations: false, }; describe('custom emoji', () => { const testCases = [ {enableCustomEmoji: false, canCreateOrDeleteCustomEmoji: false, expectedResult: false}, {enableCustomEmoji: false, canCreateOrDeleteCustomEmoji: true, expectedResult: false}, {enableCustomEmoji: true, canCreateOrDeleteCustomEmoji: false, expectedResult: false}, {enableCustomEmoji: true, canCreateOrDeleteCustomEmoji: true, expectedResult: true}, ]; testCases.forEach((testCase) => { it(`when custom emoji is ${testCase.enableCustomEmoji} and can create/delete is ${testCase.canCreateOrDeleteCustomEmoji}`, () => { const props = { ...defaultProps, enableCustomEmoji: testCase.enableCustomEmoji, canCreateOrDeleteCustomEmoji: testCase.canCreateOrDeleteCustomEmoji, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'emoji'}).exists()).toBe(testCase.expectedResult); }); }); }); describe('incoming webhooks', () => { const testCases = [ {canManageIntegrations: false, enableIncomingWebhooks: false, expectedResult: false}, {canManageIntegrations: false, enableIncomingWebhooks: true, expectedResult: false}, {canManageIntegrations: true, enableIncomingWebhooks: false, expectedResult: false}, {canManageIntegrations: true, enableIncomingWebhooks: true, expectedResult: true}, ]; testCases.forEach((testCase) => { it(`when incoming webhooks is ${testCase.enableIncomingWebhooks} and can manage integrations is ${testCase.canManageIntegrations}`, () => { const props = { ...defaultProps, enableIncomingWebhooks: testCase.enableIncomingWebhooks, canManageIntegrations: testCase.canManageIntegrations, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'incoming_webhooks'}).exists()).toBe(testCase.expectedResult); }); }); }); describe('outgoing webhooks', () => { const testCases = [ {canManageIntegrations: false, enableOutgoingWebhooks: false, expectedResult: false}, {canManageIntegrations: false, enableOutgoingWebhooks: true, expectedResult: false}, {canManageIntegrations: true, enableOutgoingWebhooks: false, expectedResult: false}, {canManageIntegrations: true, enableOutgoingWebhooks: true, expectedResult: true}, ]; testCases.forEach((testCase) => { it(`when outgoing webhooks is ${testCase.enableOutgoingWebhooks} and can manage integrations is ${testCase.canManageIntegrations}`, () => { const props = { ...defaultProps, enableOutgoingWebhooks: testCase.enableOutgoingWebhooks, canManageIntegrations: testCase.canManageIntegrations, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'outgoing_webhooks'}).exists()).toBe(testCase.expectedResult); }); }); }); describe('commands', () => { const testCases = [ {canManageIntegrations: false, enableCommands: false, expectedResult: false}, {canManageIntegrations: false, enableCommands: true, expectedResult: false}, {canManageIntegrations: true, enableCommands: false, expectedResult: false}, {canManageIntegrations: true, enableCommands: true, expectedResult: true}, ]; testCases.forEach((testCase) => { it(`when commands is ${testCase.enableCommands} and can manage integrations is ${testCase.canManageIntegrations}`, () => { const props = { ...defaultProps, enableCommands: testCase.enableCommands, canManageIntegrations: testCase.canManageIntegrations, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'commands'}).exists()).toBe(testCase.expectedResult); }); }); }); describe('oauth2 apps', () => { const testCases = [ {canManageIntegrations: false, enableOAuthServiceProvider: false, expectedResult: false}, {canManageIntegrations: false, enableOAuthServiceProvider: true, expectedResult: false}, {canManageIntegrations: true, enableOAuthServiceProvider: false, expectedResult: false}, {canManageIntegrations: true, enableOAuthServiceProvider: true, expectedResult: true}, ]; testCases.forEach((testCase) => { it(`when oauth2 apps is ${testCase.enableOAuthServiceProvider} and can manage integrations is ${testCase.canManageIntegrations}`, () => { const props = { ...defaultProps, enableOAuthServiceProvider: testCase.enableOAuthServiceProvider, canManageIntegrations: testCase.canManageIntegrations, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'oauth2-apps'}).exists()).toBe(testCase.expectedResult); }); }); }); describe('bots', () => { const testCases = [ {canManageIntegrations: false, expectedResult: false}, {canManageIntegrations: true, expectedResult: true}, ]; testCases.forEach((testCase) => { it(`when can manage integrations is ${testCase.canManageIntegrations}`, () => { const props = { ...defaultProps, canManageIntegrations: testCase.canManageIntegrations, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'bots'}).exists()).toBe(testCase.expectedResult); }); }); }); describe('all integrations', () => { it('can manage integrations', () => { const props = { ...defaultProps, enableIncomingWebhooks: true, enableOutgoingWebhooks: true, enableCommands: true, enableOAuthServiceProvider: true, canManageIntegrations: true, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'incoming_webhooks'}).exists()).toBe(true); expect(wrapper.find(BackstageCategory).find({name: 'outgoing_webhooks'}).exists()).toBe(true); expect(wrapper.find(BackstageCategory).find({name: 'commands'}).exists()).toBe(true); expect(wrapper.find(BackstageCategory).find({name: 'oauth2-apps'}).exists()).toBe(true); expect(wrapper.find(BackstageCategory).find({name: 'bots'}).exists()).toBe(true); }); it('cannot manage integrations', () => { const props = { ...defaultProps, enableIncomingWebhooks: true, enableOutgoingWebhooks: true, enableCommands: true, enableOAuthServiceProvider: true, canManageIntegrations: false, }; const wrapper = shallow( <BackstageSidebar {...props}/>, ); expect(wrapper.find(BackstageCategory).find({name: 'incoming_webhooks'}).exists()).toBe(false); expect(wrapper.find(BackstageCategory).find({name: 'outgoing_webhooks'}).exists()).toBe(false); expect(wrapper.find(BackstageCategory).find({name: 'commands'}).exists()).toBe(false); expect(wrapper.find(BackstageCategory).find({name: 'oauth2-apps'}).exists()).toBe(false); expect(wrapper.find(BackstageCategory).find({name: 'bots'}).exists()).toBe(false); }); }); });
1,632
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/backstage/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/backstage/components/__snapshots__/backstage_header.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/backstage/components/BackstageHeader should match snapshot with children 1`] = ` <div className="backstage-header" > <h1> <div> Child 1 </div> <span className="backstage-header__divider" key="divider1" > <i className="fa fa-angle-right" title="Breadcrumb Icon" /> </span> <div> Child 2 </div> </h1> </div> `; exports[`components/backstage/components/BackstageHeader should match snapshot without children 1`] = ` <div className="backstage-header" > <h1 /> </div> `;
1,634
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/browse_channels/browse_channels.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Channel} from '@mattermost/types/channels'; import type {ActionResult} from 'mattermost-redux/types/actions'; import type {Props} from 'components/browse_channels/browse_channels'; import BrowseChannels, {Filter} from 'components/browse_channels/browse_channels'; import SearchableChannelList from 'components/searchable_channel_list'; import {getHistory} from 'utils/browser_history'; import {TestHelper} from 'utils/test_helper'; jest.useFakeTimers({legacyFakeTimers: true}); describe('components/BrowseChannels', () => { const searchResults = { data: [{ id: 'channel-id-1', name: 'channel-name-1', team_id: 'team_1', display_name: 'Channel 1', delete_at: 0, type: 'O', }, { id: 'channel-id-2', name: 'archived-channel', team_id: 'team_1', display_name: 'Archived', delete_at: 123, type: 'O', }, { id: 'channel-id-3', name: 'private-channel', team_id: 'team_1', display_name: 'Private', delete_at: 0, type: 'P', }, { id: 'channel-id-4', name: 'private-channel-not-member', team_id: 'team_1', display_name: 'Private Not Member', delete_at: 0, type: 'P', }], }; const archivedChannel = TestHelper.getChannelMock({ id: 'channel_id_2', team_id: 'team_1', display_name: 'channel-2', name: 'channel-2', header: 'channel-2-header', purpose: 'channel-2-purpose', }); const privateChannel = TestHelper.getChannelMock({ id: 'channel_id_3', team_id: 'team_1', display_name: 'channel-3', name: 'channel-3', header: 'channel-3-header', purpose: 'channel-3-purpose', type: 'P', }); const channelActions = { joinChannelAction: (userId: string, teamId: string, channelId: string): Promise<ActionResult> => { return new Promise((resolve) => { if (channelId !== 'channel-1') { return resolve({ error: { message: 'error', }, }); } return resolve({data: true}); }); }, searchAllChannels: (term: string): Promise<ActionResult> => { return new Promise((resolve) => { if (term === 'fail') { return resolve({ error: { message: 'error', }, }); } return resolve(searchResults); }); }, getChannels: (): Promise<ActionResult<Channel[], Error>> => { return new Promise((resolve) => { return resolve({ data: [TestHelper.getChannelMock({})], }); }); }, getArchivedChannels: (): Promise<ActionResult<Channel[], Error>> => { return new Promise((resolve) => { return resolve({ data: [archivedChannel], }); }); }, }; const baseProps: Props = { channels: [TestHelper.getChannelMock({})], archivedChannels: [archivedChannel], privateChannels: [privateChannel], currentUserId: 'user-1', teamId: 'team_1', teamName: 'team_name', channelsRequestStarted: false, canShowArchivedChannels: true, shouldHideJoinedChannels: false, myChannelMemberships: { 'channel-id-3': TestHelper.getChannelMembershipMock({ channel_id: 'channel-id-3', user_id: 'user-1', }), }, actions: { getChannels: jest.fn(channelActions.getChannels), getArchivedChannels: jest.fn(channelActions.getArchivedChannels), joinChannel: jest.fn(channelActions.joinChannelAction), searchAllChannels: jest.fn(channelActions.searchAllChannels), openModal: jest.fn(), closeModal: jest.fn(), closeRightHandSide: jest.fn(), setGlobalItem: jest.fn(), getChannelsMemberCount: jest.fn(), }, }; test('should match snapshot and state', () => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.state('searchedChannels')).toEqual([]); expect(wrapper.state('search')).toEqual(false); expect(wrapper.state('serverError')).toBeNull(); expect(wrapper.state('searching')).toEqual(false); // on componentDidMount expect(wrapper.instance().props.actions.getChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.getChannels).toHaveBeenCalledWith(wrapper.instance().props.teamId, 0, 100); }); test('should call closeModal on handleExit', () => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().handleExit(); expect(baseProps.actions.closeModal).toHaveBeenCalledTimes(1); }); test('should match state on onChange', () => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.setState({searchedChannels: [TestHelper.getChannelMock({id: 'other_channel_id'})]}); wrapper.instance().onChange(true); expect(wrapper.state('searchedChannels')).toEqual([]); // on search wrapper.setState({search: true}); expect(wrapper.instance().onChange(false)).toEqual(undefined); }); test('should call props.getChannels on nextPage', () => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().nextPage(1); expect(wrapper.instance().props.actions.getChannels).toHaveBeenCalledTimes(2); expect(wrapper.instance().props.actions.getChannels).toHaveBeenCalledWith(wrapper.instance().props.teamId, 2, 50); }); test('should have loading prop true when searching state is true', () => { const wrapper = shallow( <BrowseChannels {...baseProps}/>, ); wrapper.setState({search: true, searching: true}); const searchList = wrapper.find(SearchableChannelList); expect(searchList.props().loading).toEqual(true); }); test('should attempt to join the channel and fail', (done) => { const props = { ...baseProps, actions: { ...baseProps.actions, joinChannel: jest.fn().mockImplementation(() => { const error = { message: 'error message', }; return Promise.resolve({error}); }), }, }; const wrapper = shallow<BrowseChannels>( <BrowseChannels {...props}/>, ); const callback = jest.fn(); wrapper.instance().handleJoin(baseProps.channels[0], callback); expect(wrapper.instance().props.actions.joinChannel).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.joinChannel).toHaveBeenCalledWith(wrapper.instance().props.currentUserId, wrapper.instance().props.teamId, baseProps.channels[0].id); process.nextTick(() => { expect(wrapper.state('serverError')).toEqual('error message'); expect(callback).toHaveBeenCalledTimes(1); done(); }); }); test('should join the channel', (done) => { const props = { ...baseProps, actions: { ...baseProps.actions, joinChannel: jest.fn().mockImplementation(() => { const data = true; return Promise.resolve({data}); }), }, }; const wrapper = shallow<BrowseChannels>( <BrowseChannels {...props}/>, ); const callback = jest.fn(); wrapper.instance().handleJoin(baseProps.channels[0], callback); expect(wrapper.instance().props.actions.joinChannel).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.joinChannel).toHaveBeenCalledWith(wrapper.instance().props.currentUserId, wrapper.instance().props.teamId, baseProps.channels[0].id); process.nextTick(() => { expect(getHistory().push).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledTimes(1); done(); }); }); test('should not perform a search if term is empty', () => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search(''); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).toHaveBeenCalledWith(true); expect(wrapper.state('search')).toEqual(false); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.instance().searchTimeoutId).toEqual(0); }); test('should handle a failed search', (done) => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().setSearchResults = jest.fn(); wrapper.instance().search('fail'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('fail', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([]); expect(wrapper.instance().setSearchResults).not.toBeCalled(); done(); }); }); test('should perform search and set the correct state', (done) => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('channel', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([searchResults.data[0], searchResults.data[1], searchResults.data[2]]); done(); }); }); test('should perform search on archived channels and set the correct state', (done) => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); wrapper.instance().changeFilter(Filter.Archived); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('channel', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([searchResults.data[1]]); done(); }); }); test('should perform search on private channels and set the correct state', (done) => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); wrapper.instance().changeFilter(Filter.Private); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('channel', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([searchResults.data[2]]); done(); }); }); test('should perform search on public channels and set the correct state', (done) => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); wrapper.instance().changeFilter(Filter.Public); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('channel', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([searchResults.data[0]]); done(); }); }); test('should perform search on all channels and set the correct state when shouldHideJoinedChannels is true', (done) => { const props = { ...baseProps, shouldHideJoinedChannels: true, }; const wrapper = shallow<BrowseChannels>( <BrowseChannels {...props}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); wrapper.instance().changeFilter(Filter.All); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('channel', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([searchResults.data[0], searchResults.data[1]]); done(); }); }); test('should perform search on all channels and set the correct state when shouldHideJoinedChannels is true and filter is private', (done) => { const props = { ...baseProps, shouldHideJoinedChannels: true, }; const wrapper = shallow<BrowseChannels>( <BrowseChannels {...props}/>, ); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); expect(clearTimeout).toHaveBeenCalledTimes(1); expect(wrapper.instance().onChange).not.toHaveBeenCalled(); expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(true); expect(wrapper.instance().searchTimeoutId).not.toEqual(''); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 100); wrapper.instance().changeFilter(Filter.Private); jest.runOnlyPendingTimers(); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledTimes(1); expect(wrapper.instance().props.actions.searchAllChannels).toHaveBeenCalledWith('channel', {include_deleted: true, nonAdminSearch: true, team_ids: ['team_1']}); process.nextTick(() => { expect(wrapper.state('search')).toEqual(true); expect(wrapper.state('searching')).toEqual(false); expect(wrapper.state('searchedChannels')).toEqual([]); done(); }); }); it('should perform search on all channels and should not show private channels that user is not a member of', (done) => { const wrapper = shallow<BrowseChannels>( <BrowseChannels {...baseProps}/>, ); wrapper.setState({search: true, searching: true}); wrapper.instance().onChange = jest.fn(); wrapper.instance().search('channel'); jest.runOnlyPendingTimers(); process.nextTick(() => { expect(wrapper.state('searchedChannels')).toEqual([searchResults.data[0], searchResults.data[1], searchResults.data[2]]); done(); }); }); });
1,637
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/browse_channels
petrpan-code/mattermost/mattermost/webapp/channels/src/components/browse_channels/__snapshots__/browse_channels.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/BrowseChannels should match snapshot and state 1`] = ` <GenericModal aria-labelledby="browseChannelsModalLabel" aria-modal={true} autoCloseOnCancelButton={true} autoCloseOnConfirmButton={false} bodyPadding={false} compassDesign={true} enforceFocus={false} headerButton={ <Memo(Connect(TeamPermissionGate)) permissions={ Array [ "create_public_channel", ] } teamId="team_1" > <button aria-label="Create New Channel" className="btn btn-secondary btn-sm" id="createNewChannelButton" onClick={[Function]} type="button" > <Memo(MemoizedFormattedMessage) defaultMessage="Create New Channel" id="more_channels.create" /> </button> </Memo(Connect(TeamPermissionGate))> } id="browseChannelsModal" keyboardEscape={true} modalHeaderText={ <Memo(MemoizedFormattedMessage) defaultMessage="Browse Channels" id="more_channels.title" /> } onExited={[Function]} show={true} > <injectIntl(SearchableChannelList) canShowArchivedChannels={true} changeFilter={[Function]} channels={ Array [ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "channel-3", "group_constrained": false, "header": "channel-3-header", "id": "channel_id_3", "last_post_at": 0, "last_root_post_at": 0, "name": "channel-3", "purpose": "channel-3-purpose", "scheme_id": "id", "team_id": "team_1", "type": "P", "update_at": 0, }, 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, }, ] } channelsPerPage={50} closeModal={[MockFunction]} filter="All" handleJoin={[Function]} hideJoinedChannelsPreference={[Function]} isSearch={false} loading={false} myChannelMemberships={ Object { "channel-id-3": Object { "channel_id": "channel-id-3", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user-1", }, } } nextPage={[Function]} noResultsText={ <React.Fragment> <p className="secondary-message" > <Memo(MemoizedFormattedMessage) defaultMessage="Try searching different keywords, checking for typos or adjusting the filters." id="more_channels.searchError" /> </p> <Memo(Connect(TeamPermissionGate)) permissions={ Array [ "create_public_channel", ] } teamId="team_1" > <button aria-label="Create New Channel" className="btn btn-primary" id="createNewChannelButton" onClick={[Function]} type="button" > <i className="icon-plus" /> <Memo(MemoizedFormattedMessage) defaultMessage="Create New Channel" id="more_channels.create" /> </button> </Memo(Connect(TeamPermissionGate))> </React.Fragment> } rememberHideJoinedChannelsChecked={false} search={[Function]} /> </GenericModal> `;
1,639
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/card/card.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 {FormattedMessage} from 'react-intl'; import Card from './card'; import TitleAndButtonCardHeader from './title_and_button_card_header/title_and_button_card_header'; describe('components/card/card', () => { const baseProps = { expanded: false, }; const headerProps = { title: <FormattedMessage id='admin.data_retention.customPolicies.title' defaultMessage='Custom retention policies' />, subtitle: <FormattedMessage id='admin.data_retention.customPolicies.subTitle' defaultMessage='Customize how long specific teams and channels will keep messages.' />, body: <div> {'Hello!'} </div>, }; test('should match snapshot', () => { const wrapper = mount( <Card {...baseProps}> <Card.Header>{'Header Test'}</Card.Header> <Card.Body>{'Body Test'}</Card.Body> </Card>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when expanded', () => { const props = { ...baseProps, expanded: true, }; const wrapper = mount( <Card {...props}> <Card.Header>{'Header Test'}</Card.Header> <Card.Body>{'Body Test'}</Card.Body> </Card>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when using header content and no button', () => { const props = { ...baseProps, expanded: true, className: 'console', }; const wrapper = shallow( <Card {...props}> <Card.Header> <TitleAndButtonCardHeader {...headerProps} /> </Card.Header> <Card.Body>{'Body Test'}</Card.Body> </Card>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when using header content and a button', () => { const props = { ...baseProps, expanded: true, className: 'console', }; const buttonProps = { buttonText: <FormattedMessage id='admin.data_retention.customPolicies.addPolicy' defaultMessage='Add policy' />, onClick: () => {} , }; const wrapper = shallow( <Card {...props}> <Card.Header> <TitleAndButtonCardHeader {...headerProps} {...buttonProps} /> </Card.Header> <Card.Body>{'Body Test'}</Card.Body> </Card>, ); expect(wrapper).toMatchSnapshot(); }); });
1,643
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/card
petrpan-code/mattermost/mattermost/webapp/channels/src/components/card/__snapshots__/card.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/card/card should match snapshot 1`] = ` <Card expanded={false} > <div className="Card" > <CardHeader expanded={false} key=".0" > <div className="Card__header" > Header Test </div> </CardHeader> <CardBody expanded={false} key=".1" > <div className="Card__body expanding" onTransitionEnd={[Function]} style={ Object { "height": "", } } > Body Test </div> </CardBody> </div> </Card> `; exports[`components/card/card should match snapshot when expanded 1`] = ` <Card expanded={true} > <div className="Card expanded" > <CardHeader expanded={true} key=".0" > <div className="Card__header expanded" > Header Test <hr className="Card__hr" /> </div> </CardHeader> <CardBody expanded={true} key=".1" > <div className="Card__body expanded expanding" onTransitionEnd={[Function]} style={ Object { "height": 0, } } > Body Test </div> </CardBody> </div> </Card> `; exports[`components/card/card should match snapshot when using header content and a button 1`] = ` <div className="Card console expanded" > <CardHeader expanded={true} key=".0" > <TitleAndButtonCardHeader body={ <div> Hello! </div> } buttonText={ <Memo(MemoizedFormattedMessage) defaultMessage="Add policy" id="admin.data_retention.customPolicies.addPolicy" /> } onClick={[Function]} subtitle={ <Memo(MemoizedFormattedMessage) defaultMessage="Customize how long specific teams and channels will keep messages." id="admin.data_retention.customPolicies.subTitle" /> } title={ <Memo(MemoizedFormattedMessage) defaultMessage="Custom retention policies" id="admin.data_retention.customPolicies.title" /> } /> </CardHeader> <CardBody expanded={true} key=".1" > Body Test </CardBody> </div> `; exports[`components/card/card should match snapshot when using header content and no button 1`] = ` <div className="Card console expanded" > <CardHeader expanded={true} key=".0" > <TitleAndButtonCardHeader body={ <div> Hello! </div> } subtitle={ <Memo(MemoizedFormattedMessage) defaultMessage="Customize how long specific teams and channels will keep messages." id="admin.data_retention.customPolicies.subTitle" /> } title={ <Memo(MemoizedFormattedMessage) defaultMessage="Custom retention policies" id="admin.data_retention.customPolicies.title" /> } /> </CardHeader> <CardBody expanded={true} key=".1" > Body Test </CardBody> </div> `;
1,646
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/center_message_lock/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {emptyLimits} from 'tests/constants/cloud'; import {emptyTeams} from 'tests/constants/teams'; import {adminUsersState, endUsersState} from 'tests/constants/users'; import {screen, renderWithContext} from 'tests/react_testing_utils'; import {makeEmptyUsage} from 'utils/limits_test'; import {TestHelper} from 'utils/test_helper'; import CenterMessageLock from './'; jest.mock('mattermost-redux/actions/cloud', () => { const actual = jest.requireActual('mattermost-redux/actions/cloud'); return { ...actual, getCloudLimits: jest.fn(), }; }); const initialState = { entities: { usage: makeEmptyUsage(), users: adminUsersState(), cloud: { limits: {...emptyLimits(), limitsLoaded: false}, }, general: { license: TestHelper.getCloudLicenseMock(), }, teams: emptyTeams(), posts: { postsInChannel: { channelId: [ { order: ['a', 'b', 'c'], oldest: true, }, ], }, posts: { a: TestHelper.getPostMock({id: 'a', create_at: 3}), b: TestHelper.getPostMock({id: 'b', create_at: 2}), c: TestHelper.getPostMock({id: 'c', create_at: 1}), }, }, }, }; const exceededLimitsState = { ...initialState, entities: { ...initialState.entities, cloud: { ...initialState.entities.cloud, limits: { ...initialState.entities.cloud.limits, limitsLoaded: true, limits: { messages: { history: 2, }, }, }, }, usage: { ...initialState.entities.usage, messages: { ...initialState.entities.usage.messages, history: 3, }, }, }, }; const exceededLimitsStateNoAccessiblePosts = { ...exceededLimitsState, entities: { ...exceededLimitsState.entities, posts: { postsInChannel: { channelId: [ ], }, posts: {}, }, }, }; const endUserLimitExceeded = { ...exceededLimitsState, entities: { ...exceededLimitsState.entities, users: endUsersState(), }, }; describe('CenterMessageLock', () => { it('returns null if limits not loaded', () => { renderWithContext( <CenterMessageLock channelId={'channelId'}/>, initialState, ); expect(screen.queryByText('Notify Admin')).not.toBeInTheDocument(); expect(screen.queryByText('Upgrade now')).not.toBeInTheDocument(); }); it('Admins have a call to upgrade', () => { renderWithContext( <CenterMessageLock channelId={'channelId'}/>, exceededLimitsState, ); screen.getByText('Upgrade now'); }); it('End users have a call to notify admin', () => { renderWithContext( <CenterMessageLock channelId={'channelId'}/>, endUserLimitExceeded, ); screen.getByText('Notify Admin'); }); it('Filtered messages over one year old display year', () => { renderWithContext( <CenterMessageLock channelId={'channelId'}/>, exceededLimitsState, ); screen.getByText('January 1, 1970', {exact: false}); }); it('New filtered messages do not show year', () => { const state = JSON.parse(JSON.stringify(exceededLimitsState)); const now = new Date(); const firstOfMonth = new Date(now.getFullYear(), now.getMonth(), 1); const expectedDate = firstOfMonth.toLocaleString('en', {month: 'long', day: 'numeric'}); state.entities.posts.posts.c.create_at = Date.parse(firstOfMonth.toUTCString()); renderWithContext( <CenterMessageLock channelId={'channelId'}/>, state, ); screen.getByText(expectedDate, {exact: false}); }); it('when there are no messages, uses day after day of most recently archived post', () => { const now = Date.now(); const secondOfMonth = new Date(now + (1000 * 60 * 60 * 24)); const expectedDate = secondOfMonth.toLocaleString('en', {month: 'long', day: 'numeric'}); renderWithContext( <CenterMessageLock channelId={'channelId'} firstInaccessiblePostTime={now} />, exceededLimitsStateNoAccessiblePosts, ); screen.getByText(expectedDate, {exact: false}); }); });
1,650
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header/channel_header.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ComponentProps} from 'react'; import type {ChannelType} from '@mattermost/types/channels'; import type {UserCustomStatus} from '@mattermost/types/users'; import ChannelHeader from 'components/channel_header/channel_header'; import ChannelInfoButton from 'components/channel_header/channel_info_button'; import Markdown from 'components/markdown'; import GuestTag from 'components/widgets/tag/guest_tag'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import Constants, {RHSStates} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; describe('components/ChannelHeader', () => { const baseProps: ComponentProps<typeof ChannelHeader> = { actions: { favoriteChannel: jest.fn(), unfavoriteChannel: jest.fn(), showPinnedPosts: jest.fn(), showChannelFiles: jest.fn(), closeRightHandSide: jest.fn(), openModal: jest.fn(), closeModal: jest.fn(), getCustomEmojisInText: jest.fn(), updateChannelNotifyProps: jest.fn(), goToLastViewedChannel: jest.fn(), showChannelMembers: jest.fn(), }, announcementBarCount: 1, teamId: 'team_id', channel: TestHelper.getChannelMock({}), channelMember: TestHelper.getChannelMembershipMock({}), currentUser: TestHelper.getUserMock({}), teammateNameDisplaySetting: '', currentRelativeTeamUrl: '', isCustomStatusEnabled: false, isCustomStatusExpired: false, isFileAttachmentsEnabled: true, lastActivityTimestamp: 1632146562846, isLastActiveEnabled: true, timestampUnits: [ 'now', 'minute', 'hour', ], hideGuestTags: false, }; const populatedProps = { ...baseProps, channel: TestHelper.getChannelMock({ id: 'channel_id', team_id: 'team_id', name: 'Test', delete_at: 0, }), channelMember: TestHelper.getChannelMembershipMock({ channel_id: 'channel_id', user_id: 'user_id', }), currentUser: TestHelper.getUserMock({ id: 'user_id', bot_description: 'the bot description', }), }; test('should render properly when empty', () => { const wrapper = shallowWithIntl( <ChannelHeader {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render properly when populated', () => { const wrapper = shallowWithIntl( <ChannelHeader {...populatedProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render properly when populated with channel props', () => { const props = { ...baseProps, channel: TestHelper.getChannelMock({ id: 'channel_id', team_id: 'team_id', name: 'Test', header: 'See ~test', props: { channel_mentions: { test: { display_name: 'Test', }, }, }, }), channelMember: TestHelper.getChannelMembershipMock({ channel_id: 'channel_id', user_id: 'user_id', }), currentUser: TestHelper.getUserMock({ id: 'user_id', }), }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render archived view', () => { const props = { ...populatedProps, channel: {...populatedProps.channel, delete_at: 1234}, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render shared view', () => { const props = { ...populatedProps, channel: TestHelper.getChannelMock({ ...populatedProps.channel, shared: true, type: Constants.OPEN_CHANNEL as ChannelType, }), }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render correct menu when muted', () => { const props = { ...populatedProps, isMuted: true, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should unmute the channel when mute icon is clicked', () => { const props = { ...populatedProps, isMuted: true, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); wrapper.find('.channel-header__mute').simulate('click'); wrapper.update(); expect(props.actions.updateChannelNotifyProps).toHaveBeenCalledTimes(1); expect(props.actions.updateChannelNotifyProps).toHaveBeenCalledWith('user_id', 'channel_id', {mark_unread: 'all'}); }); test('should render active pinned posts', () => { const props = { ...populatedProps, rhsState: RHSStates.PIN, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render active channel files', () => { const props = { ...populatedProps, rhsState: RHSStates.CHANNEL_FILES, showChannelFilesButton: true, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render not active channel files', () => { const props = { ...populatedProps, rhsState: RHSStates.PIN, showChannelFilesButton: true, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render active flagged posts', () => { const props = { ...populatedProps, rhsState: RHSStates.FLAG, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render active mentions posts', () => { const props = { ...populatedProps, rhsState: RHSStates.MENTION, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render bot description', () => { const props = { ...populatedProps, channel: TestHelper.getChannelMock({ header: 'not the bot description', type: Constants.DM_CHANNEL as ChannelType, }), dmUser: TestHelper.getUserMock({ id: 'user_id', is_bot: true, bot_description: 'the bot description', }), }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper.containsMatchingElement( <Markdown message={props.currentUser.bot_description} />, )).toEqual(true); }); test('should render the pinned icon with the pinned posts count', () => { const props = { ...populatedProps, pinnedPostsCount: 2, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render the guest tags on gms', () => { const props = { ...populatedProps, channel: TestHelper.getChannelMock({ header: 'test', display_name: 'regular_user, guest_user', type: Constants.GM_CHANNEL as ChannelType, }), gmMembers: [ TestHelper.getUserMock({ id: 'user_id', username: 'regular_user', roles: 'system_user', }), TestHelper.getUserMock({ id: 'guest_id', username: 'guest_user', roles: 'system_guest', }), ], }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper.containsMatchingElement( <GuestTag/>, )).toEqual(true); }); test('should render properly when custom status is set', () => { const props = { ...populatedProps, channel: TestHelper.getChannelMock({ header: 'not the bot description', type: Constants.DM_CHANNEL as ChannelType, status: 'offline', }), dmUser: TestHelper.getUserMock({ id: 'user_id', is_bot: false, }), isCustomStatusEnabled: true, customStatus: { emoji: 'calender', text: 'In a meeting', } as UserCustomStatus, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should render properly when custom status is expired', () => { const props = { ...populatedProps, channel: TestHelper.getChannelMock({ header: 'not the bot description', type: Constants.DM_CHANNEL as ChannelType, status: 'offline', }), dmUser: TestHelper.getUserMock({ id: 'user_id', is_bot: false, }), isCustomStatusEnabled: true, isCustomStatusExpired: true, customStatus: { emoji: 'calender', text: 'In a meeting', } as UserCustomStatus, }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should contain the channel info button', () => { const wrapper = shallowWithIntl( <ChannelHeader {...populatedProps}/>, ); expect(wrapper.contains( <ChannelInfoButton channel={populatedProps.channel}/>, )).toEqual(true); }); test('should match snapshot with last active display', () => { const props = { ...populatedProps, channel: TestHelper.getChannelMock({ header: 'not the bot description', type: Constants.DM_CHANNEL as ChannelType, status: 'offline', }), dmUser: TestHelper.getUserMock({ id: 'user_id', is_bot: false, props: { show_last_active: 'true', }, }), }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with no last active display because it is disabled', () => { const props = { ...populatedProps, isLastActiveEnabled: false, channel: TestHelper.getChannelMock({ header: 'not the bot description', type: Constants.DM_CHANNEL as ChannelType, status: 'offline', }), dmUser: TestHelper.getUserMock({ id: 'user_id', is_bot: false, props: { show_last_active: 'false', }, }), }; const wrapper = shallowWithIntl( <ChannelHeader {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,654
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header/__snapshots__/channel_header.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeader should match snapshot with last active display 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> <MemoizedFormattedMessage defaultMessage="{displayname} (you) " id="channel_header.directchannel.you" values={ Object { "displayname": "some-user", } } /> </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <StatusIcon button={false} className="" status="offline" /> <span className="header-status__text" > <span className="last-active__text" > <MemoizedFormattedMessage defaultMessage="Active {timestamp}" id="channel_header.lastActive" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </span> </span> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should match snapshot with no last active display because it is disabled 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> <MemoizedFormattedMessage defaultMessage="{displayname} (you) " id="channel_header.directchannel.you" values={ Object { "displayname": "some-user", } } /> </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <StatusIcon button={false} className="" status="offline" /> <span className="header-status__text" > <MemoizedFormattedMessage defaultMessage="Offline" id="status_dropdown.set_offline" /> </span> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render active channel files 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left channel-header__icon--active" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render active flagged posts 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render active mentions posts 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render active pinned posts 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left channel-header__icon--active" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render archived view 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> <ArchiveIcon className="icon icon__archive icon channel-header-archived-icon svg-text-color" /> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 1234, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 1234, "display_name": "name", "group_constrained": false, "header": "header", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render correct menu when muted 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="channelMutedTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Unmute" id="channelHeader.unmute" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="Muted Icon" className="style--none color--link channel-header__mute inactive" id="toggleMute" onClick={[Function]} > <i className="icon icon-bell-off-outline" /> </button> </OverlayTrigger> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render not active channel files 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left channel-header__icon--active" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render properly when custom status is expired 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> <MemoizedFormattedMessage defaultMessage="{displayname} (you) " id="channel_header.directchannel.you" values={ Object { "displayname": "some-user", } } /> </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <StatusIcon button={false} className="" status="offline" /> <span className="header-status__text" > <span className="last-active__text" > <MemoizedFormattedMessage defaultMessage="Active {timestamp}" id="channel_header.lastActive" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </span> </span> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render properly when custom status is set 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> <MemoizedFormattedMessage defaultMessage="{displayname} (you) " id="channel_header.directchannel.you" values={ Object { "displayname": "some-user", } } /> </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <StatusIcon button={false} className="" status="offline" /> <span className="header-status__text" > <span className="last-active__text" > <MemoizedFormattedMessage defaultMessage="Active {timestamp}" id="channel_header.lastActive" values={ Object { "timestamp": <Memo(Connect(injectIntl(Timestamp))) style="short" units={ Array [ "now", "minute", "hour", ] } useTime={false} value={1632146562846} />, } } /> </span> <div className="custom-emoji__wrapper" > <Memo(CustomStatusEmoji) emojiStyle={ Object { "margin": "0 4px 1px", "verticalAlign": "top", } } showTooltip={true} tooltipDirection="bottom" userID="user_id" /> <CustomStatusText className="" text="In a meeting" tooltipDirection="bottom" /> </div> </span> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="not the bot description" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "not the bot description", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "DN", "purpose": "purpose", "scheme_id": "id", "status": "offline", "team_id": "team_id", "type": "D", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render properly when empty 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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, } } /> </div> </div> `; exports[`components/ChannelHeader should render properly when populated 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render properly when populated with channel props 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="See ~test" options={ Object { "atMentions": true, "channelNamesMap": Object { "test": Object { "display_name": "Test", }, }, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="See ~test" options={ Object { "atMentions": true, "channelNamesMap": Object { "test": Object { "display_name": "Test", }, }, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="See ~test" options={ Object { "atMentions": true, "channelNamesMap": Object { "test": Object { "display_name": "Test", }, }, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "See ~test", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "Test", "props": Object { "channel_mentions": Object { "test": Object { "display_name": "Test", }, }, }, "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "See ~test", "id": "channel_id", "last_post_at": 0, "last_root_post_at": 0, "name": "Test", "props": Object { "channel_mentions": Object { "test": Object { "display_name": "Test", }, }, }, "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render shared view 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name <SharedChannelIndicator channelType="O" className="shared-channel-icon" withTooltip={true} /> </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "shared": true, "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "shared": true, "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `; exports[`components/ChannelHeader should render the pinned icon with the pinned posts count 1`] = ` <div aria-label="channel header region" className="channel-header alt a11y__region" data-a11y-sort-order="8" data-channelid="channel_id" id="channel-header" role="banner" tabIndex={-1} > <div className="flex-parent" > <div className="flex-child" > <div className="channel-header__info" id="channelHeaderInfo" > <div className="channel-header__title dropdown" > <div> <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} > <div className="channel-header__top" id="channelHeaderDropdownButton" > <button aria-label="channel menu" className="channel-header__trigger style--none " > <strong aria-level={2} className="heading" id="channelHeaderTitle" role="heading" > <span> name </span> </strong> <span className="icon icon-chevron-down header-dropdown-chevron-icon" id="channelHeaderDropdownIcon" /> </button> </div> <Memo(ChannelHeaderDropdown) /> </MenuWrapper> <OverlayTrigger defaultOverlayShown={false} delayShow={400} key="isFavorite-undefined" onEntering={[Function]} overlay={ <Tooltip id="favoriteTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Add to Favorites" id="channelHeader.addToFavorites" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button aria-label="add to favorites" className="style--none color--link channel-header__favorites inactive" id="toggleFavorite" onClick={[Function]} > <i className="icon icon-star-outline" /> </button> </OverlayTrigger> </div> </div> <div className="channel-header__description" dir="auto" id="channelHeaderDescription" > <HeaderIconWrapper ariaLabel={true} buttonClass="member-rhs__trigger channel-header__icon channel-header__icon--left channel-header__icon--wide" buttonId="member_rhs" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-account-outline channel-header__members" /> <span className="icon__text" id="channelMemberCountText" > - </span> </React.Fragment> } onClick={[Function]} tooltipKey="channelMembers" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderPinButton" iconComponent={ <React.Fragment> <i aria-hidden="true" className="icon icon-pin-outline channel-header__pin" /> <span className="icon__text" id="channelPinnedPostCountText" > 2 </span> </React.Fragment> } onClick={[Function]} tooltipKey="pinnedPosts" /> <HeaderIconWrapper ariaLabel={true} buttonClass="channel-header__icon channel-header__icon--wide channel-header__icon--left" buttonId="channelHeaderFilesButton" iconComponent={ <i className="icon icon-file-text-outline" /> } onClick={[Function]} tooltipKey="channelFiles" /> <div className="header-popover-text-measurer" > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </div> <span className="header-description__text" onClick={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <Overlay animation={[Function]} onHide={[Function]} placement="bottom" rootClose={true} show={false} target={null} > <Popover className="channel-header__popover" id="header-popover" placement="bottom" popoverSize="lg" popoverStyle="info" style={ Object { "maxWidth": 0, "transform": "translate(0px, 0px)", } } > <span onClick={[Function]} > <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": false, } } /> </span> </Popover> </Overlay> <Connect(Markdown) imageProps={ Object { "hideUtilities": true, } } message="header" options={ Object { "atMentions": true, "channelNamesMap": undefined, "mentionHighlight": false, "singleline": true, } } /> </span> </div> </div> </div> <Connect(injectIntl(ChannelHeaderPlug)) 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } channelMember={ Object { "channel_id": "channel_id", "last_update_at": 0, "last_viewed_at": 0, "mention_count": 0, "mention_count_root": 0, "msg_count": 0, "msg_count_root": 0, "notify_props": Object { "channel_auto_follow_threads": "off", "desktop": "default", "email": "default", "ignore_channel_mentions": "default", "mark_unread": "all", "push": "default", }, "roles": "channel_user", "scheme_admin": false, "scheme_user": true, "urgent_mention_count": 0, "user_id": "user_id", } } /> <Connect(CallButton) /> <ChannelInfoButton 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": "Test", "purpose": "purpose", "scheme_id": "id", "team_id": "team_id", "type": "O", "update_at": 0, } } /> </div> </div> `;
1,655
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header/components/header_icon_wrapper.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 HeaderIconWrapper from 'components/channel_header/components/header_icon_wrapper'; import FlagIcon from 'components/widgets/icons/flag_icon'; import MentionsIcon from 'components/widgets/icons/mentions_icon'; import PinIcon from 'components/widgets/icons/pin_icon'; import SearchIcon from 'components/widgets/icons/search_icon'; describe('components/channel_header/components/HeaderIconWrapper', () => { function emptyFunction() {} //eslint-disable-line no-empty-function const mentionsIcon = ( <MentionsIcon className='icon icon__mentions' aria-hidden='true' /> ); const baseProps = { iconComponent: mentionsIcon, buttonClass: 'button_class', buttonId: 'button_id', onClick: emptyFunction, tooltipKey: 'recentMentions', }; test('should match snapshot, on MentionsIcon', () => { const wrapper = shallow( <HeaderIconWrapper {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on FlagIcon', () => { const flagIcon = ( <FlagIcon className='icon icon__flag' aria-hidden='true' /> ); const props = {...baseProps, iconComponent: flagIcon, tooltipKey: 'flaggedPosts'}; const wrapper = shallow( <HeaderIconWrapper {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on PinIcon', () => { const pinIcon = ( <PinIcon className='icon icon__pin' aria-hidden='true' /> ); const props = {...baseProps, iconComponent: pinIcon, tooltipKey: 'pinnedPosts', buttonClass: 'pinned_posts_class'}; const wrapper = shallow( <HeaderIconWrapper {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on ChannelFilesIcon', () => { const channelFilesIcon = <i className='icon icon-file-document-outline'/>; const props = {...baseProps, iconComponent: channelFilesIcon, tooltipKey: 'channelFiles', buttonClass: 'channel_files_class'}; const wrapper = shallow( <HeaderIconWrapper {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on SearchIcon', () => { const searchIcon = ( <SearchIcon className='icon icon__search' aria-hidden='true' /> ); const props = {...baseProps, iconComponent: searchIcon, tooltipKey: 'search', buttonClass: 'search_class'}; const wrapper = shallow( <HeaderIconWrapper {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on PluginIcon with tooltipText', () => { const pluginIcon = ( <i className='fa fa-anchor'/> ); const props = {...baseProps, iconComponent: pluginIcon, tooltipKey: 'plugin', tooltipText: 'plugin_tooltip_text'}; const wrapper = shallow( <HeaderIconWrapper {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on PluginIcon without tooltipText', () => { const pluginIcon = ( <i className='fa fa-anchor'/> ); const props = {...baseProps, iconComponent: pluginIcon, tooltipKey: 'plugin'}; const wrapper = shallow( <HeaderIconWrapper {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
1,657
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header/components/__snapshots__/header_icon_wrapper.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on ChannelFilesIcon 1`] = ` <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="channel-files" id="channelFilesTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Channel files" id="channel_header.channelFiles" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel_files_class" id="button_id" onClick={[Function]} > <i className="icon icon-file-document-outline" /> </button> </OverlayTrigger> </div> `; exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on FlagIcon 1`] = ` <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="text-nowrap" id="flaggedTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Saved messages" id="channel_header.flagged" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="button_class" id="button_id" onClick={[Function]} > <FlagIcon aria-hidden="true" className="icon icon__flag" /> </button> </OverlayTrigger> </div> `; exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on MentionsIcon 1`] = ` <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="recentMentionsTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Recent mentions" id="channel_header.recentMentions" /> <Memo(KeyboardShortcutSequence) hideDescription={true} isInsideTooltip={true} shortcut={ Object { "default": Object { "defaultMessage": "Recent mentions: Ctrl|Shift|M", "id": "shortcuts.nav.recent_mentions", }, "mac": Object { "defaultMessage": "Recent mentions: ⌘|Shift|M", "id": "shortcuts.nav.recent_mentions.mac", }, } } /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="button_class" id="button_id" onClick={[Function]} > <MentionsIcon aria-hidden="true" className="icon icon__mentions" /> </button> </OverlayTrigger> </div> `; exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on PinIcon 1`] = ` <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="pinned-posts" id="pinnedPostTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Pinned messages" id="channel_header.pinnedPosts" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="pinned_posts_class" id="button_id" onClick={[Function]} > <PinIcon aria-hidden="true" className="icon icon__pin" /> </button> </OverlayTrigger> </div> `; exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on PluginIcon with tooltipText 1`] = ` <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> plugin_tooltip_text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="button_class" id="button_id" onClick={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </div> `; exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on PluginIcon without tooltipText 1`] = ` <Fragment> <div className="flex-child" > <button className="button_class" id="button_id" onClick={[Function]} > <i className="fa fa-anchor" /> </button> </div> </Fragment> `; exports[`components/channel_header/components/HeaderIconWrapper should match snapshot, on SearchIcon 1`] = ` <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="searchTooltip" > <Memo(MemoizedFormattedMessage) defaultMessage="Search" id="channel_header.search" /> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="search_class" id="button_id" onClick={[Function]} > <SearchIcon aria-hidden="true" className="icon icon__search" /> </button> </OverlayTrigger> </div> `;
1,658
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/channel_header_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 {TestHelper} from 'utils/test_helper'; import ChannelHeaderDropdown from './channel_header_dropdown_items'; import type {Props} from './channel_header_dropdown_items'; describe('components/ChannelHeaderDropdown', () => { const defaultProps = { user: TestHelper.getUserMock({id: 'test-user-id'}), channel: TestHelper.getChannelMock({id: 'test-channel-id'}), isDefault: false, isFavorite: false, isReadonly: false, isMuted: false, isArchived: false, isMobile: false, penultimateViewedChannelName: 'test-channel', pluginMenuItems: [], isLicensedForLDAPGroups: false, }; test('should match snapshot with no plugin items', () => { const wrapper = shallow(<ChannelHeaderDropdown {...defaultProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with plugins', () => { const props: Props = { ...defaultProps, pluginMenuItems: [ {id: 'plugin-1', pluginId: 'playbooks', action: jest.fn(), text: 'plugin-1-text'}, {id: 'plugin-2', pluginId: 'playbooks', action: jest.fn(), text: 'plugin-2-text'}, ], }; const wrapper = shallow(<ChannelHeaderDropdown {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
1,664
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/__snapshots__/channel_header_dropdown.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown should match snapshot with no plugin items 1`] = ` <Fragment> <Connect(ToggleInfo) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } show={true} /> <Memo(ChannelMoveToSubMenuOld) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } inHeaderDropdown={true} openUp={false} /> <Memo(MenuGroup)> <Connect(ToggleFavoriteChannel) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } isFavorite={false} show={false} /> <Connect(Component) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } show={false} /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, "currentUser": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "test-user-id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelNotificationPreferences" modalId="channel_notifications" show={true} text="Notification Preferences" /> <Connect(MenuItemToggleMuteChannel) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelToggleMuteChannel" isMuted={false} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "test-user-id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_public_channel_members", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelAddMembers" modalId="channel_invite" show={true} text="Add Members" /> <MenuItemToggleModalRedux dialogProps={ Object { "isExistingChannel": true, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelAddMembers" modalId="create_dm_channel" show={false} text="Add Members" /> </Connect(Component)> <Connect(ToggleChannelMembersRHS) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelViewMembers" show={false} text="View Members" /> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_public_channel_members", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelAddGroups" modalId="add_groups_to_channel" show={false} text="Add Groups" /> <MenuItemToggleModalRedux dialogProps={ Object { "channelID": "test-channel-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelManageGroups" modalId="manage_channel_groups" show={false} text="Manage Groups" /> <Connect(ToggleChannelMembersRHS) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } editMembers={true} id="channelManageMembers" show={true} text="Manage Members" /> </Connect(Component)> <Connect(Component) channelId="test-channel-id" invert={true} permissions={ Array [ "manage_public_channel_members", ] } teamId="team_id" > <Connect(ToggleChannelMembersRHS) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelViewMembers" show={true} text="View Members" /> </Connect(Component)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelEditHeader" modalId="edit_channel_header" show={false} text="Edit Conversation Header" /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="convertGMPrivateChannel" modalId="convert_gm_to_channel" show={false} text="Convert to Private Channel" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_public_channel_properties", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelEditHeader" modalId="edit_channel_header" show={true} text="Edit Channel Header" /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelEditPurpose" modalId="edit_channel_purpose" show={true} text="Edit Channel Purpose" /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelRename" modalId="rename_channel" show={true} text="Rename Channel" /> </Connect(Component)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "convert_public_channel_to_private", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channelDisplayName": "name", "channelId": "test-channel-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelConvertToPrivate" modalId="convert_channel" show={true} text="Convert to Private Channel" /> </Connect(Component)> <Connect(LeaveChannel) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelLeaveChannel" isDefault={false} isGuestUser={false} /> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "delete_public_channel", ] } teamId="team_id" > <MenuItemToggleModalRedux className="MenuItem__dangerous" dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, "penultimateViewedChannelName": "test-channel", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelArchiveChannel" modalId="delete_channel" show={true} text="Archive Channel" /> </Connect(Component)> <Connect(CloseMessage) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } currentUser={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "test-user-id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } id="channelCloseMessage" /> <Connect(Component) isArchived={false} /> </Memo(MenuGroup)> <Memo(MenuGroup) /> <Memo(MenuGroup)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_team", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelUnarchiveChannel" modalId="unarchive_channel" show={false} text="Unarchive Channel" /> </Connect(Component)> </Memo(MenuGroup)> </Fragment> `; exports[`components/ChannelHeaderDropdown should match snapshot with plugins 1`] = ` <Fragment> <Connect(ToggleInfo) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } show={true} /> <Memo(ChannelMoveToSubMenuOld) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } inHeaderDropdown={true} openUp={false} /> <Memo(MenuGroup)> <Connect(ToggleFavoriteChannel) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } isFavorite={false} show={false} /> <Connect(Component) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } show={false} /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, "currentUser": Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "test-user-id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelNotificationPreferences" modalId="channel_notifications" show={true} text="Notification Preferences" /> <Connect(MenuItemToggleMuteChannel) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelToggleMuteChannel" isMuted={false} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "test-user-id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_public_channel_members", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelAddMembers" modalId="channel_invite" show={true} text="Add Members" /> <MenuItemToggleModalRedux dialogProps={ Object { "isExistingChannel": true, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelAddMembers" modalId="create_dm_channel" show={false} text="Add Members" /> </Connect(Component)> <Connect(ToggleChannelMembersRHS) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelViewMembers" show={false} text="View Members" /> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_public_channel_members", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelAddGroups" modalId="add_groups_to_channel" show={false} text="Add Groups" /> <MenuItemToggleModalRedux dialogProps={ Object { "channelID": "test-channel-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelManageGroups" modalId="manage_channel_groups" show={false} text="Manage Groups" /> <Connect(ToggleChannelMembersRHS) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } editMembers={true} id="channelManageMembers" show={true} text="Manage Members" /> </Connect(Component)> <Connect(Component) channelId="test-channel-id" invert={true} permissions={ Array [ "manage_public_channel_members", ] } teamId="team_id" > <Connect(ToggleChannelMembersRHS) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelViewMembers" show={true} text="View Members" /> </Connect(Component)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelEditHeader" modalId="edit_channel_header" show={false} text="Edit Conversation Header" /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="convertGMPrivateChannel" modalId="convert_gm_to_channel" show={false} text="Convert to Private Channel" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_public_channel_properties", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelEditHeader" modalId="edit_channel_header" show={true} text="Edit Channel Header" /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelEditPurpose" modalId="edit_channel_purpose" show={true} text="Edit Channel Purpose" /> <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelRename" modalId="rename_channel" show={true} text="Rename Channel" /> </Connect(Component)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "convert_public_channel_to_private", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channelDisplayName": "name", "channelId": "test-channel-id", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelConvertToPrivate" modalId="convert_channel" show={true} text="Convert to Private Channel" /> </Connect(Component)> <Connect(LeaveChannel) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } id="channelLeaveChannel" isDefault={false} isGuestUser={false} /> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "delete_public_channel", ] } teamId="team_id" > <MenuItemToggleModalRedux className="MenuItem__dangerous" dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, "penultimateViewedChannelName": "test-channel", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelArchiveChannel" modalId="delete_channel" show={true} text="Archive Channel" /> </Connect(Component)> <Connect(CloseMessage) channel={ Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, } } currentUser={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "test-user-id", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } id="channelCloseMessage" /> <Connect(Component) isArchived={false} /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction id="plugin-1_pluginmenuitem" key="plugin-1_pluginmenuitem" onClick={[Function]} show={true} text="plugin-1-text" /> <MenuItemAction id="plugin-2_pluginmenuitem" key="plugin-2_pluginmenuitem" onClick={[Function]} show={true} text="plugin-2-text" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(Component) channelId="test-channel-id" permissions={ Array [ "manage_team", ] } teamId="team_id" > <MenuItemToggleModalRedux dialogProps={ Object { "channel": Object { "create_at": 0, "creator_id": "id", "delete_at": 0, "display_name": "name", "group_constrained": false, "header": "header", "id": "test-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, }, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="channelUnarchiveChannel" modalId="unarchive_channel" show={false} text="Unarchive Channel" /> </Connect(Component)> </Memo(MenuGroup)> </Fragment> `;
1,665
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/close_channel/close_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 Menu from 'components/widgets/menu/menu'; import CloseChannel from './close_channel'; describe('components/ChannelHeaderDropdown/MenuItem.CloseChannel', () => { const baseProps = { isArchived: true, actions: { goToLastViewedChannel: jest.fn(), }, }; it('should match snapshot', () => { const wrapper = shallow(<CloseChannel {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('shoud be hidden if the channel is not archived', () => { const props = { ...baseProps, isArchived: false, }; const wrapper = shallow(<CloseChannel {...props}/>); expect(wrapper).toMatchSnapshot(); }); it('should runs goToLastViewedChannel function on click', () => { const props = { ...baseProps, actions: { ...baseProps.actions, goToLastViewedChannel: jest.fn(), }, }; const wrapper = shallow(<CloseChannel {...props}/>); wrapper.find(Menu.ItemAction).simulate('click'); expect(props.actions.goToLastViewedChannel).toHaveBeenCalled(); }); });
1,668
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/close_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/close_channel/__snapshots__/close_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown/MenuItem.CloseChannel shoud be hidden if the channel is not archived 1`] = ` <MenuItemAction onClick={[MockFunction]} show={false} text="Close Channel" /> `; exports[`components/ChannelHeaderDropdown/MenuItem.CloseChannel should match snapshot 1`] = ` <MenuItemAction onClick={[MockFunction]} show={true} text="Close Channel" /> `;
1,669
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/close_message/close_message.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ChannelType} from '@mattermost/types/channels'; import type {TeamType} from '@mattermost/types/teams'; import Menu from 'components/widgets/menu/menu'; import {Constants} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import CloseMessage from './close_message'; describe('components/ChannelHeaderDropdown/MenuItem.CloseMessage', () => { const baseProps = { currentUser: TestHelper.getUserMock(), redirectChannel: 'test-default-channel', currentTeam: TestHelper.getTeamMock({ id: 'team_id', name: 'test-team', display_name: 'Test team display name', description: 'Test team description', type: 'team-type' as TeamType, }), actions: { savePreferences: jest.fn(() => Promise.resolve()), leaveDirectChannel: jest.fn(() => Promise.resolve()), }, }; const groupChannel = TestHelper.getChannelMock({ id: 'channel_id', type: Constants.GM_CHANNEL as ChannelType, }); const directChannel = TestHelper.getChannelMock({ id: 'channel_id', type: Constants.DM_CHANNEL as ChannelType, teammate_id: 'teammate-id', }); it('should match snapshot for DM Channel', () => { const props = {...baseProps, channel: directChannel}; const wrapper = shallow(<CloseMessage {...props}/>); expect(wrapper).toMatchSnapshot(); }); it('should match snapshot for GM Channel', () => { const props = {...baseProps, channel: groupChannel}; const wrapper = shallow(<CloseMessage {...props}/>); expect(wrapper).toMatchSnapshot(); }); it('should run savePreferences function on click for DM', () => { const props = {...baseProps, channel: directChannel}; const wrapper = shallow(<CloseMessage {...props}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(props.actions.savePreferences).toBeCalledWith(props.currentUser.id, [{user_id: props.currentUser.id, category: Constants.Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, name: props.channel.teammate_id, value: 'false'}]); }); it('should run savePreferences function on click for GM', () => { const props = {...baseProps, channel: groupChannel}; const wrapper = shallow(<CloseMessage {...props}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(props.actions.savePreferences).toBeCalledWith(props.currentUser.id, [{user_id: props.currentUser.id, category: Constants.Preferences.CATEGORY_GROUP_CHANNEL_SHOW, name: props.channel.id, value: 'false'}]); }); });
1,672
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/close_message
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/close_message/__snapshots__/close_message.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown/MenuItem.CloseMessage should match snapshot for DM Channel 1`] = ` <MenuItemAction onClick={[Function]} show={true} text="Close Direct Message" /> `; exports[`components/ChannelHeaderDropdown/MenuItem.CloseMessage should match snapshot for GM Channel 1`] = ` <MenuItemAction onClick={[Function]} show={true} text="Close Group Message" /> `;
1,674
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/leave_channel/leave_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 Menu from 'components/widgets/menu/menu'; import {ModalIdentifiers} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import LeaveChannel from './leave_channel'; describe('components/ChannelHeaderDropdown/MenuItem.LeaveChannel', () => { const baseProps = { channel: TestHelper.getChannelMock({ id: 'channel_id', type: 'O', }), isGuestUser: false, isDefault: false, actions: { leaveChannel: jest.fn(), openModal: jest.fn(), }, }; it('should match snapshot', () => { const wrapper = shallow<LeaveChannel>(<LeaveChannel {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should be hidden if the channel is default channel', () => { const props = { ...baseProps, isDefault: true, }; const wrapper = shallow<LeaveChannel>(<LeaveChannel {...props}/>); expect(wrapper).toMatchSnapshot(); }); it('should be hidden if the channel type is DM or GM', () => { const props = { ...baseProps, channel: {...baseProps.channel}, }; const makeWrapper = () => shallow(<LeaveChannel {...props}/>); props.channel.type = 'D'; expect(makeWrapper()).toMatchSnapshot(); props.channel.type = 'G'; expect(makeWrapper()).toMatchSnapshot(); }); it('should runs leaveChannel function on click only if the channel is not private', () => { const props = { ...baseProps, channel: {...baseProps.channel}, actions: {...baseProps.actions}, }; const wrapper = shallow<LeaveChannel>(<LeaveChannel {...props}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(props.actions.leaveChannel).toHaveBeenCalledWith(props.channel.id); expect(props.actions.openModal).not.toHaveBeenCalled(); props.channel.type = 'P'; props.actions.leaveChannel = jest.fn(); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(props.actions.leaveChannel).not.toHaveBeenCalled(); expect(props.actions.openModal).toHaveBeenCalledWith( expect.objectContaining({ modalId: ModalIdentifiers.LEAVE_PRIVATE_CHANNEL_MODAL, dialogProps: { channel: props.channel, }, })); }); });
1,676
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/leave_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/leave_channel/__snapshots__/leave_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown/MenuItem.LeaveChannel should be hidden if the channel is default channel 1`] = ` <MenuItemAction isDangerous={true} onClick={[Function]} show={false} text="Leave Channel" /> `; exports[`components/ChannelHeaderDropdown/MenuItem.LeaveChannel should be hidden if the channel type is DM or GM 1`] = ` <MenuItemAction isDangerous={true} onClick={[Function]} show={false} text="Leave Channel" /> `; exports[`components/ChannelHeaderDropdown/MenuItem.LeaveChannel should be hidden if the channel type is DM or GM 2`] = ` <MenuItemAction isDangerous={true} onClick={[Function]} show={false} text="Leave Channel" /> `; exports[`components/ChannelHeaderDropdown/MenuItem.LeaveChannel should match snapshot 1`] = ` <MenuItemAction isDangerous={true} onClick={[Function]} show={true} text="Leave Channel" /> `;
1,680
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/toggle_favorite_channel/toggle_favorite_channel.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ChannelType} from '@mattermost/types/channels'; import Menu from 'components/widgets/menu/menu'; import ToggleFavoriteChannel from './toggle_favorite_channel'; describe('components/ChannelHeaderDropdown/MenuItem.ToggleFavoriteChannel', () => { 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, }, actions: { favoriteChannel: jest.fn(), unfavoriteChannel: jest.fn(), }, }; const propsForFavorite = { ...baseProps, isFavorite: true, actions: { favoriteChannel: jest.fn(), unfavoriteChannel: jest.fn(), }, }; const propsForNotFavorite = { ...baseProps, isFavorite: false, actions: { favoriteChannel: jest.fn(), unfavoriteChannel: jest.fn(), }, }; it('should match snapshot for favorite channel', () => { const wrapper = shallow(<ToggleFavoriteChannel {...propsForFavorite}/>); expect(wrapper).toMatchSnapshot(); }); it('should runs unfavoriteChannel function for favorite channel', () => { const wrapper = shallow(<ToggleFavoriteChannel {...propsForFavorite}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(propsForFavorite.actions.unfavoriteChannel).toHaveBeenCalledWith(propsForFavorite.channel.id); expect(propsForFavorite.actions.favoriteChannel).not.toHaveBeenCalled(); }); it('should match snapshot for not favorite channel', () => { const wrapper = shallow(<ToggleFavoriteChannel {...propsForNotFavorite}/>); expect(wrapper).toMatchSnapshot(); }); it('should runs favoriteChannel function for not favorite channel', () => { const wrapper = shallow(<ToggleFavoriteChannel {...propsForNotFavorite}/>); wrapper.find(Menu.ItemAction).simulate('click', { preventDefault: jest.fn(), }); expect(propsForNotFavorite.actions.favoriteChannel).toHaveBeenCalledWith(propsForFavorite.channel.id); expect(propsForNotFavorite.actions.unfavoriteChannel).not.toHaveBeenCalled(); }); });
1,682
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/toggle_favorite_channel
petrpan-code/mattermost/mattermost/webapp/channels/src/components/channel_header_dropdown/menu_items/toggle_favorite_channel/__snapshots__/toggle_favorite_channel.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelHeaderDropdown/MenuItem.ToggleFavoriteChannel should match snapshot for favorite channel 1`] = ` <MenuItemAction onClick={[Function]} show={true} text="Remove from Favorites" /> `; exports[`components/ChannelHeaderDropdown/MenuItem.ToggleFavoriteChannel should match snapshot for not favorite channel 1`] = ` <MenuItemAction onClick={[Function]} show={true} text="Add to Favorites" /> `;
1,686
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/toggle_mute_channel/toggle_mute_channel.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Channel} from '@mattermost/types/channels'; import type {UserProfile} from '@mattermost/types/users'; import Menu from 'components/widgets/menu/menu'; import MenuItemAction from 'components/widgets/menu/menu_items/menu_item_action'; import {Constants, NotificationLevels} from 'utils/constants'; import MenuItemToggleMuteChannel from './toggle_mute_channel'; describe('components/ChannelHeaderDropdown/MenuItemToggleMuteChannel', () => { const baseProps = { user: { id: 'user_id', } as UserProfile, channel: { id: 'channel_id', type: 'O', } as Channel, isMuted: false, actions: { updateChannelNotifyProps: jest.fn(), }, }; it('should match snapshot', () => { const wrapper = shallow(<MenuItemToggleMuteChannel {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); it('should unmute channel on click the channel was muted', () => { const props = { ...baseProps, isMuted: true, actions: { updateChannelNotifyProps: jest.fn(), }, }; const wrapper = shallow(<MenuItemToggleMuteChannel {...props}/>); wrapper.find(Menu.ItemAction).simulate('click'); expect(props.actions.updateChannelNotifyProps).toBeCalledWith( props.user.id, props.channel.id, {mark_unread: NotificationLevels.ALL}, ); }); it('should mute channel on click the channel was unmuted', () => { const props = { ...baseProps, isMuted: false, actions: { updateChannelNotifyProps: jest.fn(), }, }; const wrapper = shallow(<MenuItemToggleMuteChannel {...props}/>); wrapper.find(Menu.ItemAction).simulate('click'); expect(props.actions.updateChannelNotifyProps).toBeCalledWith( props.user.id, props.channel.id, {mark_unread: NotificationLevels.MENTION}, ); }); it('should show Mute Channel to all channel types except DM_CHANNEL and GM_CHANNEL', () => { [ Constants.OPEN_CHANNEL, Constants.PRIVATE_CHANNEL, Constants.ARCHIVED_CHANNEL, ].forEach((channelType) => { const channel = { id: 'channel_id', type: channelType, } as Channel; const wrapper = shallow( <MenuItemToggleMuteChannel {...baseProps} channel={channel} />, ); expect(wrapper.find(MenuItemAction).props().show).toEqual(true); expect(wrapper.find(MenuItemAction).props().text).toEqual('Mute Channel'); }); }); it('should show Mute Conversation to channel types DM_CHANNEL and GM_CHANNEL', () => { [ Constants.DM_CHANNEL, Constants.GM_CHANNEL, ].forEach((channelType) => { const channel = { id: 'channel_id', type: channelType, } as Channel; const wrapper = shallow( <MenuItemToggleMuteChannel {...baseProps} channel={channel} />, ); expect(wrapper.find(MenuItemAction).props().show).toEqual(true); expect(wrapper.find(MenuItemAction).props().text).toEqual('Mute Conversation'); }); }); });