level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
3,949
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/general.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import * as Actions from 'mattermost-redux/actions/general'; import {Client4} from 'mattermost-redux/client'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.General', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore(); }); afterAll(() => { TestHelper.tearDown(); }); it('getClientConfig', async () => { nock(Client4.getBaseRoute()). get('/config/client'). query(true). reply(200, {Version: '4.0.0', BuildNumber: '3', BuildDate: 'Yesterday', BuildHash: '1234'}); await Actions.getClientConfig()(store.dispatch, store.getState); const clientConfig = store.getState().entities.general.config; // Check a few basic fields since they may change over time expect(clientConfig.Version).toBeTruthy(); expect(clientConfig.BuildNumber).toBeTruthy(); expect(clientConfig.BuildDate).toBeTruthy(); expect(clientConfig.BuildHash).toBeTruthy(); }); it('getLicenseConfig', async () => { nock(Client4.getBaseRoute()). get('/license/client'). query(true). reply(200, {IsLicensed: 'false'}); await Actions.getLicenseConfig()(store.dispatch, store.getState); const licenseConfig = store.getState().entities.general.license; // Check a few basic fields since they may change over time expect(licenseConfig.IsLicensed).not.toEqual(undefined); }); it('setServerVersion', async () => { const version = '3.7.0'; await Actions.setServerVersion(version)(store.dispatch, store.getState); await TestHelper.wait(100); const {serverVersion} = store.getState().entities.general; expect(serverVersion).toEqual(version); }); it('getDataRetentionPolicy', async () => { const responseData = { message_deletion_enabled: true, file_deletion_enabled: false, message_retention_cutoff: Date.now(), file_retention_cutoff: 0, }; nock(Client4.getBaseRoute()). get('/data_retention/policy'). query(true). reply(200, responseData); await Actions.getDataRetentionPolicy()(store.dispatch, store.getState); await TestHelper.wait(100); const {dataRetentionPolicy} = store.getState().entities.general; expect(dataRetentionPolicy).toEqual(responseData); }); it('getWarnMetricsStatus', async () => { const responseData = { metric1: true, metric2: false, }; nock(Client4.getBaseRoute()). get('/warn_metrics/status'). query(true). reply(200, responseData); await Actions.getWarnMetricsStatus()(store.dispatch, store.getState); const {warnMetricsStatus} = store.getState().entities.general; expect(warnMetricsStatus.metric1).toEqual(true); expect(warnMetricsStatus.metric2).toEqual(false); }); it('getFirstAdminVisitMarketplaceStatus', async () => { const responseData = { name: 'FirstAdminVisitMarketplace', value: 'false', }; nock(Client4.getPluginsRoute()). get('/marketplace/first_admin_visit'). query(true). reply(200, responseData); await Actions.getFirstAdminVisitMarketplaceStatus()(store.dispatch, store.getState); const {firstAdminVisitMarketplaceStatus} = store.getState().entities.general; expect(firstAdminVisitMarketplaceStatus).toEqual(false); }); it('setFirstAdminVisitMarketplaceStatus', async () => { nock(Client4.getPluginsRoute()). post('/marketplace/first_admin_visit'). reply(200, OK_RESPONSE); await Actions.setFirstAdminVisitMarketplaceStatus()(store.dispatch, store.getState); const {firstAdminVisitMarketplaceStatus} = store.getState().entities.general; expect(firstAdminVisitMarketplaceStatus).toEqual(true); }); });
3,951
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/groups.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import type {GetGroupsParams} from '@mattermost/types/groups'; import {SyncableType} from '@mattermost/types/groups'; import * as Actions from 'mattermost-redux/actions/groups'; import {Client4} from 'mattermost-redux/client'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; describe('Actions.Groups', () => { let store = configureStore(); beforeEach(() => { TestHelper.initBasic(Client4); store = configureStore(); }); afterEach(() => { TestHelper.tearDown(); }); it('getGroupSyncables', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const groupTeams = [ { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', team_display_name: 'dolphins', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542643748412, }, { team_id: 'tdjrcr3hg7yazyos17a53jduna', team_display_name: 'developers', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643825026, delete_at: 0, update_at: 1542643825026, }, ]; const groupChannels = [ { channel_id: 'o3tdawqxot8kikzq8bk54zggbc', channel_display_name: 'standup', channel_type: 'P', team_id: 'tdjrcr3hg7yazyos17a53jduna', team_display_name: 'developers', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542644105041, delete_at: 0, update_at: 1542644105041, }, { channel_id: 's6oxu3embpdepyprx1fn5gjhea', channel_display_name: 'swimming', channel_type: 'P', team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', team_display_name: 'dolphins', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542644105042, delete_at: 0, update_at: 1542644105042, }, ]; nock(Client4.getBaseRoute()). get(`/groups/${groupID}/teams`). reply(200, groupTeams); nock(Client4.getBaseRoute()). get(`/groups/${groupID}/channels`). reply(200, groupChannels); await Actions.getGroupSyncables(groupID, SyncableType.Team)(store.dispatch, store.getState); await Actions.getGroupSyncables(groupID, SyncableType.Channel)(store.dispatch, store.getState); const state = store.getState(); const groupSyncables = state.entities.groups.syncables[groupID]; expect(groupSyncables).toBeTruthy(); for (let i = 0; i < 2; i++) { expect(JSON.stringify(groupSyncables.teams[i]) === JSON.stringify(groupTeams[i])).toBeTruthy(); expect(JSON.stringify(groupSyncables.channels[i]) === JSON.stringify(groupChannels[i])).toBeTruthy(); } }); it('getGroup', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const response = { id: groupID, name: '8b7ks7ngqbgndqutka48gfzaqh', display_name: 'Test Group 0', description: '', type: 'ldap', remote_id: '\\eb\\80\\94\\cd\\d4\\32\\7c\\45\\87\\79\\1b\\fe\\45\\d9\\ac\\7b', create_at: 1542399032816, update_at: 1542399032816, delete_at: 0, has_syncables: false, }; nock(Client4.getBaseRoute()). get(`/groups/${groupID}?include_member_count=false`). reply(200, response); await Actions.getGroup(groupID)(store.dispatch, store.getState); const state = store.getState(); const groups = state.entities.groups.groups; expect(groups).toBeTruthy(); expect(groups[groupID]).toBeTruthy(); expect(JSON.stringify(response) === JSON.stringify(groups[groupID])).toBeTruthy(); }); it('linkGroupSyncable', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const teamID = 'ge63nq31sbfy3duzq5f7yqn1kh'; const channelID = 'o3tdawqxot8kikzq8bk54zggbc'; const groupTeamResponse = { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const groupChannelResponse = { channel_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', auto_add: true, create_at: 1542644105041, delete_at: 0, update_at: 1542662607342, }; nock(Client4.getBaseRoute()). post(`/groups/${groupID}/teams/${teamID}/link`). reply(200, groupTeamResponse); nock(Client4.getBaseRoute()). post(`/groups/${groupID}/channels/${channelID}/link`). reply(200, groupChannelResponse); await (Actions.linkGroupSyncable as any)(groupID, teamID, SyncableType.Team)(store.dispatch, store.getState); await (Actions.linkGroupSyncable as any)(groupID, channelID, SyncableType.Channel)(store.dispatch, store.getState); const state = store.getState(); const syncables = state.entities.groups.syncables; expect(syncables[groupID]).toBeTruthy(); expect(JSON.stringify(syncables[groupID].teams[0]) === JSON.stringify(groupTeamResponse)).toBeTruthy(); expect(JSON.stringify(syncables[groupID].channels[0]) === JSON.stringify(groupChannelResponse)).toBeTruthy(); }); it('unlinkGroupSyncable', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const teamID = 'ge63nq31sbfy3duzq5f7yqn1kh'; const channelID = 'o3tdawqxot8kikzq8bk54zggbc'; const groupTeamResponse = { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const groupChannelResponse = { channel_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542644105041, delete_at: 0, update_at: 1542662607342, }; nock(Client4.getBaseRoute()). post(`/groups/${groupID}/teams/${teamID}/link`). reply(200, groupTeamResponse); nock(Client4.getBaseRoute()). post(`/groups/${groupID}/channels/${channelID}/link`). reply(200, groupChannelResponse); await (Actions.linkGroupSyncable as any)(groupID, teamID, SyncableType.Team)(store.dispatch, store.getState); await (Actions.linkGroupSyncable as any)(groupID, channelID, SyncableType.Channel)(store.dispatch, store.getState); let state = store.getState(); let syncables = state.entities.groups.syncables; expect(syncables[groupID]).toBeTruthy(); expect(JSON.stringify(syncables[groupID].teams[0]) === JSON.stringify(groupTeamResponse)).toBeTruthy(); expect(JSON.stringify(syncables[groupID].channels[0]) === JSON.stringify(groupChannelResponse)).toBeTruthy(); const beforeTeamsLength = syncables[groupID].teams.length; const beforeChannelsLength = syncables[groupID].channels.length; nock(Client4.getBaseRoute()). delete(`/groups/${groupID}/teams/${teamID}/link`). reply(204, {ok: true}); nock(Client4.getBaseRoute()). delete(`/groups/${groupID}/channels/${channelID}/link`). reply(204, {ok: true}); await Actions.unlinkGroupSyncable(groupID, teamID, SyncableType.Team)(store.dispatch, store.getState); await Actions.unlinkGroupSyncable(groupID, channelID, SyncableType.Channel)(store.dispatch, store.getState); state = store.getState(); syncables = state.entities.groups.syncables; expect(syncables[groupID]).toBeTruthy(); expect(syncables[groupID].teams.length === beforeTeamsLength - 1).toBeTruthy(); expect(syncables[groupID].channels.length === beforeChannelsLength - 1).toBeTruthy(); }); it('getGroups', async () => { const response1 = { groups: [ { id: 'xh585kyz3tn55q6ipfo57btwnc', name: 'abc', display_name: 'abc', description: '', source: 'ldap', remote_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: true, }, { id: 'qhdp6g7aubbpiyja7c4sgpe7tc', name: 'qa', display_name: 'qa', description: '', source: 'ldap', remote_id: 'qa', create_at: 1553808971548, update_at: 1553808971548, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: true, }, ], total_group_count: 2, }; nock(Client4.getBaseRoute()). get('/groups?filter_allow_reference=true&page=0&per_page=0'). reply(200, response1.groups); const groupParams: GetGroupsParams = { filter_allow_reference: true, page: 0, per_page: 0, }; await Actions.getGroups(groupParams)(store.dispatch, store.getState); const state = store.getState(); const groups = state.entities.groups.groups; expect(groups).toBeTruthy(); expect((response1 as any).length).toEqual(groups.length); for (const id of Object.keys(groups)) { const index = Object.keys(groups).indexOf(id); expect(JSON.stringify(groups[id]) === JSON.stringify(response1.groups[index])).toBeTruthy(); } }); it('getAllGroupsAssociatedToTeam', async () => { const teamID = '5rgoajywb3nfbdtyafbod47ryb'; const response = { groups: [ { id: 'xh585kyz3tn55q6ipfo57btwnc', name: 'abc', display_name: 'abc', description: '', source: 'ldap', remote_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: false, }, { id: 'tnd8zod9f3fdtqosxjmhwucbth', name: 'software-engineering', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, allow_reference: false, }, { id: 'qhdp6g7aubbpiyja7c4sgpe7tc', name: 'qa', display_name: 'qa', description: '', source: 'ldap', remote_id: 'qa', create_at: 1553808971548, update_at: 1553808971548, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: false, }, ], total_group_count: 3, }; nock(Client4.getBaseRoute()). get(`/teams/${teamID}/groups?paginate=false&filter_allow_reference=false&include_member_count=true`). reply(200, response); await Actions.getAllGroupsAssociatedToTeam(teamID, false, true)(store.dispatch, store.getState); const state = store.getState(); const groupIDs = state.entities.teams.groupsAssociatedToTeam[teamID].ids; expect(groupIDs.length).toEqual(response.groups.length); groupIDs.forEach((id: string) => { expect(response.groups.map((group) => group.id).includes(id)).toBeTruthy(); }); }); it('getGroupsAssociatedToTeam', async () => { const teamID = '5rgoajywb3nfbdtyafbod47ryb'; const response = { groups: [ { id: 'tnd8zod9f3fdtqosxjmhwucbth', name: 'software-engineering', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, allow_reference: true, }, { id: 'qhdp6g7aubbpiyja7c4sgpe7tc', name: 'qa', display_name: 'qa', description: '', source: 'ldap', remote_id: 'qa', create_at: 1553808971548, update_at: 1553808971548, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: false, }, ], total_group_count: 3, }; nock(Client4.getBaseRoute()). get(`/teams/${teamID}/groups?page=100&per_page=60&q=0&include_member_count=true&filter_allow_reference=false`). reply(200, response); await Actions.getGroupsAssociatedToTeam(teamID, '0', 100)(store.dispatch, store.getState); const state = store.getState(); const groupIDs = state.entities.teams.groupsAssociatedToTeam[teamID].ids; const expectedIDs = ['tnd8zod9f3fdtqosxjmhwucbth', 'qhdp6g7aubbpiyja7c4sgpe7tc']; expect(groupIDs.length).toEqual(expectedIDs.length); groupIDs.forEach((id: string) => { expect(expectedIDs.includes(id)).toBeTruthy(); expect(state.entities.groups.groups[id]).toBeTruthy(); }); const count = state.entities.teams.groupsAssociatedToTeam[teamID].totalCount; expect(count).toEqual(response.total_group_count); }); it('getGroupsNotAssociatedToTeam', async () => { const teamID = '5rgoajywb3nfbdtyafbod47ryb'; store = configureStore({ entities: { teams: { groupsAssociatedToTeam: { [teamID]: {ids: ['existing1', 'existing2']}, }, }, }, }); const response = [ { id: 'existing1', name: 'software-engineering', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, }, ]; nock(Client4.getBaseRoute()). get(`/groups?not_associated_to_team=${teamID}&page=100&per_page=60&q=0&include_member_count=true`). reply(200, response); await Actions.getGroupsNotAssociatedToTeam(teamID, '0', 100)(store.dispatch, store.getState); const state = store.getState(); const groupIDs = state.entities.teams.groupsAssociatedToTeam[teamID].ids; const expectedIDs = ['existing2'].concat(response.map((group) => group.id)); expect(groupIDs.length).toEqual(expectedIDs.length); groupIDs.forEach((id: string) => { expect(expectedIDs.includes(id)).toBeTruthy(); }); }); it('getAllGroupsAssociatedToChannel', async () => { const channelID = '5rgoajywb3nfbdtyafbod47ryb'; const response = { groups: [ { id: 'xh585kyz3tn55q6ipfo57btwnc', name: 'abc', display_name: 'abc', description: '', source: 'ldap', remote_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, has_syncables: false, member_count: 2, }, { id: 'tnd8zod9f3fdtqosxjmhwucbth', name: 'software-engineering', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, }, { id: 'qhdp6g7aubbpiyja7c4sgpe7tc', name: 'qa', display_name: 'qa', description: '', source: 'ldap', remote_id: 'qa', create_at: 1553808971548, update_at: 1553808971548, delete_at: 0, has_syncables: false, member_count: 2, }, ], total_group_count: 3, }; nock(Client4.getBaseRoute()). get(`/channels/${channelID}/groups?paginate=false&filter_allow_reference=false&include_member_count=true`). reply(200, response); await Actions.getAllGroupsAssociatedToChannel(channelID, false, true)(store.dispatch, store.getState); const state = store.getState(); const groupIDs = state.entities.channels.groupsAssociatedToChannel[channelID].ids; expect(groupIDs.length).toEqual(response.groups.length); groupIDs.forEach((id: string) => { expect(response.groups.map((group) => group.id).includes(id)).toBeTruthy(); }); }); it('getAllGroupsAssociatedToChannelsInTeam', async () => { const teamID = 'ge63nq31sbfy3duzq5f7yqn1kh'; const channelID1 = '5rgoajywb3nfbdtyafbod47ryb'; const response1 = { groups: { '5rgoajywb3nfbdtyafbod47ryb': [ { id: 'xh585kyz3tn55q6ipfo57btwnc', name: 'abc', display_name: 'abc', description: '', source: 'ldap', remote_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: true, }, { id: 'tnd8zod9f3fdtqosxjmhwucbth', name: 'abc', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, allow_reference: false, }, ], o3tdawqxot8kikzq8bk54zggbc: [ { id: 'qhdp6g7aubbpiyja7c4sgpe7tc', name: 'qa', display_name: 'qa', description: '', source: 'ldap', remote_id: 'qa', create_at: 1553808971548, update_at: 1553808971548, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: false, }, ], }, total_group_count: 3, }; const response2 = { groups: { '5rgoajywb3nfbdtyafbod47ryb': [ { id: 'xh585kyz3tn55q6ipfo57btwnc', name: 'abc', display_name: 'abc', description: '', source: 'ldap', remote_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: true, }, ], }, total_group_count: 1, }; nock(Client4.getBaseRoute()). get(`/teams/${teamID}/groups_by_channels?paginate=false&filter_allow_reference=false`). reply(200, response1); nock(Client4.getBaseRoute()). get(`/teams/${teamID}/groups_by_channels?paginate=false&filter_allow_reference=true`). reply(200, response2); await Actions.getAllGroupsAssociatedToChannelsInTeam(teamID, false)(store.dispatch, store.getState); let state = store.getState(); let groupIDs = state.entities.channels.groupsAssociatedToChannel[channelID1].ids; expect(groupIDs.length).toEqual(response1.groups[channelID1].length); groupIDs.forEach((id: string) => { expect(response1.groups[channelID1].map((group) => group.id).includes(id)).toBeTruthy(); }); await Actions.getAllGroupsAssociatedToChannelsInTeam(teamID, true)(store.dispatch, store.getState); state = store.getState(); groupIDs = state.entities.channels.groupsAssociatedToChannel[channelID1].ids; expect(groupIDs.length).toEqual(response2.groups[channelID1].length); groupIDs.forEach((id: string) => { expect(response2.groups[channelID1].map((group) => group.id).includes(id)).toBeTruthy(); }); }); it('getGroupsAssociatedToChannel', async () => { const channelID = '5rgoajywb3nfbdtyafbod47ryb'; const response = { groups: [ { id: 'tnd8zod9f3fdtqosxjmhwucbth', name: 'software-engineering', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, allow_reference: false, }, { id: 'qhdp6g7aubbpiyja7c4sgpe7tc', name: 'qa', display_name: 'qa', description: '', source: 'ldap', remote_id: 'qa', create_at: 1553808971548, update_at: 1553808971548, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: true, }, ], total_group_count: 3, }; nock(Client4.getBaseRoute()). get(`/channels/${channelID}/groups?page=100&per_page=60&q=0&include_member_count=true&filter_allow_reference=false`). reply(200, response); await Actions.getGroupsAssociatedToChannel(channelID, '0', 100)(store.dispatch, store.getState); const state = store.getState(); const groupIDs = state.entities.channels.groupsAssociatedToChannel[channelID].ids; const expectedIDs = ['tnd8zod9f3fdtqosxjmhwucbth', 'qhdp6g7aubbpiyja7c4sgpe7tc']; expect(groupIDs.length).toEqual(expectedIDs.length); groupIDs.forEach((id: string) => { expect(expectedIDs.includes(id)).toBeTruthy(); expect(state.entities.groups.groups[id]).toBeTruthy(); }); const count = state.entities.channels.groupsAssociatedToChannel[channelID].totalCount; expect(count).toEqual(response.total_group_count); }); it('getGroupsNotAssociatedToChannel', async () => { const channelID = '5rgoajywb3nfbdtyafbod47ryb'; store = configureStore({ entities: { channels: { groupsAssociatedToChannel: { [channelID]: {ids: ['existing1', 'existing2']}, }, }, }, }); const response = [ { id: 'existing1', name: 'software-engineering', display_name: 'software engineering', description: '', source: 'ldap', remote_id: 'engineering', create_at: 1553808971099, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, }, ]; nock(Client4.getBaseRoute()). get(`/groups?not_associated_to_channel=${channelID}&page=100&per_page=60&q=0&include_member_count=true`). reply(200, response); await Actions.getGroupsNotAssociatedToChannel(channelID, '0', 100)(store.dispatch, store.getState); const state = store.getState(); const groupIDs = state.entities.channels.groupsAssociatedToChannel[channelID].ids; const expectedIDs = ['existing2'].concat(response.map((group) => group.id)); expect(groupIDs.length).toEqual(expectedIDs.length); groupIDs.forEach((id: string) => { expect(expectedIDs.includes(id)).toBeTruthy(); }); }); it('patchGroupSyncable', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const teamID = 'ge63nq31sbfy3duzq5f7yqn1kh'; const channelID = 'o3tdawqxot8kikzq8bk54zggbc'; const groupSyncablePatch = { auto_add: true, scheme_admin: true, }; const groupTeamResponse = { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, scheme_admin: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const groupChannelResponse = { channel_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, scheme_admin: true, create_at: 1542644105041, delete_at: 0, update_at: 1542662607342, }; nock(Client4.getBaseRoute()). put(`/groups/${groupID}/teams/${teamID}/patch`). reply(200, groupTeamResponse); nock(Client4.getBaseRoute()). put(`/groups/${groupID}/channels/${channelID}/patch`). reply(200, groupChannelResponse); await Actions.patchGroupSyncable(groupID, teamID, SyncableType.Team, groupSyncablePatch)(store.dispatch, store.getState); await Actions.patchGroupSyncable(groupID, channelID, SyncableType.Channel, groupSyncablePatch)(store.dispatch, store.getState); const state = store.getState(); const groupSyncables = state.entities.groups.syncables[groupID]; expect(groupSyncables).toBeTruthy(); expect(groupSyncables.teams[0].auto_add === groupSyncablePatch.auto_add).toBeTruthy(); expect(groupSyncables.channels[0].auto_add === groupSyncablePatch.auto_add).toBeTruthy(); expect(groupSyncables.teams[0].scheme_admin === groupSyncablePatch.scheme_admin).toBeTruthy(); expect(groupSyncables.channels[0].scheme_admin === groupSyncablePatch.scheme_admin).toBeTruthy(); }); it('patchGroup', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const groupPatch = { allow_reference: true, }; const response = { id: '5rgoajywb3nfbdtyafbod47rya', name: 'Test-Group-0', display_name: 'Test Group 0', description: '', type: 'ldap', remote_id: '\\eb\\80\\94\\cd\\d4\\32\\7c\\45\\87\\79\\1b\\fe\\45\\d9\\ac\\7b', create_at: 1542399032816, update_at: 1542399032816, delete_at: 0, has_syncables: false, allow_reference: true, }; nock(Client4.getBaseRoute()). put(`/groups/${groupID}/patch`). reply(200, response); await Actions.patchGroup(groupID, groupPatch)(store.dispatch, store.getState); let state = store.getState(); let groups = state.entities.groups.groups; expect(groups).toBeTruthy(); expect(groups[groupID]).toBeTruthy(); expect(groups[groupID].allow_reference === groupPatch.allow_reference).toBeTruthy(); expect(JSON.stringify(response) === JSON.stringify(groups[groupID])).toBeTruthy(); //with allow_reference=false groupPatch.allow_reference = false; response.allow_reference = false; nock(Client4.getBaseRoute()). put(`/groups/${groupID}/patch`). reply(200, response); await Actions.patchGroup(groupID, groupPatch)(store.dispatch, store.getState); state = store.getState(); groups = state.entities.groups.groups; expect(groups).toBeTruthy(); expect(groups[groupID]).toBeTruthy(); expect(groups[groupID].allow_reference === groupPatch.allow_reference).toBeTruthy(); expect(JSON.stringify(response) === JSON.stringify(groups[groupID])).toBeTruthy(); //with name="newname" (groupPatch as any).name = 'newname'; response.name = 'newname'; nock(Client4.getBaseRoute()). put(`/groups/${groupID}/patch`). reply(200, response); await Actions.patchGroup(groupID, groupPatch)(store.dispatch, store.getState); state = store.getState(); groups = state.entities.groups.groups; expect(groups).toBeTruthy(); expect(groups[groupID]).toBeTruthy(); expect(groups[groupID].name === (groupPatch as any).name).toBeTruthy(); expect(JSON.stringify(response) === JSON.stringify(groups[groupID])).toBeTruthy(); }); it('getGroupStats', async () => { const groupID = '5rgoajywb3nfbdtyafbod47rya'; const response = { group_id: '5rgoajywb3nfbdtyafbod47rya', total_member_count: 55, }; nock(Client4.getBaseRoute()). get(`/groups/${groupID}/stats`). reply(200, response); await Actions.getGroupStats(groupID)(store.dispatch, store.getState); const state = store.getState(); const stats = state.entities.groups.stats; expect(stats).toBeTruthy(); expect(stats[groupID]).toBeTruthy(); expect(JSON.stringify(response) === JSON.stringify(stats[groupID])).toBeTruthy(); }); });
3,953
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/helpers.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {ClientError} from '@mattermost/client'; import {UserTypes} from 'mattermost-redux/action_types'; import {forceLogoutIfNecessary} from 'mattermost-redux/actions/helpers'; import {Client4} from 'mattermost-redux/client'; import configureStore, {mockDispatch} from '../../test/test_store'; describe('Actions.Helpers', () => { describe('forceLogoutIfNecessary', () => { const token = 'token'; beforeEach(() => { Client4.setToken(token); }); it('should do nothing when passed a client error', async () => { const store = configureStore({ entities: { users: { currentUserId: 'user', }, }, }); const dispatch = mockDispatch(store.dispatch); const error = new ClientError(Client4.getUrl(), { message: 'no internet connection', url: '/api/v4/foo/bar', }); forceLogoutIfNecessary(error, dispatch as any, store.getState); expect(Client4.token).toEqual(token); expect(dispatch.actions).toEqual([]); }); it('should do nothing when passed a non-401 server error', async () => { const store = configureStore({ entities: { users: { currentUserId: 'user', }, }, }); const dispatch = mockDispatch(store.dispatch); const error = new ClientError(Client4.getUrl(), { message: 'Failed to do something', status_code: 403, url: '/api/v4/foo/bar', }); forceLogoutIfNecessary(error, dispatch as any, store.getState); expect(Client4.token).toEqual(token); expect(dispatch.actions).toEqual([]); }); it('should trigger logout when passed a 401 server error', async () => { const store = configureStore({ entities: { users: { currentUserId: 'user', }, }, }); const dispatch = mockDispatch(store.dispatch); const error = new ClientError(Client4.getUrl(), { message: 'Failed to do something', status_code: 401, url: '/api/v4/foo/bar', }); forceLogoutIfNecessary(error, dispatch as any, store.getState); expect(Client4.token).not.toEqual(token); expect(dispatch.actions).toEqual([{type: UserTypes.LOGOUT_SUCCESS, data: {}}]); }); it('should do nothing when failing to log in', async () => { const store = configureStore({ entities: { users: { currentUserId: 'user', }, }, }); const dispatch = mockDispatch(store.dispatch); const error = new ClientError(Client4.getUrl(), { message: 'Failed to do something', status_code: 401, url: '/api/v4/login', }); forceLogoutIfNecessary(error, dispatch as any, store.getState); expect(Client4.token).toEqual(token); expect(dispatch.actions).toEqual([]); }); it('should do nothing when not logged in', async () => { const store = configureStore({ entities: { users: { currentUserId: '', }, }, }); const dispatch = mockDispatch(store.dispatch); const error = new ClientError(Client4.getUrl(), { message: 'Failed to do something', status_code: 401, url: '/api/v4/foo/bar', }); forceLogoutIfNecessary(error, dispatch as any, store.getState); expect(Client4.token).toEqual(token); expect(dispatch.actions).toEqual([]); }); }); });
3,956
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/integrations.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import type {DialogSubmission, IncomingWebhook, OutgoingWebhook} from '@mattermost/types/integrations'; import * as Actions from 'mattermost-redux/actions/integrations'; import * as TeamsActions from 'mattermost-redux/actions/teams'; import {Client4} from 'mattermost-redux/client'; import type {ActionResult} from 'mattermost-redux/types/actions'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.Integrations', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore(); }); afterAll(() => { TestHelper.tearDown(); }); it('createIncomingHook', async () => { nock(Client4.getBaseRoute()). post('/hooks/incoming'). reply(201, TestHelper.testIncomingHook()); const {data: created} = await Actions.createIncomingHook( { channel_id: TestHelper.basicChannel!.id, display_name: 'test', description: 'test', } as IncomingWebhook, )(store.dispatch, store.getState) as ActionResult; const state = store.getState(); const hooks = state.entities.integrations.incomingHooks; expect(hooks).toBeTruthy(); expect(hooks[created.id]).toBeTruthy(); }); it('getIncomingWebhook', async () => { nock(Client4.getBaseRoute()). post('/hooks/incoming'). reply(201, TestHelper.testIncomingHook()); const {data: created} = await Actions.createIncomingHook( { channel_id: TestHelper.basicChannel!.id, display_name: 'test', description: 'test', } as IncomingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/hooks/incoming/${created.id}`). reply(200, created); await Actions.getIncomingHook(created.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.incomingHooks; expect(hooks).toBeTruthy(); expect(hooks[created.id]).toBeTruthy(); }); it('getIncomingWebhooks', async () => { nock(Client4.getBaseRoute()). post('/hooks/incoming'). reply(201, TestHelper.testIncomingHook()); const {data: created} = await Actions.createIncomingHook( { channel_id: TestHelper.basicChannel!.id, display_name: 'test', description: 'test', } as IncomingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get('/hooks/incoming'). query(true). reply(200, [created]); await Actions.getIncomingHooks(TestHelper.basicTeam!.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.incomingHooks; expect(hooks).toBeTruthy(); expect(hooks[created.id]).toBeTruthy(); }); it('removeIncomingHook', async () => { nock(Client4.getBaseRoute()). post('/hooks/incoming'). reply(201, TestHelper.testIncomingHook()); const {data: created} = await Actions.createIncomingHook( { channel_id: TestHelper.basicChannel!.id, display_name: 'test', description: 'test', } as IncomingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). delete(`/hooks/incoming/${created.id}`). reply(200, OK_RESPONSE); await Actions.removeIncomingHook(created.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.incomingHooks; expect(!hooks[created.id]).toBeTruthy(); }); it('updateIncomingHook', async () => { nock(Client4.getBaseRoute()). post('/hooks/incoming'). reply(201, TestHelper.testIncomingHook()); const {data: created} = await Actions.createIncomingHook( { channel_id: TestHelper.basicChannel!.id, display_name: 'test', description: 'test', } as IncomingWebhook, )(store.dispatch, store.getState) as ActionResult; const updated = {...created}; updated.display_name = 'test2'; nock(Client4.getBaseRoute()). put(`/hooks/incoming/${created.id}`). reply(200, updated); await Actions.updateIncomingHook(updated)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.incomingHooks; expect(hooks[created.id]).toBeTruthy(); expect(hooks[created.id].display_name === updated.display_name).toBeTruthy(); }); it('createOutgoingHook', async () => { nock(Client4.getBaseRoute()). post('/hooks/outgoing'). reply(201, TestHelper.testOutgoingHook()); const {data: created} = await Actions.createOutgoingHook( { channel_id: TestHelper.basicChannel!.id, team_id: TestHelper.basicTeam!.id, display_name: 'test', trigger_words: [TestHelper.generateId()], callback_urls: ['http://localhost/notarealendpoint'], } as OutgoingWebhook, )(store.dispatch, store.getState) as ActionResult; const state = store.getState(); const hooks = state.entities.integrations.outgoingHooks; expect(hooks).toBeTruthy(); expect(hooks[created.id]).toBeTruthy(); }); it('getOutgoingWebhook', async () => { nock(Client4.getBaseRoute()). post('/hooks/outgoing'). reply(201, TestHelper.testOutgoingHook()); const {data: created} = await Actions.createOutgoingHook( { channel_id: TestHelper.basicChannel!.id, team_id: TestHelper.basicTeam!.id, display_name: 'test', trigger_words: [TestHelper.generateId()], callback_urls: ['http://localhost/notarealendpoint'], } as OutgoingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/hooks/outgoing/${created.id}`). reply(200, TestHelper.testOutgoingHook()); await Actions.getOutgoingHook(created.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.outgoingHooks; expect(hooks).toBeTruthy(); expect(hooks[created.id]).toBeTruthy(); }); it('getOutgoingWebhooks', async () => { nock(Client4.getBaseRoute()). post('/hooks/outgoing'). reply(201, TestHelper.testOutgoingHook()); const {data: created} = await Actions.createOutgoingHook( { channel_id: TestHelper.basicChannel!.id, team_id: TestHelper.basicTeam!.id, display_name: 'test', trigger_words: [TestHelper.generateId()], callback_urls: ['http://localhost/notarealendpoint'], } as OutgoingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get('/hooks/outgoing'). query(true). reply(200, [TestHelper.testOutgoingHook()]); await Actions.getOutgoingHooks(TestHelper.basicChannel!.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.outgoingHooks; expect(hooks).toBeTruthy(); expect(hooks[created.id]).toBeTruthy(); }); it('removeOutgoingHook', async () => { nock(Client4.getBaseRoute()). post('/hooks/outgoing'). reply(201, TestHelper.testOutgoingHook()); const {data: created} = await Actions.createOutgoingHook( { channel_id: TestHelper.basicChannel!.id, team_id: TestHelper.basicTeam!.id, display_name: 'test', trigger_words: [TestHelper.generateId()], callback_urls: ['http://localhost/notarealendpoint'], } as OutgoingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). delete(`/hooks/outgoing/${created.id}`). reply(200, OK_RESPONSE); await Actions.removeOutgoingHook(created.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.outgoingHooks; expect(!hooks[created.id]).toBeTruthy(); }); it('updateOutgoingHook', async () => { nock(Client4.getBaseRoute()). post('/hooks/outgoing'). reply(201, TestHelper.testOutgoingHook()); const {data: created} = await Actions.createOutgoingHook( { channel_id: TestHelper.basicChannel!.id, team_id: TestHelper.basicTeam!.id, display_name: 'test', trigger_words: [TestHelper.generateId()], callback_urls: ['http://localhost/notarealendpoint'], } as OutgoingWebhook, )(store.dispatch, store.getState) as ActionResult; const updated = {...created}; updated.display_name = 'test2'; nock(Client4.getBaseRoute()). put(`/hooks/outgoing/${created.id}`). reply(200, updated); await Actions.updateOutgoingHook(updated)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.outgoingHooks; expect(hooks[created.id]).toBeTruthy(); expect(hooks[created.id].display_name === updated.display_name).toBeTruthy(); }); it('regenOutgoingHookToken', async () => { nock(Client4.getBaseRoute()). post('/hooks/outgoing'). reply(201, TestHelper.testOutgoingHook()); const {data: created} = await Actions.createOutgoingHook( { channel_id: TestHelper.basicChannel!.id, team_id: TestHelper.basicTeam!.id, display_name: 'test', trigger_words: [TestHelper.generateId()], callback_urls: ['http://localhost/notarealendpoint'], } as OutgoingWebhook, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). post(`/hooks/outgoing/${created.id}/regen_token`). reply(200, {...created, token: TestHelper.generateId()}); await Actions.regenOutgoingHookToken(created.id)(store.dispatch, store.getState); const state = store.getState(); const hooks = state.entities.integrations.outgoingHooks; expect(hooks[created.id]).toBeTruthy(); expect(hooks[created.id].token !== created.token).toBeTruthy(); }); it('getCommands', async () => { const noTeamCommands = store.getState().entities.integrations.commands; const noSystemCommands = store.getState().entities.integrations.systemCommands; expect(Object.keys({...noTeamCommands, ...noSystemCommands}).length).toEqual(0); nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const teamCommand = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...teamCommand, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: created} = await Actions.addCommand( teamCommand, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get('/commands'). query(true). reply(200, [created, { trigger: 'system-command', }]); await Actions.getCommands( team.id, )(store.dispatch, store.getState); const teamCommands = store.getState().entities.integrations.commands; const executableCommands = store.getState().entities.integrations.executableCommands; expect(Object.keys({...teamCommands, ...executableCommands}).length).toBeTruthy(); }); it('getAutocompleteCommands', async () => { const noTeamCommands = store.getState().entities.integrations.commands; const noSystemCommands = store.getState().entities.integrations.systemCommands; expect(Object.keys({...noTeamCommands, ...noSystemCommands}).length).toEqual(0); nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const teamCommandWithAutocomplete = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...teamCommandWithAutocomplete, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: createdWithAutocomplete} = await Actions.addCommand( teamCommandWithAutocomplete, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/teams/${team.id}/commands/autocomplete`). query(true). reply(200, [createdWithAutocomplete, { trigger: 'system-command', }]); await Actions.getAutocompleteCommands( team.id, )(store.dispatch, store.getState); const teamCommands = store.getState().entities.integrations.commands; const systemCommands = store.getState().entities.integrations.systemCommands; expect(Object.keys({...teamCommands, ...systemCommands}).length).toEqual(2); }); it('getCustomTeamCommands', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get('/commands'). query(true). reply(200, []); await Actions.getCustomTeamCommands( team.id, )(store.dispatch, store.getState); const noCommands = store.getState().entities.integrations.commands; expect(Object.keys(noCommands).length).toEqual(0); const command = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...command, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: created} = await Actions.addCommand( command, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get('/commands'). query(true). reply(200, []); await Actions.getCustomTeamCommands( team.id, )(store.dispatch, store.getState); const {commands} = store.getState().entities.integrations; expect(commands[created.id]).toBeTruthy(); expect(Object.keys(commands).length).toEqual(1); const actual = commands[created.id]; const expected = created; expect(JSON.stringify(actual)).toEqual(JSON.stringify(expected)); }); it('executeCommand', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const args = { channel_id: TestHelper.basicChannel!.id, team_id: team.id, }; nock(Client4.getBaseRoute()). post('/commands/execute'). reply(200, []); await Actions.executeCommand('/echo message 5', args); }); it('addCommand', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const expected = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...expected, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: created} = await Actions.addCommand(expected)(store.dispatch, store.getState) as ActionResult; const {commands} = store.getState().entities.integrations; expect(commands[created.id]).toBeTruthy(); const actual = commands[created.id]; expect(actual.token).toBeTruthy(); expect(actual.create_at).toEqual(actual.update_at); expect(actual.delete_at).toEqual(0); expect(actual.creator_id).toBeTruthy(); expect(actual.team_id).toEqual(team.id); expect(actual.trigger).toEqual(expected.trigger); expect(actual.method).toEqual(expected.method); expect(actual.username).toEqual(expected.username); expect(actual.icon_url).toEqual(expected.icon_url); expect(actual.auto_complete).toEqual(expected.auto_complete); expect(actual.auto_complete_desc).toEqual(expected.auto_complete_desc); expect(actual.auto_complete_hint).toEqual(expected.auto_complete_hint); expect(actual.display_name).toEqual(expected.display_name); expect(actual.description).toEqual(expected.description); expect(actual.url).toEqual(expected.url); }); it('regenCommandToken', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const command = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...command, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: created} = await Actions.addCommand( command, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). put(`/commands/${created.id}/regen_token`). reply(200, {...created, token: TestHelper.generateId()}); await Actions.regenCommandToken( created.id, )(store.dispatch, store.getState); const {commands} = store.getState().entities.integrations; expect(commands[created.id]).toBeTruthy(); const updated = commands[created.id]; expect(updated.id).toEqual(created.id); expect(updated.token).not.toEqual(created.token); expect(updated.create_at).toEqual(created.create_at); expect(updated.update_at).toEqual(created.update_at); expect(updated.delete_at).toEqual(created.delete_at); expect(updated.creator_id).toEqual(created.creator_id); expect(updated.team_id).toEqual(created.team_id); expect(updated.trigger).toEqual(created.trigger); expect(updated.method).toEqual(created.method); expect(updated.username).toEqual(created.username); expect(updated.icon_url).toEqual(created.icon_url); expect(updated.auto_complete).toEqual(created.auto_complete); expect(updated.auto_complete_desc).toEqual(created.auto_complete_desc); expect(updated.auto_complete_hint).toEqual(created.auto_complete_hint); expect(updated.display_name).toEqual(created.display_name); expect(updated.description).toEqual(created.description); expect(updated.url).toEqual(created.url); }); it('editCommand', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const command = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...command, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: created} = await Actions.addCommand( command, )(store.dispatch, store.getState) as ActionResult; const expected = Object.assign({}, created); expected.trigger = 'modified'; expected.method = 'G'; expected.username = 'modified'; expected.auto_complete = false; nock(Client4.getBaseRoute()). put(`/commands/${expected.id}`). reply(200, {...expected, update_at: 123}); await Actions.editCommand( expected, )(store.dispatch, store.getState); const {commands} = store.getState().entities.integrations; expect(commands[created.id]).toBeTruthy(); const actual = commands[created.id]; expect(actual.update_at).not.toEqual(expected.update_at); expected.update_at = actual.update_at; expect(JSON.stringify(actual)).toEqual(JSON.stringify(expected)); }); it('deleteCommand', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const {data: team} = await TeamsActions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState) as ActionResult; const command = TestHelper.testCommand(team.id); nock(Client4.getBaseRoute()). post('/commands'). reply(201, {...command, token: TestHelper.generateId(), id: TestHelper.generateId()}); const {data: created} = await Actions.addCommand( command, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). delete(`/commands/${created.id}`). reply(200, OK_RESPONSE); await Actions.deleteCommand( created.id, )(store.dispatch, store.getState); const {commands} = store.getState().entities.integrations; expect(!commands[created.id]).toBeTruthy(); }); it('addOAuthApp', async () => { nock(Client4.getBaseRoute()). post('/oauth/apps'). reply(201, TestHelper.fakeOAuthAppWithId()); const {data: created} = await Actions.addOAuthApp(TestHelper.fakeOAuthApp())(store.dispatch, store.getState) as ActionResult; const {oauthApps} = store.getState().entities.integrations; expect(oauthApps[created.id]).toBeTruthy(); }); it('getOAuthApp', async () => { nock(Client4.getBaseRoute()). post('/oauth/apps'). reply(201, TestHelper.fakeOAuthAppWithId()); const {data: created} = await Actions.addOAuthApp(TestHelper.fakeOAuthApp())(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/oauth/apps/${created.id}`). reply(200, created); await Actions.getOAuthApp(created.id)(store.dispatch, store.getState); const {oauthApps} = store.getState().entities.integrations; expect(oauthApps[created.id]).toBeTruthy(); }); it('editOAuthApp', async () => { nock(Client4.getBaseRoute()). post('/oauth/apps'). reply(201, TestHelper.fakeOAuthAppWithId()); const {data: created} = await Actions.addOAuthApp(TestHelper.fakeOAuthApp())(store.dispatch, store.getState) as ActionResult; const expected = Object.assign({}, created); expected.name = 'modified'; expected.description = 'modified'; expected.homepage = 'https://modified.com'; expected.icon_url = 'https://modified.com/icon'; expected.callback_urls = ['https://modified.com/callback1', 'https://modified.com/callback2']; expected.is_trusted = true; const nockReply = Object.assign({}, expected); nockReply.update_at += 1; nock(Client4.getBaseRoute()). put(`/oauth/apps/${created.id}`).reply(200, nockReply); await Actions.editOAuthApp(expected)(store.dispatch, store.getState); const {oauthApps} = store.getState().entities.integrations; expect(oauthApps[created.id]).toBeTruthy(); const actual = oauthApps[created.id]; expect(actual.update_at).not.toEqual(expected.update_at); const actualWithoutUpdateAt = {...actual}; delete actualWithoutUpdateAt.update_at; delete expected.update_at; expect(JSON.stringify(actualWithoutUpdateAt)).toEqual(JSON.stringify(expected)); }); it('getOAuthApps', async () => { nock(Client4.getBaseRoute()). post('/oauth/apps'). reply(201, TestHelper.fakeOAuthAppWithId()); const {data: created} = await Actions.addOAuthApp(TestHelper.fakeOAuthApp())(store.dispatch, store.getState) as ActionResult; const user = TestHelper.basicUser; nock(Client4.getBaseRoute()). get(`/users/${user!.id}/oauth/apps/authorized`). reply(200, [created]); await Actions.getAuthorizedOAuthApps()(store.dispatch, store.getState); const {oauthApps} = store.getState().entities.integrations; expect(oauthApps).toBeTruthy(); }); it('deleteOAuthApp', async () => { nock(Client4.getBaseRoute()). post('/oauth/apps'). reply(201, TestHelper.fakeOAuthAppWithId()); const {data: created} = await Actions.addOAuthApp(TestHelper.fakeOAuthApp())(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). delete(`/oauth/apps/${created.id}`). reply(200, OK_RESPONSE); await Actions.deleteOAuthApp(created.id)(store.dispatch, store.getState); const {oauthApps} = store.getState().entities.integrations; expect(!oauthApps[created.id]).toBeTruthy(); }); it('regenOAuthAppSecret', async () => { nock(Client4.getBaseRoute()). post('/oauth/apps'). reply(201, TestHelper.fakeOAuthAppWithId()); const {data: created} = await Actions.addOAuthApp(TestHelper.fakeOAuthApp())(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). post(`/oauth/apps/${created.id}/regen_secret`). reply(200, {...created, client_secret: TestHelper.generateId()}); await Actions.regenOAuthAppSecret(created.id)(store.dispatch, store.getState); const {oauthApps} = store.getState().entities.integrations; expect(oauthApps[created.id].client_secret !== created.client_secret).toBeTruthy(); }); it('submitInteractiveDialog', async () => { nock(Client4.getBaseRoute()). post('/actions/dialogs/submit'). reply(200, {errors: {name: 'some error'}}); const submit: DialogSubmission = { url: 'https://mattermost.com', callback_id: '123', state: '123', channel_id: TestHelper.generateId(), team_id: TestHelper.generateId(), submission: {name: 'value'}, cancelled: false, user_id: '', }; const {data} = await store.dispatch(Actions.submitInteractiveDialog(submit)); expect(data.errors).toBeTruthy(); expect(data.errors.name).toEqual('some error'); }); });
3,958
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/jobs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import type {Job} from '@mattermost/types/jobs'; import * as Actions from 'mattermost-redux/actions/jobs'; import {Client4} from 'mattermost-redux/client'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.Jobs', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore(); }); afterAll(() => { TestHelper.tearDown(); }); it('createJob', async () => { const job = { type: 'data_retention', } as Job; nock(Client4.getBaseRoute()). post('/jobs'). reply(201, { id: 'six4h67ja7ntdkek6g13dp3wka', create_at: 1491399241953, type: 'data_retention', status: 'pending', data: {}, }); await Actions.createJob(job)(store.dispatch, store.getState); const state = store.getState(); const jobs = state.entities.jobs.jobs; expect(jobs.six4h67ja7ntdkek6g13dp3wka).toBeTruthy(); }); it('getJob', async () => { nock(Client4.getBaseRoute()). get('/jobs/six4h67ja7ntdkek6g13dp3wka'). reply(200, { id: 'six4h67ja7ntdkek6g13dp3wka', create_at: 1491399241953, type: 'data_retention', status: 'pending', data: {}, }); await Actions.getJob('six4h67ja7ntdkek6g13dp3wka')(store.dispatch, store.getState); const state = store.getState(); const jobs = state.entities.jobs.jobs; expect(jobs.six4h67ja7ntdkek6g13dp3wka).toBeTruthy(); }); it('cancelJob', async () => { nock(Client4.getBaseRoute()). post('/jobs/six4h67ja7ntdkek6g13dp3wka/cancel'). reply(200, OK_RESPONSE); await Actions.cancelJob('six4h67ja7ntdkek6g13dp3wka')(store.dispatch, store.getState); const state = store.getState(); const jobs = state.entities.jobs.jobs; expect(!jobs.six4h67ja7ntdkek6g13dp3wka).toBeTruthy(); }); it('getJobs', async () => { nock(Client4.getBaseRoute()). get('/jobs'). query(true). reply(200, [{ id: 'six4h67ja7ntdkek6g13dp3wka', create_at: 1491399241953, type: 'data_retention', status: 'pending', data: {}, }]); await Actions.getJobs()(store.dispatch, store.getState); const state = store.getState(); const jobs = state.entities.jobs.jobs; expect(jobs.six4h67ja7ntdkek6g13dp3wka).toBeTruthy(); }); it('getJobsByType', async () => { nock(Client4.getBaseRoute()). get('/jobs/type/data_retention'). query(true). reply(200, [{ id: 'six4h67ja7ntdkek6g13dp3wka', create_at: 1491399241953, type: 'data_retention', status: 'pending', data: {}, }]); await Actions.getJobsByType('data_retention')(store.dispatch, store.getState); const state = store.getState(); const jobs = state.entities.jobs.jobs; expect(jobs.six4h67ja7ntdkek6g13dp3wka).toBeTruthy(); const jobsByType = state.entities.jobs.jobsByTypeList; expect(jobsByType.data_retention).toBeTruthy(); expect(jobsByType.data_retention.length === 1).toBeTruthy(); }); });
3,960
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/posts.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import fs from 'fs'; import nock from 'nock'; import type {Post, PostList} from '@mattermost/types/posts'; import type {GlobalState} from '@mattermost/types/store'; import {PostTypes, UserTypes} from 'mattermost-redux/action_types'; import {getChannelStats} from 'mattermost-redux/actions/channels'; import {createCustomEmoji} from 'mattermost-redux/actions/emojis'; import * as Actions from 'mattermost-redux/actions/posts'; import {loadMe} from 'mattermost-redux/actions/users'; import {Client4} from 'mattermost-redux/client'; import type {ActionResult, GetStateFunc} from 'mattermost-redux/types/actions'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; import {Preferences, Posts, RequestStatus} from '../constants'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.Posts', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore({ entities: { general: { config: { CollapsedThreads: 'always_on', EnableJoinLeaveMessageByDefault: 'true', }, }, }, }); }); afterAll(() => { TestHelper.tearDown(); }); it('createPost', async () => { const channelId = TestHelper.basicChannel!.id; const post = TestHelper.fakePost(channelId); nock(Client4.getBaseRoute()). post('/posts'). reply(201, {...post, id: TestHelper.generateId()}); await Actions.createPost(post)(store.dispatch, store.getState); const state: GlobalState = store.getState(); const createRequest = state.requests.posts.createPost; if (createRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(createRequest.error)); } const {posts, postsInChannel} = state.entities.posts; expect(posts).toBeTruthy(); expect(postsInChannel).toBeTruthy(); let found = false; for (const storedPost of Object.values(posts)) { if (storedPost.message === post.message) { found = true; break; } } // failed to find new post in posts expect(found).toBeTruthy(); // postsInChannel[channelId] should not exist as create post should not add entry to postsInChannel when it did not exist before // postIds in channel do not exist expect(!postsInChannel[channelId]).toBeTruthy(); }); it('maintain postReplies', async () => { const channelId = TestHelper.basicChannel!.id; const post = TestHelper.fakePost(channelId); const postId = TestHelper.generateId(); nock(Client4.getBaseRoute()). post('/posts'). reply(201, {...post, id: postId}); await Actions.createPostImmediately(post)(store.dispatch, store.getState); const post2 = TestHelper.fakePostWithId(channelId); post2.root_id = postId; nock(Client4.getBaseRoute()). post('/posts'). reply(201, post2); await Actions.createPostImmediately(post2)(store.dispatch, store.getState); expect(store.getState().entities.posts.postsReplies[postId]).toBe(1); nock(Client4.getBaseRoute()). delete(`/posts/${post2.id}`). reply(200, OK_RESPONSE); await Actions.deletePost(post2)(store.dispatch, store.getState); await Actions.removePost(post2)(store.dispatch, store.getState); expect(store.getState().entities.posts.postsReplies[postId]).toBe(0); }); it('resetCreatePostRequest', async () => { const channelId = TestHelper.basicChannel!.id; const post = TestHelper.fakePost(channelId); const createPostError = { message: 'Invalid RootId parameter', server_error_id: 'api.post.create_post.root_id.app_error', status_code: 400, url: 'http://localhost:8065/api/v4/posts', }; nock(Client4.getBaseRoute()). post('/posts'). reply(400, createPostError); await Actions.createPost(post)(store.dispatch, store.getState); await TestHelper.wait(50); let state = store.getState(); let createRequest = state.requests.posts.createPost; if (createRequest.status !== RequestStatus.FAILURE) { throw new Error(JSON.stringify(createRequest.error)); } expect(createRequest.status).toEqual(RequestStatus.FAILURE); expect(createRequest.error.message).toEqual(createPostError.message); expect(createRequest.error.status_code).toEqual(createPostError.status_code); store.dispatch(Actions.resetCreatePostRequest()); await TestHelper.wait(50); state = store.getState(); createRequest = state.requests.posts.createPost; if (createRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(createRequest.error)); } expect(createRequest.status).toEqual(RequestStatus.NOT_STARTED); expect(createRequest.error).toBe(null); }); it('createPost with file attachments', async () => { const channelId = TestHelper.basicChannel!.id; const post = TestHelper.fakePost(channelId); const files = TestHelper.fakeFiles(3); nock(Client4.getBaseRoute()). post('/posts'). reply(201, {...post, id: TestHelper.generateId(), file_ids: [files[0].id, files[1].id, files[2].id]}); await Actions.createPost( post, files, )(store.dispatch, store.getState); const state: GlobalState = store.getState(); const createRequest = state.requests.posts.createPost; if (createRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(createRequest.error)); } let newPost: Post; for (const storedPost of Object.values(state.entities.posts.posts)) { if (storedPost.message === post.message) { newPost = storedPost; break; } } // failed to find new post in posts expect(newPost!).toBeTruthy(); let found = true; for (const file of files) { if (!state.entities.files.files[file.id]) { found = false; break; } } // failed to find uploaded files in files expect(found).toBeTruthy(); const postIdForFiles = state.entities.files.fileIdsByPostId[newPost!.id]; // failed to find files for post id in files Ids by post id expect(postIdForFiles).toBeTruthy(); expect(postIdForFiles.length).toBe(files.length); }); it('editPost', async () => { const channelId = TestHelper.basicChannel!.id; nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(channelId)); const post = await Client4.createPost( TestHelper.fakePost(channelId), ); const message = post.message; post.message = `${message} (edited)`; nock(Client4.getBaseRoute()). put(`/posts/${post.id}/patch`). reply(200, post); await Actions.editPost( post, )(store.dispatch, store.getState); const state: GlobalState = store.getState(); const editRequest = state.requests.posts.editPost; const {posts} = state.entities.posts; if (editRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(editRequest.error)); } expect(posts).toBeTruthy(); expect(posts[post.id]).toBeTruthy(); expect( posts[post.id].message).toEqual( `${message} (edited)`, ); }); it('deletePost', async () => { const channelId = TestHelper.basicChannel!.id; nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(channelId)); await Actions.createPost(TestHelper.fakePost(channelId))(store.dispatch, store.getState); const initialPosts = store.getState().entities.posts; const postId = Object.keys(initialPosts.posts)[0]; nock(Client4.getBaseRoute()). delete(`/posts/${postId}`). reply(200, OK_RESPONSE); await Actions.deletePost(initialPosts.posts[postId])(store.dispatch, store.getState); const state: GlobalState = store.getState(); const {posts} = state.entities.posts; expect(posts).toBeTruthy(); expect(posts[postId]).toBeTruthy(); expect( posts[postId].state).toEqual( Posts.POST_DELETED, ); }); it('deletePostWithReaction', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const emojiName = '+1'; nock(Client4.getBaseRoute()). post('/reactions'). reply(201, {user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName, create_at: 1508168444721}); await Actions.addReaction(post1.id, emojiName)(store.dispatch, store.getState); let reactions = store.getState().entities.posts.reactions; expect(reactions).toBeTruthy(); expect(reactions[post1.id]).toBeTruthy(); expect(reactions[post1.id][TestHelper.basicUser!.id + '-' + emojiName]).toBeTruthy(); nock(Client4.getBaseRoute()). delete(`/posts/${post1.id}`). reply(200, OK_RESPONSE); await Actions.deletePost(post1)(store.dispatch, store.getState); reactions = store.getState().entities.posts.reactions; expect(reactions).toBeTruthy(); expect(!reactions[post1.id]).toBeTruthy(); }); it('removePost', async () => { const post1 = TestHelper.getPostMock({id: 'post1', channel_id: 'channel1', create_at: 1001, message: ''}); const post2 = TestHelper.getPostMock({id: 'post2', channel_id: 'channel1', create_at: 1002, message: '', is_pinned: true}); const post3 = TestHelper.getPostMock({id: 'post3', channel_id: 'channel1', root_id: 'post2', create_at: 1003, message: ''}); const post4 = TestHelper.getPostMock({id: 'post4', channel_id: 'channel1', root_id: 'post1', create_at: 1004, message: ''}); store = configureStore({ entities: { posts: { posts: { post1, post2, post3, post4, }, postsInChannel: { channel1: [ {order: ['post4', 'post3', 'post2', 'post1'], recent: false}, ], }, postsInThread: { post1: ['post4'], post2: ['post3'], }, }, channels: { stats: { channel1: { pinnedpost_count: 2, }, }, }, }, }); await store.dispatch(Actions.removePost(post2)); const state: GlobalState = store.getState(); const {stats} = state.entities.channels; const pinnedPostCount = stats.channel1.pinnedpost_count; expect(state.entities.posts.posts).toEqual({ post1, post4, }); expect(state.entities.posts.postsInChannel).toEqual({ channel1: [ {order: ['post4', 'post1'], recent: false}, ], }); expect(state.entities.posts.postsInThread).toEqual({ post1: ['post4'], }); expect(pinnedPostCount).toEqual(1); }); it('removePostWithReaction', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const emojiName = '+1'; nock(Client4.getBaseRoute()). post('/reactions'). reply(201, {user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName, create_at: 1508168444721}); await Actions.addReaction(post1.id, emojiName)(store.dispatch, store.getState); let reactions = store.getState().entities.posts.reactions; expect(reactions).toBeTruthy(); expect(reactions[post1.id]).toBeTruthy(); expect(reactions[post1.id][TestHelper.basicUser!.id + '-' + emojiName]).toBeTruthy(); await store.dispatch(Actions.removePost(post1)); reactions = store.getState().entities.posts.reactions; expect(reactions).toBeTruthy(); expect(!reactions[post1.id]).toBeTruthy(); }); it('getPostsUnread', async () => { const {dispatch, getState} = store; const channelId = TestHelper.basicChannel!.id; const post = TestHelper.fakePostWithId(channelId); const userId = getState().entities.users.currentUserId; const response = { posts: { [post.id]: post, }, order: [post.id], next_post_id: '', prev_post_id: '', }; nock(Client4.getUsersRoute()). get(`/${userId}/channels/${channelId}/posts/unread`). query(true). reply(200, response); await Actions.getPostsUnread(channelId)(dispatch, getState); const {posts} = getState().entities.posts; expect(posts[post.id]).toBeTruthy(); }); it('getPostsUnread should load recent posts when unreadScrollPosition is startFromNewest and unread posts are not the latestPosts', async () => { const mockStore = configureStore({ entities: { general: { config: { CollapsedThreads: 'always_on', }, }, preferences: { myPreferences: { 'advanced_settings--unread_scroll_position': { category: 'advanced_settings', name: 'unread_scroll_position', value: Preferences.UNREAD_SCROLL_POSITION_START_FROM_NEWEST, }, }, }, }, }); const {dispatch, getState} = mockStore; const userId = getState().entities.users.currentUserId; const channelId = TestHelper.basicChannel!.id; const post = TestHelper.fakePostWithId(channelId); const recentPost = TestHelper.fakePostWithId(channelId); const response = { posts: { [post.id]: post, }, order: [post.id], next_post_id: recentPost.id, prev_post_id: '', }; const responseWithRecentPosts = { posts: { [recentPost.id]: recentPost, }, order: [recentPost.id], next_post_id: '', prev_post_id: '', }; nock(Client4.getUsersRoute()). get(`/${userId}/channels/${channelId}/posts/unread`). query(true). reply(200, response); nock(Client4.getChannelsRoute()). get(`/${channelId}/posts`). query(true). reply(200, responseWithRecentPosts); await Actions.getPostsUnread(channelId)(dispatch, getState); const {posts} = getState().entities.posts; expect(posts[recentPost.id]).toBeTruthy(); }); it('getPostThread', async () => { const channelId = TestHelper.basicChannel!.id; const post = TestHelper.getPostMock({id: TestHelper.generateId(), channel_id: channelId, message: ''}); const comment = {id: TestHelper.generateId(), root_id: post.id, channel_id: channelId, message: ''}; store.dispatch(Actions.receivedPostsInChannel({order: [post.id], posts: {[post.id]: post}} as PostList, channelId)); const postList = { order: [post.id], posts: { [post.id]: post, [comment.id]: comment, }, }; nock(Client4.getBaseRoute()). get(`/posts/${post.id}/thread?skipFetchThreads=false&collapsedThreads=true&collapsedThreadsExtended=false&direction=down&perPage=60`). reply(200, postList); await Actions.getPostThread(post.id)(store.dispatch, store.getState); const state: GlobalState = store.getState(); const getRequest = state.requests.posts.getPostThread; const { posts, postsInChannel, postsInThread, } = state.entities.posts; if (getRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(getRequest.error)); } expect(posts).toBeTruthy(); expect(posts[post.id]).toBeTruthy(); expect(postsInThread[post.id]).toBeTruthy(); expect(postsInThread[post.id]).toEqual([comment.id]); expect(postsInChannel[channelId]).toBeTruthy(); const found = postsInChannel[channelId].find((block) => block.order.indexOf(comment.id) !== -1); // should not have found comment in postsInChannel expect(!found).toBeTruthy(); }); it('getPostEditHistory', async () => { const postId = TestHelper.generateId(); const data = [{ create_at: 1502715365009, edit_at: 1502715372443, user_id: TestHelper.basicUser!.id, }]; nock(Client4.getBaseRoute()). get(`/posts/${postId}/edit_history`). reply(200, data); await Actions.getPostEditHistory(postId)(store.dispatch, store.getState); const state: GlobalState = store.getState(); const editHistory = state.entities.posts.postEditHistory; expect(editHistory[0]).toBeTruthy(); expect(editHistory).toEqual(data); }); it('getPosts', async () => { const post0 = TestHelper.getPostMock({id: 'post0', channel_id: 'channel1', create_at: 1000, message: ''}); const post1 = TestHelper.getPostMock({id: 'post1', channel_id: 'channel1', create_at: 1001, message: ''}); const post2 = TestHelper.getPostMock({id: 'post2', channel_id: 'channel1', create_at: 1002, message: ''}); const post3 = TestHelper.getPostMock({id: 'post3', channel_id: 'channel1', root_id: 'post2', create_at: 1003, message: '', user_id: 'user1'}); const post4 = TestHelper.getPostMock({id: 'post4', channel_id: 'channel1', root_id: 'post0', create_at: 1004, message: '', user_id: 'user2'}); const postList = { order: ['post4', 'post3', 'post2', 'post1'], posts: { post0, post1, post2, post3, post4, }, }; nock(Client4.getChannelsRoute()). get('/channel1/posts'). query(true). reply(200, postList); const result = await store.dispatch(Actions.getPosts('channel1')); expect(result).toEqual({data: postList}); const state: GlobalState = store.getState(); expect(state.entities.posts.posts).toEqual({ post0: {...post0, participants: [{id: 'user2'}]}, post1, post2: {...post2, participants: [{id: 'user1'}]}, post3, post4, }); expect(state.entities.posts.postsInChannel).toEqual({ channel1: [ {order: ['post4', 'post3', 'post2', 'post1'], recent: true, oldest: false}, ], }); expect(state.entities.posts.postsInThread).toEqual({ post0: ['post4'], post2: ['post3'], }); }); it('getNeededAtMentionedUsernames', async () => { const state = { entities: { users: { profiles: { 1: { id: '1', username: 'aaa', }, }, }, groups: { groups: [ { id: '1', name: 'zzz', }, ], }, }, } as unknown as GlobalState; expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: 'aaa'}), ])).toEqual( new Set(), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@aaa'}), ])).toEqual( new Set(), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@zzz'}), ])).toEqual( new Set(), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@aaa @bbb @ccc @zzz'}), ])).toEqual( new Set(['bbb', 'ccc']), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@bbb. @ccc.ddd'}), ])).toEqual( new Set(['bbb.', 'bbb', 'ccc.ddd']), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@bbb- @ccc-ddd'}), ])).toEqual( new Set(['bbb-', 'bbb', 'ccc-ddd']), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@bbb_ @ccc_ddd'}), ])).toEqual( new Set(['bbb_', 'ccc_ddd']), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '(@bbb/@ccc) ddd@eee'}), ])).toEqual( new Set(['bbb', 'ccc']), ); expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({ message: '@aaa @bbb', props: { attachments: [ {text: '@ccc @ddd @zzz'}, {pretext: '@eee @fff', text: '@ggg'}, ], }, }), ]), ).toEqual( new Set(['bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg']), ); // should never try to request usernames matching special mentions expect( Actions.getNeededAtMentionedUsernamesAndGroups(state, [ TestHelper.getPostMock({message: '@all'}), TestHelper.getPostMock({message: '@here'}), TestHelper.getPostMock({message: '@channel'}), TestHelper.getPostMock({message: '@all.'}), TestHelper.getPostMock({message: '@here.'}), TestHelper.getPostMock({message: '@channel.'}), ])).toEqual( new Set(), ); }); it('getPostsSince', async () => { const post0 = TestHelper.getPostMock({id: 'post0', channel_id: 'channel1', create_at: 1000, message: ''}); const post1 = TestHelper.getPostMock({id: 'post1', channel_id: 'channel1', create_at: 1001, message: ''}); const post2 = TestHelper.getPostMock({id: 'post2', channel_id: 'channel1', create_at: 1002, message: ''}); const post3 = TestHelper.getPostMock({id: 'post3', channel_id: 'channel1', create_at: 1003, message: ''}); const post4 = TestHelper.getPostMock({id: 'post4', channel_id: 'channel1', root_id: 'post0', create_at: 1004, message: '', user_id: 'user1'}); store = configureStore({ entities: { posts: { posts: { post1, post2, }, postsInChannel: { channel1: [ {order: ['post2', 'post1'], recent: true}, ], }, }, }, }); const postList = { order: ['post4', 'post3', 'post1'], posts: { post0, post1, // Pretend post1 has been updated post3, post4, }, }; nock(Client4.getChannelsRoute()). get('/channel1/posts'). query(true). reply(200, postList); const result = await store.dispatch(Actions.getPostsSince('channel1', post2.create_at)); expect(result).toEqual({data: postList}); const state: GlobalState = store.getState(); expect(state.entities.posts.posts).toEqual({ post0: {...post0, participants: [{id: 'user1'}]}, post1, post2, post3, post4, }); expect(state.entities.posts.postsInChannel).toEqual({ channel1: [ {order: ['post4', 'post3', 'post2', 'post1'], recent: true}, ], }); expect(state.entities.posts.postsInThread).toEqual({ post0: ['post4'], }); }); it('getPostsBefore', async () => { const channelId = 'channel1'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1001, message: ''}; const post2 = {id: 'post2', channel_id: channelId, root_id: 'post1', create_at: 1002, message: ''}; const post3 = {id: 'post3', channel_id: channelId, create_at: 1003, message: ''}; store = configureStore({ entities: { posts: { posts: { post3, }, postsInChannel: { channel1: [ {order: ['post1'], recent: false, oldest: false}, ], }, }, }, }); const postList = { order: [post2.id, post1.id], posts: { post2, post1, }, prev_post_id: '', next_post_id: 'post3', }; nock(Client4.getChannelsRoute()). get(`/${channelId}/posts`). query(true). reply(200, postList); const result = await store.dispatch(Actions.getPostsBefore(channelId, 'post3', 0, 10)); expect(result).toEqual({data: postList}); const state: GlobalState = store.getState(); expect(state.entities.posts.posts).toEqual({post1, post2, post3}); expect(state.entities.posts.postsInChannel.channel1).toEqual([ {order: ['post3', 'post2', 'post1'], recent: false, oldest: true}, ]); expect(state.entities.posts.postsInThread).toEqual({ post1: ['post2'], }); }); it('getPostsAfter', async () => { const channelId = 'channel1'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1001, message: ''}; const post2 = {id: 'post2', channel_id: channelId, root_id: 'post1', create_at: 1002, message: '', user_id: 'user1'}; const post3 = {id: 'post3', channel_id: channelId, create_at: 1003, message: ''}; store = configureStore({ entities: { posts: { posts: { post1, }, postsInChannel: { channel1: [ {order: ['post1'], recent: false}, ], }, }, }, }); const postList = { order: [post3.id, post2.id], posts: { post2, post3, }, }; nock(Client4.getChannelsRoute()). get(`/${channelId}/posts`). query(true). reply(200, postList); const result = await store.dispatch(Actions.getPostsAfter(channelId, 'post1', 0, 10)); expect(result).toEqual({data: postList}); const state: GlobalState = store.getState(); expect(state.entities.posts.posts).toEqual({ post1: {...post1, participants: [{id: 'user1'}]}, post2, post3, }); expect(state.entities.posts.postsInChannel.channel1).toEqual([ {order: ['post3', 'post2', 'post1'], recent: false}, ]); expect(state.entities.posts.postsInThread).toEqual({ post1: ['post2'], }); }); it('getPostsAfter with empty next_post_id', async () => { const channelId = 'channel1'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1001, message: ''}; const post2 = {id: 'post2', channel_id: channelId, root_id: 'post1', create_at: 1002, message: '', user_id: 'user1'}; const post3 = {id: 'post3', channel_id: channelId, create_at: 1003, message: ''}; store = configureStore({ entities: { posts: { posts: { post1, }, postsInChannel: { channel1: [ {order: ['post1'], recent: false}, ], }, }, }, }); const postList = { order: [post3.id, post2.id], posts: { post2, post3, }, next_post_id: '', }; nock(Client4.getChannelsRoute()). get(`/${channelId}/posts`). query(true). reply(200, postList); const result = await store.dispatch(Actions.getPostsAfter(channelId, 'post1', 0, 10)); expect(result).toEqual({data: postList}); const state: GlobalState = store.getState(); expect(state.entities.posts.posts).toEqual({ post1: {...post1, participants: [{id: 'user1'}]}, post2, post3, }); expect(state.entities.posts.postsInChannel.channel1).toEqual([ {order: ['post3', 'post2', 'post1'], recent: true}, ]); }); it('getPostsAround', async () => { const postId = 'post3'; const channelId = 'channel1'; const postsAfter = { posts: { post1: {id: 'post1', create_at: 10002, message: ''}, post2: {id: 'post2', create_at: 10001, message: ''}, }, order: ['post1', 'post2'], next_post_id: 'post0', before_post_id: 'post3', }; const postsThread = { posts: { root: {id: 'root', create_at: 10010, message: ''}, post3: {id: 'post3', root_id: 'root', create_at: 10000, message: ''}, }, order: ['post3'], next_post_id: 'post2', before_post_id: 'post5', }; const postsBefore = { posts: { post4: {id: 'post4', create_at: 9999, message: ''}, post5: {id: 'post5', create_at: 9998, message: ''}, }, order: ['post4', 'post5'], next_post_id: 'post3', prev_post_id: 'post6', }; nock(Client4.getChannelsRoute()). get(`/${channelId}/posts`). query((params) => Boolean(params.after)). reply(200, postsAfter); nock(Client4.getChannelsRoute()). get(`/${channelId}/posts`). query((params) => Boolean(params.before)). reply(200, postsBefore); nock(Client4.getBaseRoute()). get(`/posts/${postId}/thread`). query(true). reply(200, postsThread); const result = await store.dispatch(Actions.getPostsAround(channelId, postId)); expect(result.error).toBeFalsy(); expect(result.data).toEqual({ posts: { ...postsAfter.posts, ...postsThread.posts, ...postsBefore.posts, }, order: [ ...postsAfter.order, postId, ...postsBefore.order, ], next_post_id: postsAfter.next_post_id, prev_post_id: postsBefore.prev_post_id, first_inaccessible_post_time: 0, }); const {posts, postsInChannel, postsInThread} = store.getState().entities.posts; // should store all of the posts expect(posts).toHaveProperty('post1'); expect(posts).toHaveProperty('post2'); expect(posts).toHaveProperty('post3'); expect(posts).toHaveProperty('post4'); expect(posts).toHaveProperty('post5'); expect(posts).toHaveProperty('root'); // should only store the posts that we know the order of expect(postsInChannel[channelId]).toEqual([{order: ['post1', 'post2', 'post3', 'post4', 'post5'], recent: false, oldest: false}]); // should populate postsInThread expect(postsInThread.root).toEqual(['post3']); }); it('flagPost', async () => { const {dispatch, getState} = store; const channelId = TestHelper.basicChannel!.id; nock(Client4.getUsersRoute()). post('/logout'). reply(200, OK_RESPONSE); await TestHelper.basicClient4!.logout(); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(channelId), ); nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); Actions.flagPost(post1.id)(dispatch, getState); const state = getState(); const prefKey = getPreferenceKey(Preferences.CATEGORY_FLAGGED_POST, post1.id); const preference = state.entities.preferences.myPreferences[prefKey]; expect(preference).toBeTruthy(); }); it('unflagPost', async () => { const {dispatch, getState} = store; const channelId = TestHelper.basicChannel!.id; nock(Client4.getUsersRoute()). post('/logout'). reply(200, OK_RESPONSE); await TestHelper.basicClient4!.logout(); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(channelId), ); nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); Actions.flagPost(post1.id)(dispatch, getState); let state = getState(); const prefKey = getPreferenceKey(Preferences.CATEGORY_FLAGGED_POST, post1.id); const preference = state.entities.preferences.myPreferences[prefKey]; expect(preference).toBeTruthy(); nock(Client4.getUsersRoute()). delete(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); Actions.unflagPost(post1.id)(dispatch, getState); state = getState(); const unflagged = state.entities.preferences.myPreferences[prefKey]; if (unflagged) { throw new Error('unexpected unflagged'); } }); it('setUnreadPost', async () => { const teamId = TestHelper.generateId(); const channelId = TestHelper.generateId(); const userId = TestHelper.generateId(); const postId = TestHelper.generateId(); store = configureStore({ entities: { channels: { channels: { [channelId]: {team_id: teamId}, }, messageCounts: { [channelId]: {total: 10}, }, myMembers: { [channelId]: {msg_count: 10, mention_count: 0, last_viewed_at: 0}, }, }, teams: { myMembers: { [teamId]: {msg_count: 15, mention_count: 0}, }, }, users: { currentUserId: userId, }, posts: { posts: { [postId]: {id: postId, msg: 'test message', create_at: 123, delete_at: 0, channel_id: channelId}, }, }, }, }); nock(Client4.getUserRoute(userId)).post(`/posts/${postId}/set_unread`).reply(200, { team_id: teamId, channel_id: channelId, msg_count: 3, last_viewed_at: 1565605543, mention_count: 1, }); await store.dispatch(Actions.setUnreadPost(userId, postId)); const state: GlobalState = store.getState(); expect(state.entities.channels.messageCounts[channelId].total).toBe(10); expect(state.entities.channels.myMembers[channelId].msg_count).toBe(3); expect(state.entities.channels.myMembers[channelId].mention_count).toBe(1); expect(state.entities.channels.myMembers[channelId].last_viewed_at).toBe(1565605543); expect(state.entities.teams.myMembers[teamId].msg_count).toBe(8); expect(state.entities.teams.myMembers[teamId].mention_count).toBe(1); }); it('pinPost', async () => { const {dispatch, getState} = store; nock(Client4.getBaseRoute()). get(`/channels/${TestHelper.basicChannel!.id}/stats?exclude_files_count=true`). reply(200, {channel_id: TestHelper.basicChannel!.id, member_count: 1, pinnedpost_count: 0}); await dispatch(getChannelStats(TestHelper.basicChannel!.id)); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const postList = {order: [post1.id], posts: {}} as PostList; postList.posts[post1.id] = post1; nock(Client4.getBaseRoute()). get(`/posts/${post1.id}/thread?skipFetchThreads=false&collapsedThreads=true&collapsedThreadsExtended=false&direction=down&perPage=60`). reply(200, postList); await Actions.getPostThread(post1.id)(dispatch, getState); nock(Client4.getBaseRoute()). post(`/posts/${post1.id}/pin`). reply(200, OK_RESPONSE); await Actions.pinPost(post1.id)(dispatch, getState); const state = getState(); const {stats} = state.entities.channels; const post = state.entities.posts.posts[post1.id]; const pinnedPostCount = stats[TestHelper.basicChannel!.id].pinnedpost_count; expect(post).toBeTruthy(); expect(post.is_pinned === true).toBeTruthy(); expect(pinnedPostCount === 1).toBeTruthy(); }); it('unpinPost', async () => { const {dispatch, getState} = store; nock(Client4.getBaseRoute()). get(`/channels/${TestHelper.basicChannel!.id}/stats?exclude_files_count=true`). reply(200, {channel_id: TestHelper.basicChannel!.id, member_count: 1, pinnedpost_count: 0}); await dispatch(getChannelStats(TestHelper.basicChannel!.id)); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const postList = {order: [post1.id], posts: {}} as PostList; postList.posts[post1.id] = post1; nock(Client4.getBaseRoute()). get(`/posts/${post1.id}/thread?skipFetchThreads=false&collapsedThreads=true&collapsedThreadsExtended=false&direction=down&perPage=60`). reply(200, postList); await Actions.getPostThread(post1.id)(dispatch, getState); nock(Client4.getBaseRoute()). post(`/posts/${post1.id}/pin`). reply(200, OK_RESPONSE); await Actions.pinPost(post1.id)(dispatch, getState); nock(Client4.getBaseRoute()). post(`/posts/${post1.id}/unpin`). reply(200, OK_RESPONSE); await Actions.unpinPost(post1.id)(dispatch, getState); const state = getState(); const {stats} = state.entities.channels; const post = state.entities.posts.posts[post1.id]; const pinnedPostCount = stats[TestHelper.basicChannel!.id].pinnedpost_count; expect(post).toBeTruthy(); expect(post.is_pinned === false).toBeTruthy(); expect(pinnedPostCount === 0).toBeTruthy(); }); it('addReaction', async () => { const {dispatch, getState} = store; TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const emojiName = '+1'; nock(Client4.getBaseRoute()). post('/reactions'). reply(201, {user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName, create_at: 1508168444721}); await Actions.addReaction(post1.id, emojiName)(dispatch, getState); const state = getState(); const reactions = state.entities.posts.reactions[post1.id]; expect(reactions).toBeTruthy(); expect(reactions[TestHelper.basicUser!.id + '-' + emojiName]).toBeTruthy(); }); it('removeReaction', async () => { const {dispatch, getState} = store; TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const emojiName = '+1'; nock(Client4.getBaseRoute()). post('/reactions'). reply(201, {user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName, create_at: 1508168444721}); await Actions.addReaction(post1.id, emojiName)(dispatch, getState); nock(Client4.getUsersRoute()). delete(`/${TestHelper.basicUser!.id}/posts/${post1.id}/reactions/${emojiName}`). reply(200, OK_RESPONSE); await Actions.removeReaction(post1.id, emojiName)(dispatch, getState); const state = getState(); const reactions = state.entities.posts.reactions[post1.id]; expect(reactions).toBeTruthy(); expect(!reactions[TestHelper.basicUser!.id + '-' + emojiName]).toBeTruthy(); }); it('getReactionsForPost', async () => { const {dispatch, getState} = store; TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await store.dispatch(loadMe()); nock(Client4.getBaseRoute()). post('/posts'). reply(201, TestHelper.fakePostWithId(TestHelper.basicChannel!.id)); const post1 = await Client4.createPost( TestHelper.fakePost(TestHelper.basicChannel!.id), ); const emojiName = '+1'; nock(Client4.getBaseRoute()). post('/reactions'). reply(201, {user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName, create_at: 1508168444721}); await Actions.addReaction(post1.id, emojiName)(dispatch, getState); dispatch({ type: PostTypes.REACTION_DELETED, data: {user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName}, }); nock(Client4.getBaseRoute()). get(`/posts/${post1.id}/reactions`). reply(200, [{user_id: TestHelper.basicUser!.id, post_id: post1.id, emoji_name: emojiName, create_at: 1508168444721}]); await Actions.getReactionsForPost(post1.id)(dispatch, getState); const state = getState(); const reactions = state.entities.posts.reactions[post1.id]; expect(reactions).toBeTruthy(); expect(reactions[TestHelper.basicUser!.id + '-' + emojiName]).toBeTruthy(); }); it('getCustomEmojiForReaction', async () => { const testImageData = fs.createReadStream('src/packages/mattermost-redux/test/assets/images/test.png'); const {dispatch, getState} = store; nock(Client4.getBaseRoute()). post('/emoji'). reply(201, {id: TestHelper.generateId(), create_at: 1507918415696, update_at: 1507918415696, delete_at: 0, creator_id: TestHelper.basicUser!.id, name: TestHelper.generateId()}); const {data: created} = await createCustomEmoji( { name: TestHelper.generateId(), creator_id: TestHelper.basicUser!.id, }, testImageData, )(store.dispatch, store.getState) as ActionResult; nock(Client4.getEmojisRoute()). get(`/name/${created.name}`). reply(200, created); const missingEmojiName = ':notrealemoji:'; nock(Client4.getEmojisRoute()). get(`/name/${missingEmojiName}`). reply(404, {message: 'Not found', status_code: 404}); await Actions.getCustomEmojiForReaction(missingEmojiName)(dispatch, getState); const state = getState(); const emojis = state.entities.emojis.customEmoji; expect(emojis).toBeTruthy(); expect(emojis[created.id]).toBeTruthy(); expect(state.entities.emojis.nonExistentEmoji.has(missingEmojiName)).toBeTruthy(); }); it('doPostAction', async () => { nock(Client4.getBaseRoute()). post('/posts/posth67ja7ntdkek6g13dp3wka/actions/action7ja7ntdkek6g13dp3wka'). reply(200, {}); const {data} = await Actions.doPostAction('posth67ja7ntdkek6g13dp3wka', 'action7ja7ntdkek6g13dp3wka', 'option')(store.dispatch, store.getState); expect(data).toEqual({}); }); it('doPostActionWithCookie', async () => { nock(Client4.getBaseRoute()). post('/posts/posth67ja7ntdkek6g13dp3wka/actions/action7ja7ntdkek6g13dp3wka'). reply(200, {}); const {data} = await Actions.doPostActionWithCookie('posth67ja7ntdkek6g13dp3wka', 'action7ja7ntdkek6g13dp3wka', '', 'option')(store.dispatch, store.getState); expect(data).toEqual({}); }); it('addMessageIntoHistory', async () => { const {dispatch, getState} = store; await Actions.addMessageIntoHistory('test1')(dispatch); let history = getState().entities.posts.messagesHistory.messages; expect(history.length === 1).toBeTruthy(); expect(history[0] === 'test1').toBeTruthy(); await Actions.addMessageIntoHistory('test2')(dispatch); history = getState().entities.posts.messagesHistory.messages; expect(history.length === 2).toBeTruthy(); expect(history[1] === 'test2').toBeTruthy(); await Actions.addMessageIntoHistory('test3')(dispatch); history = getState().entities.posts.messagesHistory.messages; expect(history.length === 3).toBeTruthy(); expect(history[2] === 'test3').toBeTruthy(); }); it('resetHistoryIndex', async () => { const {dispatch, getState} = store; await Actions.addMessageIntoHistory('test1')(dispatch); await Actions.addMessageIntoHistory('test2')(dispatch); await Actions.addMessageIntoHistory('test3')(dispatch); let index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 3).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.COMMENT)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 1).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 2).toBeTruthy(); await Actions.resetHistoryIndex(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 3).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 2).toBeTruthy(); await Actions.resetHistoryIndex(Posts.MESSAGE_TYPES.COMMENT)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 3).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); }); it('moveHistoryIndexBack', async () => { const {dispatch, getState} = store; await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); let index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === -1).toBeTruthy(); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === -1).toBeTruthy(); await Actions.addMessageIntoHistory('test1')(dispatch); await Actions.addMessageIntoHistory('test2')(dispatch); await Actions.addMessageIntoHistory('test3')(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 3).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 1).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 0).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.COMMENT)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 0).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 2).toBeTruthy(); }); it('moveHistoryIndexForward', async () => { const {dispatch, getState} = store; await Actions.moveHistoryIndexForward(Posts.MESSAGE_TYPES.POST)(dispatch); let index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 0).toBeTruthy(); await Actions.moveHistoryIndexForward(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 0).toBeTruthy(); await Actions.addMessageIntoHistory('test1')(dispatch); await Actions.addMessageIntoHistory('test2')(dispatch); await Actions.addMessageIntoHistory('test3')(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 3).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); await Actions.moveHistoryIndexForward(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexForward(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 3).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 3).toBeTruthy(); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.POST)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.COMMENT)(dispatch); await Actions.moveHistoryIndexBack(Posts.MESSAGE_TYPES.COMMENT)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 1).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 1).toBeTruthy(); await Actions.moveHistoryIndexForward(Posts.MESSAGE_TYPES.POST)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 2).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 1).toBeTruthy(); await Actions.moveHistoryIndexForward(Posts.MESSAGE_TYPES.COMMENT)(dispatch); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.POST]; expect(index === 2).toBeTruthy(); index = getState().entities.posts.messagesHistory.index[Posts.MESSAGE_TYPES.COMMENT]; expect(index === 2).toBeTruthy(); }); describe('getMentionsAndStatusesForPosts', () => { describe('different values for posts argument', () => { // Mock the state to prevent any followup requests since we aren't testing those const currentUserId = 'user'; const post = TestHelper.getPostMock({id: 'post', user_id: currentUserId, message: 'This is a post'}); const dispatch = null; const getState = (() => ({ entities: { general: { config: { EnableCustomEmoji: 'false', }, }, users: { currentUserId, statuses: { [currentUserId]: 'status', }, }, }, })) as unknown as GetStateFunc; it('null', async () => { await Actions.getMentionsAndStatusesForPosts(null as any, dispatch as any, getState); }); it('array of posts', async () => { const posts = [post]; await Actions.getMentionsAndStatusesForPosts(posts, dispatch as any, getState); }); it('object map of posts', async () => { const posts = { [post.id]: post, }; await Actions.getMentionsAndStatusesForPosts(posts, dispatch as any, getState); }); }); }); describe('getThreadsForPosts', () => { beforeAll(() => { TestHelper.initBasic(Client4); }); afterAll(() => { TestHelper.tearDown(); }); let channelId = ''; let post1 = TestHelper.getPostMock(); let post2 = TestHelper.getPostMock(); let post3 = TestHelper.getPostMock(); let comment = TestHelper.getPostMock(); beforeEach(async () => { store = configureStore(); channelId = TestHelper.basicChannel!.id; post1 = TestHelper.getPostMock({id: TestHelper.generateId(), channel_id: channelId, message: ''}); post2 = TestHelper.getPostMock({id: TestHelper.generateId(), channel_id: channelId, message: ''}); comment = TestHelper.getPostMock({id: TestHelper.generateId(), root_id: post1.id, channel_id: channelId, message: ''}); post3 = TestHelper.getPostMock({id: TestHelper.generateId(), channel_id: channelId, message: ''}); store.dispatch(Actions.receivedPostsInChannel({ order: [post2.id, post3.id], posts: {[post2.id]: post2, [post3.id]: post3}, } as PostList, channelId)); const threadList = { order: [post1.id], posts: { [post1.id]: post1, [comment.id]: comment, }, }; nock(Client4.getBaseRoute()). get(`/posts/${post1.id}/thread?skipFetchThreads=false&collapsedThreads=false&collapsedThreadsExtended=false&direction=down&perPage=60`). reply(200, threadList); }); it('handlesNull', async () => { const ret = await store.dispatch(Actions.getThreadsForPosts(null as any)); expect(ret).toEqual({data: true}); const state: GlobalState = store.getState(); const getRequest = state.requests.posts.getPostThread; if (getRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(getRequest.error)); } const { postsInChannel, postsInThread, } = state.entities.posts; expect(postsInChannel[channelId]).toBeTruthy(); expect(postsInChannel[channelId][0].order).toEqual([post2.id, post3.id]); expect(!postsInThread[post1.id]).toBeTruthy(); const found = postsInChannel[channelId].find((block) => block.order.indexOf(comment.id) !== -1); // should not have found comment in postsInChannel expect(!found).toBeTruthy(); }); it('pullsUpTheThreadOfAMissingPost', async () => { await store.dispatch(Actions.getThreadsForPosts([comment])); const state: GlobalState = store.getState(); const getRequest = state.requests.posts.getPostThread; if (getRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(getRequest.error)); } const { posts, postsInChannel, postsInThread, } = state.entities.posts; expect(posts).toBeTruthy(); expect(postsInChannel[channelId][0].order).toEqual([post2.id, post3.id]); expect(posts[post1.id]).toBeTruthy(); expect(postsInThread[post1.id]).toBeTruthy(); expect(postsInThread[post1.id]).toEqual([comment.id]); const found = postsInChannel[channelId].find((block) => block.order.indexOf(comment.id) !== -1); // should not have found comment in postsInChannel expect(!found).toBeTruthy(); }); }); describe('receivedPostsBefore', () => { it('Should return default false for oldest key if param does not exist', () => { const posts = {} as PostList; const result = Actions.receivedPostsBefore(posts, 'channelId', 'beforePostId'); expect(result).toEqual({ type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channelId', data: posts, beforePostId: 'beforePostId', oldest: false, }); }); it('Should return true for oldest key', () => { const posts = {} as PostList; const result = Actions.receivedPostsBefore(posts, 'channelId', 'beforePostId', true); expect(result).toEqual({ type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channelId', data: posts, beforePostId: 'beforePostId', oldest: true, }); }); }); describe('receivedPostsInChannel', () => { it('Should return default false for both recent and oldest keys if params dont exist', () => { const posts = {} as PostList; const result = Actions.receivedPostsInChannel(posts, 'channelId'); expect(result).toEqual({ type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channelId', data: posts, recent: false, oldest: false, }); }); it('Should return true for oldest and recent keys', () => { const posts = {} as PostList; const result = Actions.receivedPostsInChannel(posts, 'channelId', true, true); expect(result).toEqual({ type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channelId', data: posts, recent: true, oldest: true, }); }); }); });
3,962
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/preferences.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import {UserTypes} from 'mattermost-redux/action_types'; import * as Actions from 'mattermost-redux/actions/preferences'; import {loadMe} from 'mattermost-redux/actions/users'; import {Client4} from 'mattermost-redux/client'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; import {Preferences} from '../constants'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.Preferences', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore({ entities: { users: { currentUserId: TestHelper.basicUser!.id, }, general: { config: { CollapsedThreads: 'always_on', }, }, }, }); }); afterAll(() => { TestHelper.tearDown(); }); it('getMyPreferences', async () => { const user = TestHelper.basicUser!; const existingPreferences = [ { user_id: user.id, category: 'test', name: 'test1', value: 'test', }, { user_id: user.id, category: 'test', name: 'test2', value: 'test', }, ]; nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Client4.savePreferences(user.id, existingPreferences); nock(Client4.getUsersRoute()). get('/me/preferences'). reply(200, existingPreferences); await Actions.getMyPreferences()(store.dispatch, store.getState); const state = store.getState(); const {myPreferences} = state.entities.preferences; // first preference doesn't exist expect(myPreferences['test--test1']).toBeTruthy(); expect(existingPreferences[0]).toEqual(myPreferences['test--test1']); // second preference doesn't exist expect(myPreferences['test--test2']).toBeTruthy(); expect(existingPreferences[1]).toEqual(myPreferences['test--test2']); }); it('savePrefrences', async () => { const user = TestHelper.basicUser!; const existingPreferences = [ { user_id: user.id, category: 'test', name: 'test1', value: 'test', }, ]; nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Client4.savePreferences(user.id, existingPreferences); nock(Client4.getUsersRoute()). get('/me/preferences'). reply(200, existingPreferences); await Actions.getMyPreferences()(store.dispatch, store.getState); const preferences = [ { user_id: user.id, category: 'test', name: 'test2', value: 'test', }, { user_id: user.id, category: 'test', name: 'test3', value: 'test', }, ]; nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Actions.savePreferences(user.id, preferences)(store.dispatch); const state = store.getState(); const {myPreferences} = state.entities.preferences; // first preference doesn't exist expect(myPreferences['test--test1']).toBeTruthy(); expect(existingPreferences[0]).toEqual(myPreferences['test--test1']); // second preference doesn't exist expect(myPreferences['test--test2']).toBeTruthy(); expect(preferences[0]).toEqual(myPreferences['test--test2']); // third preference doesn't exist expect(myPreferences['test--test3']).toBeTruthy(); expect(preferences[1]).toEqual(myPreferences['test--test3']); }); it('deletePreferences', async () => { const user = TestHelper.basicUser!; const existingPreferences = [ { user_id: user.id, category: 'test', name: 'test1', value: 'test', }, { user_id: user.id, category: 'test', name: 'test2', value: 'test', }, { user_id: user.id, category: 'test', name: 'test3', value: 'test', }, ]; nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Client4.savePreferences(user.id, existingPreferences); nock(Client4.getUsersRoute()). get('/me/preferences'). reply(200, existingPreferences); await Actions.getMyPreferences()(store.dispatch, store.getState); nock(Client4.getUsersRoute()). post(`/${TestHelper.basicUser!.id}/preferences/delete`). reply(200, OK_RESPONSE); await Actions.deletePreferences(user.id, [ existingPreferences[0], existingPreferences[2], ])(store.dispatch, store.getState); const state = store.getState(); const {myPreferences} = state.entities.preferences; // deleted preference still exists expect(!myPreferences['test--test1']).toBeTruthy(); // second preference doesn't exist expect(myPreferences['test--test2']).toBeTruthy(); expect(existingPreferences[1]).toEqual(myPreferences['test--test2']); // third preference doesn't exist expect(!myPreferences['test--test3']).toBeTruthy(); }); it('makeDirectChannelVisibleIfNecessary', async () => { const user = TestHelper.basicUser!; nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user2 = await TestHelper.createClient4().createUser(TestHelper.fakeUser(), '', ''); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await loadMe()(store.dispatch, store.getState); // Test that a new preference is created if none exists nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Actions.makeDirectChannelVisibleIfNecessary(user2.id)(store.dispatch, store.getState); let state = store.getState(); let myPreferences = state.entities.preferences.myPreferences; let preference = myPreferences[`${Preferences.CATEGORY_DIRECT_CHANNEL_SHOW}--${user2.id}`]; // preference for showing direct channel doesn't exist expect(preference).toBeTruthy(); // preference for showing direct channel is not true expect(preference.value).toBe('true'); // Test that nothing changes if the preference already exists and is true nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Actions.makeDirectChannelVisibleIfNecessary(user2.id)(store.dispatch, store.getState); const state2 = store.getState(); // store should not change since direct channel is already visible expect(state).toEqual(state2); // Test that the preference is updated if it already exists and is false nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); Actions.savePreferences(user.id, [{ ...preference, value: 'false', }])(store.dispatch); nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Actions.makeDirectChannelVisibleIfNecessary(user2.id)(store.dispatch, store.getState); state = store.getState(); myPreferences = state.entities.preferences.myPreferences; preference = myPreferences[`${Preferences.CATEGORY_DIRECT_CHANNEL_SHOW}--${user2.id}`]; // preference for showing direct channel doesn't exist expect(preference).toBeTruthy(); // preference for showing direct channel is not true expect(preference.value).toEqual('true'); }); it('saveTheme', async () => { const user = TestHelper.basicUser!; const team = TestHelper.basicTeam!; const existingPreferences = [ { user_id: user.id, category: 'theme', name: team.id, value: JSON.stringify({ type: 'Mattermost', }), }, ]; nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Client4.savePreferences(user.id, existingPreferences); nock(Client4.getUsersRoute()). get('/me/preferences'). reply(200, existingPreferences); await Actions.getMyPreferences()(store.dispatch, store.getState); const newTheme = { type: 'Mattermost Dark', } as unknown as Theme; nock(Client4.getUsersRoute()). put(`/${TestHelper.basicUser!.id}/preferences`). reply(200, OK_RESPONSE); await Actions.saveTheme(team.id, newTheme)(store.dispatch, store.getState); const state = store.getState(); const {myPreferences} = state.entities.preferences; // theme preference doesn't exist expect(myPreferences[`theme--${team.id}`]).toBeTruthy(); expect(myPreferences[`theme--${team.id}`].value).toEqual(JSON.stringify(newTheme)); }); it('deleteTeamSpecificThemes', async () => { const user = TestHelper.basicUser!; TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await loadMe()(store.dispatch, store.getState); const theme = { type: 'Mattermost Dark', }; const existingPreferences = [ { user_id: user.id, category: 'theme', name: '', value: JSON.stringify(theme), }, { user_id: user.id, category: 'theme', name: TestHelper.generateId(), value: JSON.stringify({ type: 'Mattermost', }), }, { user_id: user.id, category: 'theme', name: TestHelper.generateId(), value: JSON.stringify({ type: 'Mattermost', }), }, ]; nock(Client4.getUsersRoute()). put(`/${user.id}/preferences`). reply(200, OK_RESPONSE); await Client4.savePreferences(user.id, existingPreferences); nock(Client4.getUsersRoute()). get('/me/preferences'). reply(200, existingPreferences); await Actions.getMyPreferences()(store.dispatch, store.getState); nock(Client4.getUsersRoute()). post(`/${user.id}/preferences/delete`). reply(200, OK_RESPONSE); await Actions.deleteTeamSpecificThemes()(store.dispatch, store.getState); const state = store.getState(); const {myPreferences} = state.entities.preferences; expect(Object.entries(myPreferences).length).toBe(1); // theme preference doesn't exist expect(myPreferences['theme--']).toBeTruthy(); }); });
3,966
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/schemes.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import * as Actions from 'mattermost-redux/actions/schemes'; import {Client4} from 'mattermost-redux/client'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; describe('Actions.Schemes', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore(); }); afterAll(() => { TestHelper.tearDown(); }); it('getSchemes', async () => { const mockScheme = TestHelper.basicScheme; nock(Client4.getBaseRoute()). get('/schemes'). query(true). reply(200, [mockScheme]); await Actions.getSchemes('team')(store.dispatch, store.getState); const {schemes} = store.getState().entities.schemes; expect(Object.keys(schemes).length > 0).toBeTruthy(); }); it('createScheme', async () => { const mockScheme = TestHelper.basicScheme; nock(Client4.getBaseRoute()). post('/schemes'). reply(201, mockScheme!); await Actions.createScheme(TestHelper.mockScheme())(store.dispatch, store.getState); const {schemes} = store.getState().entities.schemes; const schemeId = Object.keys(schemes)[0]; expect(Object.keys(schemes).length).toEqual(1); expect(mockScheme!.id).toEqual(schemeId); }); it('getScheme', async () => { nock(Client4.getBaseRoute()). get('/schemes/' + TestHelper.basicScheme!.id). reply(200, TestHelper.basicScheme!); await Actions.getScheme(TestHelper.basicScheme!.id)(store.dispatch, store.getState); const state = store.getState(); const {schemes} = state.entities.schemes; expect(schemes[TestHelper.basicScheme!.id].name).toEqual(TestHelper.basicScheme!.name); }); it('patchScheme', async () => { const patchData = {name: 'The Updated Scheme', description: 'This is a scheme created by unit tests'}; const scheme = { ...TestHelper.basicScheme, ...patchData, }; nock(Client4.getBaseRoute()). put('/schemes/' + TestHelper.basicScheme!.id + '/patch'). reply(200, scheme); await Actions.patchScheme(TestHelper.basicScheme!.id, scheme)(store.dispatch, store.getState); const state = store.getState(); const {schemes} = state.entities.schemes; const updated = schemes[TestHelper.basicScheme!.id]; expect(updated).toBeTruthy(); expect(updated.name).toEqual(patchData.name); expect(updated.description).toEqual(patchData.description); }); it('deleteScheme', async () => { nock(Client4.getBaseRoute()). delete('/schemes/' + TestHelper.basicScheme!.id). reply(200, {status: 'OK'}); await Actions.deleteScheme(TestHelper.basicScheme!.id)(store.dispatch, store.getState); const state = store.getState(); const {schemes} = state.entities.schemes; expect(schemes).not.toBe({}); }); });
3,968
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/search.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import type {SearchParameter} from '@mattermost/types/search'; import * as Actions from 'mattermost-redux/actions/search'; import {Client4} from 'mattermost-redux/client'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; describe('Actions.Search', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore(); }); afterAll(() => { TestHelper.tearDown(); }); it('Perform Search', async () => { const {dispatch, getState} = store; let post1 = { ...TestHelper.fakePost(TestHelper.basicChannel!.id), message: 'try searching for this using the first and last word', }; let post2 = { ...TestHelper.fakePost(TestHelper.basicChannel!.id), message: 'return this message in second attempt', }; nock(Client4.getBaseRoute()). post('/posts'). reply(201, {...post1, id: TestHelper.generateId()}); post1 = await Client4.createPost(post1); nock(Client4.getBaseRoute()). post('/posts'). reply(201, {...post2, id: TestHelper.generateId()}); post2 = await Client4.createPost(post2); // Test for a couple of words const search1 = 'try word'; nock(Client4.getTeamsRoute()). post(`/${TestHelper.basicTeam!.id}/posts/search`). reply(200, {order: [post1.id], posts: {[post1.id]: post1}}); nock(Client4.getChannelsRoute()). get(`/${TestHelper.basicChannel!.id}/members/me`). reply(201, {user_id: TestHelper.basicUser!.id, channel_id: TestHelper.basicChannel!.id}); await Actions.searchPosts(TestHelper.basicTeam!.id, search1, false, false)(dispatch, getState); let state = getState(); let {recent, results} = state.entities.search; const {posts} = state.entities.posts; let current = state.entities.search.current[TestHelper.basicTeam!.id]; expect(recent[TestHelper.basicTeam!.id]).toBeTruthy(); let searchIsPresent = recent[TestHelper.basicTeam!.id].findIndex((r: {terms: string}) => r.terms === search1); expect(searchIsPresent !== -1).toBeTruthy(); expect(Object.keys(recent[TestHelper.basicTeam!.id]).length).toEqual(1); expect(results.length).toEqual(1); expect(posts[results[0]]).toBeTruthy(); expect(!current.isEnd).toBeTruthy(); // Search the next page and check the end of the search nock(Client4.getTeamsRoute()). post(`/${TestHelper.basicTeam!.id}/posts/search`). reply(200, {order: [], posts: {}}); await Actions.searchPostsWithParams(TestHelper.basicTeam!.id, {terms: search1, page: 1} as SearchParameter)(dispatch, getState); state = getState(); current = state.entities.search.current[TestHelper.basicTeam!.id]; recent = state.entities.search.recent; results = state.entities.search.results; expect(recent[TestHelper.basicTeam!.id]).toBeTruthy(); searchIsPresent = recent[TestHelper.basicTeam!.id].findIndex((r: {terms: string}) => r.terms === search1); expect(searchIsPresent !== -1).toBeTruthy(); expect(Object.keys(recent[TestHelper.basicTeam!.id]).length).toEqual(1); expect(results.length).toEqual(1); expect(current.isEnd).toBeTruthy(); // DISABLED // Test for posts from a user in a channel //const search2 = `from: ${TestHelper.basicUser.username} in: ${TestHelper.basicChannel.name}`; //nock(Client4.getTeamsRoute(), `/${TestHelper.basicTeam.id}/posts/search`). //post(`/${TestHelper.basicTeam.id}/posts/search`). //reply(200, {order: [post1.id, post2.id, TestHelper.basicPost.id], posts: {[post1.id]: post1, [TestHelper.basicPost.id]: TestHelper.basicPost, [post2.id]: post2}}); //nock(Client4.getChannelsRoute()). //get(`/${TestHelper.basicChannel.id}/members/me`). //reply(201, {user_id: TestHelper.basicUser.id, channel_id: TestHelper.basicChannel.id}); // //await Actions.searchPosts( //TestHelper.basicTeam.id, //search2 //)(dispatch, getState); // //state = getState(); //recent = state.entities.search.recent; //results = state.entities.search.results; //searchIsPresent = recent[TestHelper.basicTeam.id].findIndex((r) => r.terms === search1); //expect(searchIsPresent !== -1).toBeTruthy(); //expect(Object.keys(recent[TestHelper.basicTeam.id]).length).toEqual(2); //expect(results.length).toEqual(3); // Clear posts from the search store //await Actions.clearSearch()(dispatch, getState); //state = getState(); //recent = state.entities.search.recent; //results = state.entities.search.results; //searchIsPresent = recent[TestHelper.basicTeam.id].findIndex((r) => r.terms === search1); //expect(searchIsPresent !== -1).toBeTruthy(); //expect(Object.keys(recent[TestHelper.basicTeam.id]).length).toEqual(2); //expect(results.length).toEqual(0); // Clear a recent term //await Actions.removeSearchTerms(TestHelper.basicTeam.id, search2)(dispatch, getState); //state = getState(); //recent = state.entities.search.recent; //results = state.entities.search.results; //searchIsPresent = recent[TestHelper.basicTeam.id].findIndex((r) => r.terms === search1); //expect(searchIsPresent !== -1).toBeTruthy(); //searchIsPresent = recent[TestHelper.basicTeam.id].findIndex((r) => r.terms === search2); //expect(searchIsPresent === -1).toBeTruthy(); //expect(Object.keys(recent[TestHelper.basicTeam.id]).length).toEqual(1); //expect(results.length).toEqual(0); }); it('Perform Files Search', async () => { const {dispatch, getState} = store; const files = TestHelper.fakeFiles(2); (files[0] as any).channel_id = TestHelper.basicChannel!.id; (files[1] as any).channel_id = TestHelper.basicChannel!.id; // Test for a couple of words const search1 = 'try word'; nock(Client4.getTeamsRoute()). post(`/${TestHelper.basicTeam!.id}/files/search`). reply(200, {order: [files[0].id], file_infos: {[files[0].id]: files[0]}}); nock(Client4.getChannelsRoute()). get(`/${TestHelper.basicChannel!.id}/members/me`). reply(201, {user_id: TestHelper.basicUser!.id, channel_id: TestHelper.basicChannel!.id}); await Actions.searchFiles(TestHelper.basicTeam!.id, search1, false, false)(dispatch, getState); let state = getState(); let {recent, fileResults} = state.entities.search; const {filesFromSearch} = state.entities.files; let current = state.entities.search.current[TestHelper.basicTeam!.id]; expect(recent[TestHelper.basicTeam!.id]).toBeTruthy(); let searchIsPresent = recent[TestHelper.basicTeam!.id].findIndex((r: {terms: string}) => r.terms === search1); expect(searchIsPresent !== -1).toBeTruthy(); expect(Object.keys(recent[TestHelper.basicTeam!.id]).length).toEqual(1); expect(fileResults.length).toEqual(1); expect(filesFromSearch[fileResults[0]]).toBeTruthy(); expect(!current.isFilesEnd).toBeTruthy(); // Search the next page and check the end of the search nock(Client4.getTeamsRoute()). post(`/${TestHelper.basicTeam!.id}/files/search`). reply(200, {order: [], file_infos: {}}); await Actions.searchFilesWithParams(TestHelper.basicTeam!.id, {terms: search1, page: 1} as SearchParameter)(dispatch, getState); state = getState(); current = state.entities.search.current[TestHelper.basicTeam!.id]; recent = state.entities.search.recent; fileResults = state.entities.search.fileResults; expect(recent[TestHelper.basicTeam!.id]).toBeTruthy(); searchIsPresent = recent[TestHelper.basicTeam!.id].findIndex((r: {terms: string}) => r.terms === search1); expect(searchIsPresent !== -1).toBeTruthy(); expect(Object.keys(recent[TestHelper.basicTeam!.id]).length).toEqual(1); expect(fileResults.length).toEqual(1); expect(current.isFilesEnd).toBeTruthy(); }); });
3,970
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/teams.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import fs from 'fs'; import nock from 'nock'; import type {Team} from '@mattermost/types/teams'; import {GeneralTypes, UserTypes} from 'mattermost-redux/action_types'; import * as Actions from 'mattermost-redux/actions/teams'; import {loadMe} from 'mattermost-redux/actions/users'; import {Client4} from 'mattermost-redux/client'; import {General, RequestStatus} from 'mattermost-redux/constants'; import type {ActionResult} from 'mattermost-redux/types/actions'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.Teams', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore({ entities: { general: { config: { CollapsedThreads: 'always_on', }, }, }, }); }); afterAll(() => { TestHelper.tearDown(); }); it('selectTeam', async () => { await store.dispatch(Actions.selectTeam(TestHelper.basicTeam!)); await TestHelper.wait(100); const {currentTeamId} = store.getState().entities.teams; expect(currentTeamId).toBeTruthy(); expect(currentTeamId).toEqual(TestHelper.basicTeam!.id); }); it('getMyTeams', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await loadMe()(store.dispatch, store.getState); nock(Client4.getBaseRoute()). get('/users/me/teams'). reply(200, [TestHelper.basicTeam]); await Actions.getMyTeams()(store.dispatch, store.getState); const teamsRequest = store.getState().requests.teams.getMyTeams; const {teams} = store.getState().entities.teams; if (teamsRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(teamsRequest.error)); } expect(teams).toBeTruthy(); expect(teams[TestHelper.basicTeam!.id]).toBeTruthy(); }); it('getTeamsForUser', async () => { nock(Client4.getBaseRoute()). get(`/users/${TestHelper.basicUser!.id}/teams`). reply(200, [TestHelper.basicTeam]); await Actions.getTeamsForUser(TestHelper.basicUser!.id)(store.dispatch, store.getState); const teamsRequest = store.getState().requests.teams.getTeams; const {teams} = store.getState().entities.teams; if (teamsRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(teamsRequest.error)); } expect(teams).toBeTruthy(); expect(teams[TestHelper.basicTeam!.id]).toBeTruthy(); }); it('getTeams', async () => { let team = {...TestHelper.fakeTeam(), allow_open_invite: true}; nock(Client4.getBaseRoute()). post('/teams'). reply(201, {...team, id: TestHelper.generateId()}); team = await Client4.createTeam(team); nock(Client4.getBaseRoute()). get('/teams'). query(true). reply(200, [team]); await Actions.getTeams()(store.dispatch, store.getState); const teamsRequest = store.getState().requests.teams.getTeams; const {teams} = store.getState().entities.teams; if (teamsRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(teamsRequest.error)); } expect(Object.keys(teams).length > 0).toBeTruthy(); }); it('getTeams with total count', async () => { let team = {...TestHelper.fakeTeam(), allow_open_invite: true}; nock(Client4.getBaseRoute()). post('/teams'). reply(201, {...team, id: TestHelper.generateId()}); team = await Client4.createTeam(team); nock(Client4.getBaseRoute()). get('/teams'). query(true). reply(200, {teams: [team], total_count: 43}); await Actions.getTeams(0, 1, true)(store.dispatch, store.getState); const teamsRequest = store.getState().requests.teams.getTeams; const {teams, totalCount} = store.getState().entities.teams; if (teamsRequest.status === RequestStatus.FAILURE!) { throw new Error(JSON.stringify(teamsRequest.error)); } expect(Object.keys(teams).length > 0).toBeTruthy(); expect(totalCount).toEqual(43); }); it('getTeam', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const team = await Client4.createTeam(TestHelper.fakeTeam()); nock(Client4.getBaseRoute()). get(`/teams/${team.id}`). reply(200, team); await Actions.getTeam(team.id)(store.dispatch, store.getState); const state = store.getState(); const {teams} = state.entities.teams; expect(teams).toBeTruthy(); expect(teams[team.id]).toBeTruthy(); }); it('getTeamByName', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const team = await Client4.createTeam(TestHelper.fakeTeam()); nock(Client4.getBaseRoute()). get(`/teams/name/${team.name}`). reply(200, team); await Actions.getTeamByName(team.name)(store.dispatch, store.getState); const state = store.getState(); const {teams} = state.entities.teams; expect(teams).toBeTruthy(); expect(teams[team.id]).toBeTruthy(); }); it('createTeam', async () => { nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); await Actions.createTeam( TestHelper.fakeTeam(), )(store.dispatch, store.getState); const {teams, myMembers, currentTeamId} = store.getState().entities.teams; const teamId = Object.keys(teams)[0]; expect(Object.keys(teams).length).toEqual(1); expect(currentTeamId).toEqual(teamId); expect(myMembers[teamId]).toBeTruthy(); }); it('deleteTeam', async () => { const secondClient = TestHelper.createClient4(); nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, user); await secondClient.login(user.email, 'password1'); nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const secondTeam = await secondClient.createTeam( TestHelper.fakeTeam()); nock(Client4.getBaseRoute()). delete(`/teams/${secondTeam.id}`). reply(200, OK_RESPONSE); await Actions.deleteTeam( secondTeam.id, )(store.dispatch, store.getState); const {teams, myMembers} = store.getState().entities.teams; if (teams[secondTeam.id]) { throw new Error('unexpected teams[secondTeam.id]'); } if (myMembers[secondTeam.id]) { throw new Error('unexpected myMembers[secondTeam.id]'); } }); it('unarchiveTeam', async () => { const secondClient = TestHelper.createClient4(); nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, user); await secondClient.login(user.email, 'password1'); nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const secondTeam = await secondClient.createTeam( TestHelper.fakeTeam()); nock(Client4.getBaseRoute()). delete(`/teams/${secondTeam.id}`). reply(200, OK_RESPONSE); await Actions.deleteTeam( secondTeam.id, )(store.dispatch, store.getState); nock(Client4.getBaseRoute()). post(`/teams/${secondTeam.id}/restore`). reply(200, secondTeam); await Actions.unarchiveTeam( secondTeam.id, )(store.dispatch, store.getState); const {teams} = store.getState().entities.teams; expect(teams[secondTeam.id]).toEqual(secondTeam); }); it('updateTeam', async () => { const displayName = 'The Updated Team'; const description = 'This is a team created by unit tests'; const team = { ...TestHelper.basicTeam, display_name: displayName, description, }; nock(Client4.getBaseRoute()). put(`/teams/${team.id}`). reply(200, team); await Actions.updateTeam(team as Team)(store.dispatch, store.getState); const {teams} = store.getState().entities.teams; const updated = teams[TestHelper.basicTeam!.id]; expect(updated).toBeTruthy(); expect(updated.display_name).toEqual(displayName); expect(updated.description).toEqual(description); }); it('patchTeam', async () => { const displayName = 'The Patched Team'; const description = 'This is a team created by unit tests'; const team = { ...TestHelper.basicTeam, display_name: displayName, description, }; nock(Client4.getBaseRoute()). put(`/teams/${team.id}/patch`). reply(200, team); await Actions.patchTeam(team as Team)(store.dispatch, store.getState); const {teams} = store.getState().entities.teams; const patched = teams[TestHelper.basicTeam!.id]; expect(patched).toBeTruthy(); expect(patched.display_name).toEqual(displayName); expect(patched.description).toEqual(description); }); it('regenerateTeamInviteId', async () => { const patchedInviteId = TestHelper.generateId(); const team = TestHelper.basicTeam; const patchedTeam = { ...team, invite_id: patchedInviteId, }; nock(Client4.getBaseRoute()). post(`/teams/${team!.id}/regenerate_invite_id`). reply(200, patchedTeam); await Actions.regenerateTeamInviteId(team!.id)(store.dispatch, store.getState); const {teams} = store.getState().entities.teams; const patched = teams[TestHelper.basicTeam!.id]; expect(patched).toBeTruthy(); expect(patched.invite_id).not.toEqual(team!.invite_id); expect(patched.invite_id).toEqual(patchedInviteId); }); it('Join Open Team', async () => { const client = TestHelper.createClient4(); nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user = await client.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, user); await client.login(user.email, 'password1'); nock(Client4.getBaseRoute()). post('/teams'). reply(201, {...TestHelper.fakeTeamWithId(), allow_open_invite: true}); const team = await client.createTeam({...TestHelper.fakeTeam(), allow_open_invite: true}); store.dispatch({type: GeneralTypes.RECEIVED_SERVER_VERSION, data: '4.0.0'}); nock(Client4.getBaseRoute()). post('/teams/members/invite'). query(true). reply(201, {user_id: TestHelper.basicUser!.id, team_id: team.id}); nock(Client4.getBaseRoute()). get(`/teams/${team.id}`). reply(200, team); nock(Client4.getUserRoute('me')). get('/teams/members'). reply(200, [{user_id: TestHelper.basicUser!.id, roles: 'team_user', team_id: team.id}]); nock(Client4.getUserRoute('me')). get('/teams/unread'). query({params: {include_collapsed_threads: true}}). reply(200, [{team_id: team.id, msg_count: 0, mention_count: 0}]); await Actions.joinTeam(team.invite_id, team.id)(store.dispatch, store.getState); const state = store.getState(); const request = state.requests.teams.joinTeam; if (request.status !== RequestStatus.SUCCESS) { throw new Error(JSON.stringify(request.error)); } const {teams, myMembers} = state.entities.teams; expect(teams[team.id]).toBeTruthy(); expect(myMembers[team.id]).toBeTruthy(); }); it('getMyTeamMembers and getMyTeamUnreads', async () => { nock(Client4.getUserRoute('me')). get('/teams/members'). reply(200, [{user_id: TestHelper.basicUser!.id, roles: 'team_user', team_id: TestHelper.basicTeam!.id}]); await Actions.getMyTeamMembers()(store.dispatch, store.getState); nock(Client4.getUserRoute('me')). get('/teams/unread'). query({params: {include_collapsed_threads: true}}). reply(200, [{team_id: TestHelper.basicTeam!.id, msg_count: 0, mention_count: 0}]); await Actions.getMyTeamUnreads(false)(store.dispatch, store.getState); const members = store.getState().entities.teams.myMembers; const member = members[TestHelper.basicTeam!.id]; expect(member).toBeTruthy(); expect(Object.prototype.hasOwnProperty.call(member, 'mention_count')).toBeTruthy(); }); it('getTeamMembersForUser', async () => { nock(Client4.getUserRoute(TestHelper.basicUser!.id)). get('/teams/members'). reply(200, [{user_id: TestHelper.basicUser!.id, team_id: TestHelper.basicTeam!.id}]); await Actions.getTeamMembersForUser(TestHelper.basicUser!.id)(store.dispatch, store.getState); const membersInTeam = store.getState().entities.teams.membersInTeam; expect(membersInTeam).toBeTruthy(); expect(membersInTeam[TestHelper.basicTeam!.id]).toBeTruthy(); expect(membersInTeam[TestHelper.basicTeam!.id][TestHelper.basicUser!.id]).toBeTruthy(); }); it('getTeamMember', async () => { nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). get(`/teams/${TestHelper.basicTeam!.id}/members/${user.id}`). reply(200, {user_id: user.id, team_id: TestHelper.basicTeam!.id}); await Actions.getTeamMember(TestHelper.basicTeam!.id, user.id)(store.dispatch, store.getState); const members = store.getState().entities.teams.membersInTeam; expect(members[TestHelper.basicTeam!.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user.id]).toBeTruthy(); }); it('getTeamMembers', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user1 = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user2 = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). post('/members'). reply(201, {user_id: user1.id, team_id: TestHelper.basicTeam!.id}); const {data: member1} = await Actions.addUserToTeam(TestHelper.basicTeam!.id, user1.id)(store.dispatch, store.getState) as ActionResult; nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). post('/members'). reply(201, {user_id: user2.id, team_id: TestHelper.basicTeam!.id}); const {data: member2} = await Actions.addUserToTeam(TestHelper.basicTeam!.id, user2.id)(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/teams/${TestHelper.basicTeam!.id}/members`). query(true). reply(200, [member1, member2, TestHelper.basicTeamMember]); await Actions.getTeamMembers(TestHelper.basicTeam!.id, undefined, undefined, {})(store.dispatch, store.getState); const membersInTeam = store.getState().entities.teams.membersInTeam; expect(membersInTeam[TestHelper.basicTeam!.id]).toBeTruthy(); expect(membersInTeam[TestHelper.basicTeam!.id][TestHelper.basicUser!.id]).toBeTruthy(); expect(membersInTeam[TestHelper.basicTeam!.id][user1.id]).toBeTruthy(); expect(membersInTeam[TestHelper.basicTeam!.id][user2.id]).toBeTruthy(); }); it('getTeamMembersByIds', async () => { nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user1 = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user2 = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). post(`/teams/${TestHelper.basicTeam!.id}/members/ids`). reply(200, [{user_id: user1.id, team_id: TestHelper.basicTeam!.id}, {user_id: user2.id, team_id: TestHelper.basicTeam!.id}]); await Actions.getTeamMembersByIds( TestHelper.basicTeam!.id, [user1.id, user2.id], )(store.dispatch, store.getState); const members = store.getState().entities.teams.membersInTeam; expect(members[TestHelper.basicTeam!.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user1.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user2.id]).toBeTruthy(); }); it('getTeamStats', async () => { nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). get('/stats'). reply(200, {team_id: TestHelper.basicTeam!.id, total_member_count: 2605, active_member_count: 2571}); await Actions.getTeamStats(TestHelper.basicTeam!.id)(store.dispatch, store.getState); const {stats} = store.getState().entities.teams; const stat = stats[TestHelper.basicTeam!.id]; expect(stat).toBeTruthy(); expect(stat.total_member_count > 1).toBeTruthy(); expect(stat.active_member_count > 1).toBeTruthy(); }); it('addUserToTeam', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). post('/members'). reply(201, {user_id: user.id, team_id: TestHelper.basicTeam!.id}); await Actions.addUserToTeam(TestHelper.basicTeam!.id, user.id)(store.dispatch, store.getState); const members = store.getState().entities.teams.membersInTeam; expect(members[TestHelper.basicTeam!.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user.id]).toBeTruthy(); }); it('addUsersToTeam', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user2 = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). post('/members/batch'). reply(201, [{user_id: user.id, team_id: TestHelper.basicTeam!.id}, {user_id: user2.id, team_id: TestHelper.basicTeam!.id}]); await Actions.addUsersToTeam(TestHelper.basicTeam!.id, [user.id, user2.id])(store.dispatch, store.getState); const members = store.getState().entities.teams.membersInTeam; const profilesInTeam = store.getState().entities.users.profilesInTeam; expect(members[TestHelper.basicTeam!.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user2.id]).toBeTruthy(); expect(profilesInTeam[TestHelper.basicTeam!.id]).toBeTruthy(); expect(profilesInTeam[TestHelper.basicTeam!.id].has(user.id)).toBeTruthy(); expect(profilesInTeam[TestHelper.basicTeam!.id].has(user2.id)).toBeTruthy(); }); describe('removeUserFromTeam', () => { const team = {id: 'team'}; const user = {id: 'user'}; test('should remove the user from the team', async () => { store = configureStore({ entities: { teams: { membersInTeam: { [team.id]: { [user.id]: {}, }, }, }, users: { currentUserId: '', profilesInTeam: { [team.id]: [user.id], }, profilesNotInTeam: { [team.id]: [], }, }, }, }); nock(Client4.getBaseRoute()). delete(`/teams/${team.id}/members/${user.id}`). reply(200, OK_RESPONSE); await store.dispatch(Actions.removeUserFromTeam(team.id, user.id)); const state = store.getState(); expect(state.entities.teams.membersInTeam[team.id]).toEqual({}); expect(state.entities.users.profilesInTeam[team.id]).toEqual(new Set()); expect(state.entities.users.profilesNotInTeam[team.id]).toEqual(new Set([user.id])); }); test('should leave all channels when leaving a team', async () => { const channel1 = {id: 'channel1', team_id: team.id}; const channel2 = {id: 'channel2', team_id: 'team2'}; store = configureStore({ entities: { channels: { channels: { [channel1.id]: channel1, [channel2.id]: channel2, }, myMembers: { [channel1.id]: {user_id: user.id, channel_id: channel1.id}, [channel2.id]: {user_id: user.id, channel_id: channel2.id}, }, }, users: { currentUserId: user.id, }, }, }); nock(Client4.getBaseRoute()). delete(`/teams/${team.id}/members/${user.id}`). reply(200, OK_RESPONSE); await store.dispatch(Actions.removeUserFromTeam(team.id, user.id)); const state = store.getState(); expect(state.entities.channels.myMembers[channel1.id]).toBeFalsy(); expect(state.entities.channels.myMembers[channel2.id]).toBeTruthy(); }); test('should clear the current channel when leaving a team', async () => { const channel = {id: 'channel'}; store = configureStore({ entities: { channels: { channels: { [channel.id]: channel, }, myMembers: {}, }, users: { currentUserId: user.id, }, }, }); nock(Client4.getBaseRoute()). delete(`/teams/${team.id}/members/${user.id}`). reply(200, OK_RESPONSE); await store.dispatch(Actions.removeUserFromTeam(team.id, user.id)); const state = store.getState(); expect(state.entities.channels.currentChannelId).toBe(''); }); }); it('updateTeamMemberRoles', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). post('/members'). reply(201, {user_id: user.id, team_id: TestHelper.basicTeam!.id}); await Actions.addUserToTeam(TestHelper.basicTeam!.id, user.id)(store.dispatch, store.getState); const roles = General.TEAM_USER_ROLE + ' ' + General.TEAM_ADMIN_ROLE; nock(Client4.getBaseRoute()). put(`/teams/${TestHelper.basicTeam!.id}/members/${user.id}/roles`). reply(200, {user_id: user.id, team_id: TestHelper.basicTeam!.id, roles}); await Actions.updateTeamMemberRoles(TestHelper.basicTeam!.id, user.id, roles.split(' '))(store.dispatch, store.getState); const members = store.getState().entities.teams.membersInTeam; expect(members[TestHelper.basicTeam!.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user.id]).toBeTruthy(); expect(members[TestHelper.basicTeam!.id][user.id].roles).toEqual(roles.split(' ')); }); it('sendEmailInvitesToTeam', async () => { nock(Client4.getTeamRoute(TestHelper.basicTeam!.id)). post('/invite/email'). reply(200, OK_RESPONSE); const {data} = await Actions.sendEmailInvitesToTeam(TestHelper.basicTeam!.id, ['[email protected]', '[email protected]'])(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); }); it('checkIfTeamExists', async () => { nock(Client4.getBaseRoute()). get(`/teams/name/${TestHelper.basicTeam!.name}/exists`). reply(200, {exists: true}); let {data: exists} = await Actions.checkIfTeamExists(TestHelper.basicTeam!.name)(store.dispatch, store.getState) as ActionResult; expect(exists === true).toBeTruthy(); nock(Client4.getBaseRoute()). get('/teams/name/junk/exists'). reply(200, {exists: false}); const {data} = await Actions.checkIfTeamExists('junk')(store.dispatch, store.getState) as ActionResult; exists = data; expect(exists === false).toBeTruthy(); }); it('setTeamIcon', async () => { const team = {id: 'teamId', invite_id: ''}; store = configureStore({ entities: { teams: { teams: { [team!.id]: {...team}, }, }, }, }); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await loadMe()(store.dispatch, store.getState); let state = store.getState(); expect(state.entities.teams.teams[team!.id].invite_id).toEqual(''); const imageData = fs.createReadStream('src/packages/mattermost-redux/test/assets/images/test.png'); nock(Client4.getTeamRoute(team!.id)). post('/image'). reply(200, OK_RESPONSE); nock(Client4.getTeamRoute(team!.id)). get(''). reply(200, {...team, invite_id: 'inviteId'}); const {data} = await Actions.setTeamIcon(team!.id, imageData as any)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); state = store.getState(); expect(state.entities.teams.teams[team!.id].invite_id).toEqual('inviteId'); }); it('removeTeamIcon', async () => { const team = {id: 'teamId', invite_id: ''}; store = configureStore({ entities: { teams: { teams: { [team!.id]: {...team}, }, }, }, }); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await loadMe()(store.dispatch, store.getState); let state = store.getState(); expect(state.entities.teams.teams[team!.id].invite_id).toEqual(''); nock(Client4.getTeamRoute(team!.id)). delete('/image'). reply(200, OK_RESPONSE); nock(Client4.getTeamRoute(team!.id)). get(''). reply(200, {...team, invite_id: 'inviteId'}); const {data} = await Actions.removeTeamIcon(team!.id)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); state = store.getState(); expect(state.entities.teams.teams[team!.id].invite_id).toEqual('inviteId'); }); it('updateTeamScheme', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await loadMe()(store.dispatch, store.getState); const schemeId = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; const {id} = TestHelper.basicTeam!; nock(Client4.getBaseRoute()). put('/teams/' + id + '/scheme'). reply(200, OK_RESPONSE); await Actions.updateTeamScheme(id, schemeId)(store.dispatch, store.getState); const state = store.getState!(); const {teams} = state.entities.teams; const updated = teams[id]; expect(updated).toBeTruthy(); expect(updated.scheme_id).toEqual(schemeId); }); it('membersMinusGroupMembers', async () => { const teamID = 'tid10000000000000000000000'; const groupIDs = ['gid10000000000000000000000', 'gid20000000000000000000000']; const page = 4; const perPage = 63; nock(Client4.getBaseRoute()).get( `/teams/${teamID}/members_minus_group_members?group_ids=${groupIDs.join(',')}&page=${page}&per_page=${perPage}`). reply(200, {users: [], total_count: 0}); const {error} = await Actions.membersMinusGroupMembers(teamID, groupIDs, page, perPage)(store.dispatch, store.getState) as ActionResult; expect(error).toEqual(undefined); }); it('searchTeams', async () => { const userClient = TestHelper.createClient4(); nock(Client4.getBaseRoute()). post('/users'). query(true). reply(201, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, user); await userClient.login(user.email, 'password1'); nock(Client4.getBaseRoute()). post('/teams'). reply(201, TestHelper.fakeTeamWithId()); const userTeam = await userClient.createTeam( TestHelper.fakeTeam(), ); nock(Client4.getBaseRoute()). post('/teams/search'). reply(200, [TestHelper.basicTeam, userTeam]); await store.dispatch(Actions.searchTeams('test', {page: 0})); const moreRequest = store.getState().requests.teams.getTeams; if (moreRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(moreRequest.error)); } nock(Client4.getBaseRoute()). post('/teams/search'). reply(200, {teams: [TestHelper.basicTeam, userTeam], total_count: 2}); const response = await store.dispatch(Actions.searchTeams('test', {page: 0, per_page: 1})); const paginatedRequest = store.getState().requests.teams.getTeams; if (paginatedRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(paginatedRequest.error)); } expect(response.data.teams.length === 2).toBeTruthy(); }); });
3,975
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/actions/users.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import fs from 'fs'; import nock from 'nock'; import type {UserProfile} from '@mattermost/types/users'; import {UserTypes} from 'mattermost-redux/action_types'; import * as Actions from 'mattermost-redux/actions/users'; import {Client4} from 'mattermost-redux/client'; import type {ActionResult} from 'mattermost-redux/types/actions'; import deepFreeze from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../test/test_helper'; import configureStore from '../../test/test_store'; import {RequestStatus} from '../constants'; const OK_RESPONSE = {status: 'OK'}; describe('Actions.Users', () => { let store = configureStore(); beforeAll(() => { TestHelper.initBasic(Client4); }); beforeEach(() => { store = configureStore({ entities: { general: { config: { CollapsedThreads: 'always_on', }, }, }, }); Client4.setUserId(''); Client4.setUserRoles(''); }); afterEach(() => { nock.cleanAll(); }); afterAll(() => { TestHelper.tearDown(); }); it('createUser', async () => { const userToCreate = TestHelper.fakeUser(); nock(Client4.getBaseRoute()). post('/users'). reply(201, {...userToCreate, id: TestHelper.generateId()}); const {data: user} = await Actions.createUser(userToCreate, '', '', '')(store.dispatch, store.getState) as ActionResult; const state = store.getState(); const {profiles} = state.entities.users; expect(profiles).toBeTruthy(); expect(profiles[user.id]).toBeTruthy(); }); it('getTermsOfService', async () => { const response = { create_at: 1537976679426, id: '1234', text: 'Terms of Service', user_id: '1', }; nock(Client4.getBaseRoute()). get('/terms_of_service'). reply(200, response); const {data} = await Actions.getTermsOfService()(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(response); }); it('updateMyTermsOfServiceStatus accept terms', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(201, {...TestHelper.fakeUserWithId()}); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); nock(Client4.getBaseRoute()). post('/users/me/terms_of_service'). reply(200, OK_RESPONSE); await Actions.updateMyTermsOfServiceStatus('1', true)(store.dispatch, store.getState); const {currentUserId} = store.getState().entities.users; const currentUser = store.getState().entities.users.profiles[currentUserId]; expect(currentUserId).toBeTruthy(); expect(currentUser.terms_of_service_id).toBeTruthy(); expect(currentUser.terms_of_service_create_at).toBeTruthy(); expect(currentUser.terms_of_service_id).toEqual('1'); }); it('updateMyTermsOfServiceStatus reject terms', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(201, {...TestHelper.fakeUserWithId()}); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); nock(Client4.getBaseRoute()). post('/users/me/terms_of_service'). reply(200, OK_RESPONSE); await Actions.updateMyTermsOfServiceStatus('1', false)(store.dispatch, store.getState); const {currentUserId, myAcceptedTermsOfServiceId} = store.getState().entities.users; expect(currentUserId).toBeTruthy(); expect(myAcceptedTermsOfServiceId).not.toEqual('1'); }); it('logout', async () => { nock(Client4.getBaseRoute()). post('/users/logout'). reply(200, OK_RESPONSE); await Actions.logout()(store.dispatch, store.getState); const state = store.getState(); const logoutRequest = state.requests.users.logout; const general = state.entities.general; const users = state.entities.users; const teams = state.entities.teams; const channels = state.entities.channels; const posts = state.entities.posts; const preferences = state.entities.preferences; if (logoutRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(logoutRequest.error)); } // config not empty expect(general.config).toEqual({}); // license not empty expect(general.license).toEqual({}); // current user id not empty expect(users.currentUserId).toEqual(''); // user sessions not empty expect(users.mySessions).toEqual([]); // user audits not empty expect(users.myAudits).toEqual([]); // user profiles not empty expect(users.profiles).toEqual({}); // users profiles in team not empty expect(users.profilesInTeam).toEqual({}); // users profiles in channel not empty expect(users.profilesInChannel).toEqual({}); // users profiles NOT in channel not empty expect(users.profilesNotInChannel).toEqual({}); // users statuses not empty expect(users.statuses).toEqual({}); // current team id is not empty expect(teams.currentTeamId).toEqual(''); // teams is not empty expect(teams.teams).toEqual({}); // team members is not empty expect(teams.myMembers).toEqual({}); // members in team is not empty expect(teams.membersInTeam).toEqual({}); // team stats is not empty expect(teams.stats).toEqual({}); // current channel id is not empty expect(channels.currentChannelId).toEqual(''); // channels is not empty expect(channels.channels).toEqual({}); // channelsInTeam is not empty expect(channels.channelsInTeam).toEqual({}); // channel members is not empty expect(channels.myMembers).toEqual({}); // channel stats is not empty expect(channels.stats).toEqual({}); // selected post id is not empty expect(posts.selectedPostId).toEqual(''); // current focused post id is not empty expect(posts.currentFocusedPostId).toEqual(''); // posts is not empty expect(posts.posts).toEqual({}); // posts by channel is not empty expect(posts.postsInChannel).toEqual({}); // user preferences not empty expect(preferences.myPreferences).toEqual({}); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, TestHelper.basicUser!); await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); }); it('getProfiles', async () => { nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [TestHelper.basicUser]); await Actions.getProfiles(0)(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; expect(Object.keys(profiles).length).toBeTruthy(); }); it('getProfilesByIds', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). post('/users/ids'). reply(200, [user]); await Actions.getProfilesByIds([user.id])(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; expect(profiles[user.id]).toBeTruthy(); }); it('getMissingProfilesByIds', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). post('/users/ids'). reply(200, [user]); await Actions.getMissingProfilesByIds([user.id])(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; expect(profiles[user.id]).toBeTruthy(); }); it('getProfilesByUsernames', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). post('/users/usernames'). reply(200, [user]); await Actions.getProfilesByUsernames([user.username])(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; expect(profiles[user.id]).toBeTruthy(); }); it('getProfilesInTeam', async () => { nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [TestHelper.basicUser]); await Actions.getProfilesInTeam(TestHelper.basicTeam!.id, 0)(store.dispatch, store.getState); const {profilesInTeam, profiles} = store.getState().entities.users; const team = profilesInTeam[TestHelper.basicTeam!.id]; expect(team).toBeTruthy(); expect(team.has(TestHelper.basicUser!.id)).toBeTruthy(); // profiles != profiles in team expect(Object.keys(profiles).length).toEqual(team.size); }); it('getProfilesNotInTeam', async () => { const team = TestHelper.basicTeam; nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [user]); await Actions.getProfilesNotInTeam(team!.id, false, 0)(store.dispatch, store.getState); const {profilesNotInTeam} = store.getState().entities.users; const notInTeam = profilesNotInTeam[team!.id]; expect(notInTeam).toBeTruthy(); expect(notInTeam.size > 0).toBeTruthy(); }); it('getProfilesWithoutTeam', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [user]); await Actions.getProfilesWithoutTeam(0)(store.dispatch, store.getState); const {profilesWithoutTeam, profiles} = store.getState().entities.users; expect(profilesWithoutTeam).toBeTruthy(); expect(profilesWithoutTeam.size > 0).toBeTruthy(); expect(profiles).toBeTruthy(); expect(Object.keys(profiles).length > 0).toBeTruthy(); }); it('getProfilesInChannel', async () => { nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [TestHelper.basicUser]); await Actions.getProfilesInChannel( TestHelper.basicChannel!.id, 0, )(store.dispatch, store.getState); const {profiles, profilesInChannel} = store.getState().entities.users; const channel = profilesInChannel[TestHelper.basicChannel!.id]; expect(channel.has(TestHelper.basicUser!.id)).toBeTruthy(); // profiles != profiles in channel expect(Object.keys(profiles).length).toEqual(channel.size); }); it('getProfilesNotInChannel', async () => { nock(Client4.getBaseRoute()). post('/users'). query(true). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [user]); await Actions.getProfilesNotInChannel( TestHelper.basicTeam!.id, TestHelper.basicChannel!.id, false, 0, )(store.dispatch, store.getState); const {profiles, profilesNotInChannel} = store.getState().entities.users; const channel = profilesNotInChannel[TestHelper.basicChannel!.id]; expect(channel.has(user.id)).toBeTruthy(); // profiles != profiles in channel expect(Object.keys(profiles).length).toEqual(channel.size); }); it('getProfilesInGroup', async () => { nock(Client4.getBaseRoute()). get('/users'). query(true). reply(200, [TestHelper.basicUser]); await Actions.getProfilesInGroup(TestHelper.basicGroup!.id, 0)(store.dispatch, store.getState); const {profilesInGroup, profiles} = store.getState().entities.users; const group = profilesInGroup[TestHelper.basicGroup!.id]; expect(group).toBeTruthy(); expect(group.has(TestHelper.basicUser!.id)).toBeTruthy(); // profiles != profiles in group expect(Object.keys(profiles).length).toEqual(group.size); }); it('getUser', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). get(`/users/${user.id}`). reply(200, user); await Actions.getUser( user.id, )(store.dispatch, store.getState); const state = store.getState(); const {profiles} = state.entities.users; expect(profiles[user.id]).toBeTruthy(); expect(profiles[user.id].id).toEqual(user.id); }); it('getMe', async () => { nock(Client4.getBaseRoute()). get('/users/me'). reply(200, TestHelper.basicUser!); await Actions.getMe()(store.dispatch, store.getState); const state = store.getState(); const {profiles, currentUserId} = state.entities.users; expect(profiles[currentUserId]).toBeTruthy(); expect(profiles[currentUserId].id).toEqual(currentUserId); }); it('getUserByUsername', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). get(`/users/username/${user.username}`). reply(200, user); await Actions.getUserByUsername( user.username, )(store.dispatch, store.getState); const state = store.getState(); const {profiles} = state.entities.users; expect(profiles[user.id]).toBeTruthy(); expect(profiles[user.id].username).toEqual(user.username); }); it('getUserByEmail', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser(TestHelper.fakeUser(), '', ''); nock(Client4.getBaseRoute()). get(`/users/email/${user.email}`). reply(200, user); await Actions.getUserByEmail( user.email, )(store.dispatch, store.getState); const state = store.getState(); const {profiles} = state.entities.users; expect(profiles[user.id]).toBeTruthy(); expect(profiles[user.id].email).toEqual(user.email); }); it('searchProfiles', async () => { const user = TestHelper.basicUser; nock(Client4.getBaseRoute()). post('/users/search'). reply(200, [user]); await Actions.searchProfiles( user!.username, )(store.dispatch, store.getState); const state = store.getState(); const {profiles} = state.entities.users; expect(profiles[user!.id]).toBeTruthy(); expect(profiles[user!.id].id).toEqual(user!.id); }); it('getStatusesByIds', async () => { nock(Client4.getBaseRoute()). post('/users/status/ids'). reply(200, [{user_id: TestHelper.basicUser!.id, status: 'online', manual: false, last_activity_at: 1507662212199}]); await Actions.getStatusesByIds( [TestHelper.basicUser!.id], )(store.dispatch, store.getState); const statuses = store.getState().entities.users.statuses; expect(statuses[TestHelper.basicUser!.id]).toBeTruthy(); expect(Object.keys(statuses).length).toEqual(1); }); it('getTotalUsersStats', async () => { nock(Client4.getBaseRoute()). get('/users/stats'). reply(200, {total_users_count: 2605}); await Actions.getTotalUsersStats()(store.dispatch, store.getState); const {stats} = store.getState().entities.users; expect(stats.total_users_count).toEqual(2605); }); it('getStatus', async () => { const user = TestHelper.basicUser; nock(Client4.getBaseRoute()). get(`/users/${user!.id}/status`). reply(200, {user_id: user!.id, status: 'online', manual: false, last_activity_at: 1507662212199}); await Actions.getStatus( user!.id, )(store.dispatch, store.getState); const statuses = store.getState().entities.users.statuses; expect(statuses[user!.id]).toBeTruthy(); }); it('setStatus', async () => { nock(Client4.getBaseRoute()). put(`/users/${TestHelper.basicUser!.id}/status`). reply(200, OK_RESPONSE); await Actions.setStatus( {user_id: TestHelper.basicUser!.id, status: 'away'}, )(store.dispatch, store.getState); const statuses = store.getState().entities.users.statuses; expect(statuses[TestHelper.basicUser!.id] === 'away').toBeTruthy(); }); it('getSessions', async () => { nock(Client4.getBaseRoute()). get(`/users/${TestHelper.basicUser!.id}/sessions`). reply(200, [{id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}]); await Actions.getSessions(TestHelper.basicUser!.id)(store.dispatch, store.getState); const sessions = store.getState().entities.users.mySessions; expect(sessions.length).toBeTruthy(); expect(sessions[0].user_id).toEqual(TestHelper.basicUser!.id); }); it('revokeSession', async () => { nock(Client4.getBaseRoute()). get(`/users/${TestHelper.basicUser!.id}/sessions`). reply(200, [{id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}]); await Actions.getSessions(TestHelper.basicUser!.id)(store.dispatch, store.getState); let sessions = store.getState().entities.users.mySessions; const sessionsLength = sessions.length; nock(Client4.getBaseRoute()). post(`/users/${TestHelper.basicUser!.id}/sessions/revoke`). reply(200, OK_RESPONSE); await Actions.revokeSession(TestHelper.basicUser!.id, sessions[0].id)(store.dispatch, store.getState); sessions = store.getState().entities.users.mySessions; expect(sessions.length === sessionsLength - 1).toBeTruthy(); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, TestHelper.basicUser!); await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); }); it('revokeSession and logout', async () => { nock(Client4.getBaseRoute()). get(`/users/${TestHelper.basicUser!.id}/sessions`). reply(200, [{id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}]); await Actions.getSessions(TestHelper.basicUser!.id)(store.dispatch, store.getState); const sessions = store.getState().entities.users.mySessions; nock(Client4.getBaseRoute()). post(`/users/${TestHelper.basicUser!.id}/sessions/revoke`). reply(200, OK_RESPONSE); const {data: revokeSessionResponse} = await Actions.revokeSession(TestHelper.basicUser!.id, sessions[0].id)(store.dispatch, store.getState) as ActionResult; expect(revokeSessionResponse).toBe(true); nock(Client4.getBaseRoute()). get('/users'). reply(401, {}); await Actions.getProfiles(0)(store.dispatch, store.getState); const basicUser = TestHelper.basicUser; nock(Client4.getBaseRoute()). post('/users/login'). reply(200, basicUser!); const response = await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); expect(response.email).toEqual(basicUser!.email); }); it('revokeAllSessionsForCurrentUser', async () => { const user = TestHelper.basicUser; nock(Client4.getBaseRoute()). post('/users/logout'). reply(200, OK_RESPONSE); await TestHelper.basicClient4!.logout(); let sessions = store.getState().entities.users.mySessions; expect(sessions.length).toBe(0); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, TestHelper.basicUser!); await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); nock(Client4.getBaseRoute()). get(`/users/${user!.id}/sessions`). reply(200, [{id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}, {id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}]); await Actions.getSessions(user!.id)(store.dispatch, store.getState); sessions = store.getState().entities.users.mySessions; expect(sessions.length > 1).toBeTruthy(); nock(Client4.getBaseRoute()). post(`/users/${user!.id}/sessions/revoke/all`). reply(200, OK_RESPONSE); const {data} = await Actions.revokeAllSessionsForUser(user!.id)(store.dispatch, store.getState) as ActionResult; expect(data).toBe(true); nock(Client4.getBaseRoute()). get('/users'). query(true). reply(401, {}); await Actions.getProfiles(0)(store.dispatch, store.getState); const logoutRequest = store.getState().requests.users.logout; if (logoutRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(logoutRequest.error)); } sessions = store.getState().entities.users.mySessions; expect(sessions.length).toBe(0); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, TestHelper.basicUser!); await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); }); it('revokeSessionsForAllUsers', async () => { const user = TestHelper.basicUser; nock(Client4.getBaseRoute()). post('/users/logout'). reply(200, OK_RESPONSE); await TestHelper.basicClient4!.logout(); let sessions = store.getState().entities.users.mySessions; expect(sessions.length).toBe(0); TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, TestHelper.basicUser!); await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); nock(Client4.getBaseRoute()). get(`/users/${user!.id}/sessions`). reply(200, [{id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}, {id: TestHelper.generateId(), create_at: 1507756921338, expires_at: 1510348921338, last_activity_at: 1507821125630, user_id: TestHelper.basicUser!.id, device_id: '', roles: 'system_admin system_user'}]); await Actions.getSessions(user!.id)(store.dispatch, store.getState); sessions = store.getState().entities.users.mySessions; expect(sessions.length > 1).toBeTruthy(); nock(Client4.getBaseRoute()). post('/users/sessions/revoke/all'). reply(200, OK_RESPONSE); const {data} = await Actions.revokeSessionsForAllUsers()(store.dispatch, store.getState) as ActionResult; expect(data).toBe(true); nock(Client4.getBaseRoute()). get('/users'). query(true). reply(401, {}); await Actions.getProfiles(0)(store.dispatch, store.getState); const logoutRequest = store.getState().requests.users.logout; if (logoutRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(logoutRequest.error)); } sessions = store.getState().entities.users.mySessions; expect(sessions.length).toBe(0); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, TestHelper.basicUser!); await TestHelper.basicClient4!.login(TestHelper.basicUser!.email, 'password1'); }); it('getUserAudits', async () => { nock(Client4.getBaseRoute()). get(`/users/${TestHelper.basicUser!.id}/audits`). query(true). reply(200, [{id: TestHelper.generateId(), create_at: 1497285546645, user_id: TestHelper.basicUser!.id, action: '/api/v4/users/login', extra_info: 'success', ip_address: '::1', session_id: ''}]); await Actions.getUserAudits(TestHelper.basicUser!.id)(store.dispatch, store.getState); const audits = store.getState().entities.users.myAudits; expect(audits.length).toBeTruthy(); expect(audits[0].user_id).toEqual(TestHelper.basicUser!.id); }); it('autocompleteUsers', async () => { nock(Client4.getBaseRoute()). post('/users'). query(true). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). get('/users/autocomplete'). query(true). reply(200, {users: [TestHelper.basicUser], out_of_channel: [user]}); await Actions.autocompleteUsers( '', TestHelper.basicTeam!.id, TestHelper.basicChannel!.id, )(store.dispatch, store.getState); const autocompleteRequest = store.getState().requests.users.autocompleteUsers; const {profiles, profilesNotInChannel, profilesInChannel} = store.getState().entities.users; if (autocompleteRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(autocompleteRequest.error)); } const notInChannel = profilesNotInChannel[TestHelper.basicChannel!.id]; const inChannel = profilesInChannel[TestHelper.basicChannel!.id]; expect(notInChannel.has(user.id)).toBeTruthy(); expect(inChannel.has(TestHelper.basicUser!.id)).toBeTruthy(); expect(profiles[user.id]).toBeTruthy(); }); it('autocompleteUsers without out_of_channel', async () => { nock(Client4.getBaseRoute()). post('/users'). query(true). reply(200, TestHelper.fakeUserWithId()); const user = await TestHelper.basicClient4!.createUser( TestHelper.fakeUser(), '', '', TestHelper.basicTeam!.invite_id, ); nock(Client4.getBaseRoute()). get('/users/autocomplete'). query(true). reply(200, {users: [user]}); await Actions.autocompleteUsers( '', TestHelper.basicTeam!.id, TestHelper.basicChannel!.id, )(store.dispatch, store.getState); const autocompleteRequest = store.getState().requests.users.autocompleteUsers; const {profiles, profilesNotInChannel, profilesInChannel} = store.getState().entities.users; if (autocompleteRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(autocompleteRequest.error)); } const notInChannel = profilesNotInChannel[TestHelper.basicChannel!.id]; const inChannel = profilesInChannel[TestHelper.basicChannel!.id]; expect(notInChannel).toBe(undefined); expect(inChannel.has(user.id)).toBeTruthy(); expect(profiles[user.id]).toBeTruthy(); }); it('updateMe', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const state = store.getState(); const currentUser = state.entities.users.profiles[state.entities.users.currentUserId]; const notifyProps = currentUser.notify_props; nock(Client4.getBaseRoute()). put('/users/me/patch'). query(true). reply(200, { ...currentUser, notify_props: { ...notifyProps, comments: 'any', email: 'false', first_name: 'false', mention_keys: '', user_id: currentUser.id, }, }); await Actions.updateMe({ notify_props: { ...notifyProps, comments: 'any', email: 'false', first_name: 'false', mention_keys: '', user_id: currentUser.id, }, } as UserProfile)(store.dispatch, store.getState); const updateRequest = store.getState().requests.users.updateMe; const {currentUserId, profiles} = store.getState().entities.users; const updateNotifyProps = profiles[currentUserId].notify_props; if (updateRequest.status === RequestStatus.FAILURE) { throw new Error(JSON.stringify(updateRequest.error)); } expect(updateNotifyProps.comments).toBe('any'); expect(updateNotifyProps.email).toBe('false'); expect(updateNotifyProps.first_name).toBe('false'); expect(updateNotifyProps.mention_keys).toBe(''); }); it('patchUser', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const state = store.getState(); const currentUserId = state.entities.users.currentUserId; const currentUser = state.entities.users.profiles[currentUserId]; const notifyProps = currentUser.notify_props; nock(Client4.getBaseRoute()). put(`/users/${currentUserId}/patch`). query(true). reply(200, { ...currentUser, notify_props: { ...notifyProps, comments: 'any', email: 'false', first_name: 'false', mention_keys: '', user_id: currentUser.id, }, }); await Actions.patchUser({ id: currentUserId, notify_props: { ...notifyProps, comments: 'any', email: 'false', first_name: 'false', mention_keys: '', user_id: currentUser.id, }, } as UserProfile)(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; const updateNotifyProps = profiles[currentUserId].notify_props; expect(updateNotifyProps.comments).toBe('any'); expect(updateNotifyProps.email).toBe('false'); expect(updateNotifyProps.first_name).toBe('false'); expect(updateNotifyProps.mention_keys).toBe(''); }); it('updateUserRoles', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). put(`/users/${currentUserId}/roles`). reply(200, OK_RESPONSE); await Actions.updateUserRoles(currentUserId, 'system_user system_admin')(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; const currentUserRoles = profiles[currentUserId].roles; expect(currentUserRoles).toBe('system_user system_admin'); }); it('updateUserMfa', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). put(`/users/${currentUserId}/mfa`). reply(200, OK_RESPONSE); await Actions.updateUserMfa(currentUserId, false, '')(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; const currentUserMfa = profiles[currentUserId].mfa_active; expect(currentUserMfa).toBe(false); }); it('updateUserPassword', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const beforeTime = new Date().getTime(); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). put(`/users/${currentUserId}/password`). reply(200, OK_RESPONSE); await Actions.updateUserPassword(currentUserId, 'password1', 'password1')(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; const currentUser = profiles[currentUserId]; expect(currentUser).toBeTruthy(); expect(currentUser.last_password_update_at > beforeTime).toBeTruthy(); }); it('generateMfaSecret', async () => { const response = {secret: 'somesecret', qr_code: 'someqrcode'}; nock(Client4.getBaseRoute()). post('/users/me/mfa/generate'). reply(200, response); const {data} = await Actions.generateMfaSecret('me')(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(response); }); it('updateUserActive', async () => { nock(Client4.getBaseRoute()). post('/users'). reply(200, TestHelper.fakeUserWithId()); const {data: user} = await Actions.createUser(TestHelper.fakeUser(), '', '', '')(store.dispatch, store.getState) as ActionResult; const beforeTime = new Date().getTime(); nock(Client4.getBaseRoute()). put(`/users/${user.id}/active`). reply(200, OK_RESPONSE); await Actions.updateUserActive(user.id, false)(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; expect(profiles[user.id]).toBeTruthy(); expect(profiles[user.id].delete_at > beforeTime).toBeTruthy(); }); it('verifyUserEmail', async () => { nock(Client4.getBaseRoute()). post('/users/email/verify'). reply(200, OK_RESPONSE); const {data} = await Actions.verifyUserEmail('sometoken')(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); }); it('sendVerificationEmail', async () => { nock(Client4.getBaseRoute()). post('/users/email/verify/send'). reply(200, OK_RESPONSE); const {data} = await Actions.sendVerificationEmail(TestHelper.basicUser!.email)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); }); it('resetUserPassword', async () => { nock(Client4.getBaseRoute()). post('/users/password/reset'). reply(200, OK_RESPONSE); const {data} = await Actions.resetUserPassword('sometoken', 'newpassword')(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); }); it('sendPasswordResetEmail', async () => { nock(Client4.getBaseRoute()). post('/users/password/reset/send'). reply(200, OK_RESPONSE); const {data} = await Actions.sendPasswordResetEmail(TestHelper.basicUser!.email)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual(OK_RESPONSE); }); it('uploadProfileImage', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const testImageData = fs.createReadStream('src/packages/mattermost-redux/test/assets/images/test.png'); const beforeTime = new Date().getTime(); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${TestHelper.basicUser!.id}/image`). reply(200, OK_RESPONSE); await Actions.uploadProfileImage(currentUserId, testImageData)(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; const currentUser = profiles[currentUserId]; expect(currentUser).toBeTruthy(); expect(currentUser.last_picture_update > beforeTime).toBeTruthy(); }); it('setDefaultProfileImage', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). delete(`/users/${TestHelper.basicUser!.id}/image`). reply(200, OK_RESPONSE); await Actions.setDefaultProfileImage(currentUserId)(store.dispatch, store.getState); const {profiles} = store.getState().entities.users; const currentUser = profiles[currentUserId]; expect(currentUser).toBeTruthy(); expect(currentUser.last_picture_update).toBe(0); }); it('switchEmailToOAuth', async () => { nock(Client4.getBaseRoute()). post('/users/login/switch'). reply(200, {follow_link: '/login'}); const {data} = await Actions.switchEmailToOAuth('gitlab', TestHelper.basicUser!.email, TestHelper.basicUser!.password)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual({follow_link: '/login'}); }); it('switchOAuthToEmail', async () => { nock(Client4.getBaseRoute()). post('/users/login/switch'). reply(200, {follow_link: '/login'}); const {data} = await Actions.switchOAuthToEmail('gitlab', TestHelper.basicUser!.email, TestHelper.basicUser!.password)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual({follow_link: '/login'}); }); it('switchEmailToLdap', async () => { nock(Client4.getBaseRoute()). post('/users/login/switch'). reply(200, {follow_link: '/login'}); const {data} = await Actions.switchEmailToLdap(TestHelper.basicUser!.email, TestHelper.basicUser!.password, 'someid', 'somepassword')(store.dispatch, store.getState) as ActionResult; expect(data).toEqual({follow_link: '/login'}); }); it('switchLdapToEmail', (done) => { async function test() { nock(Client4.getBaseRoute()). post('/users/login/switch'). reply(200, {follow_link: '/login'}); const {data} = await Actions.switchLdapToEmail('somepassword', TestHelper.basicUser!.email, TestHelper.basicUser!.password)(store.dispatch, store.getState) as ActionResult; expect(data).toEqual({follow_link: '/login'}); done(); } test(); }); it('createUserAccessToken', (done) => { async function test() { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; const {myUserAccessTokens} = store.getState().entities.users; const {userAccessTokensByUser} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[data.id]).toBeTruthy(); expect(!myUserAccessTokens[data.id].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][data.id]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][data.id].token).toBeTruthy(); done(); } test(); }); it('getUserAccessToken', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/users/tokens/${data.id}`). reply(200, {id: data.id, description: 'test token', user_id: currentUserId}); await Actions.getUserAccessToken(data.id)(store.dispatch, store.getState); const {myUserAccessTokens} = store.getState().entities.users; const {userAccessTokensByUser, userAccessTokens} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[data.id]).toBeTruthy(); expect(!myUserAccessTokens[data.id].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][data.id]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][data.id].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[data.id]).toBeTruthy(); expect(!userAccessTokens[data.id].token).toBeTruthy(); }); it('getUserAccessTokens', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get('/users/tokens'). query(true). reply(200, [{id: data.id, description: 'test token', user_id: currentUserId}]); await Actions.getUserAccessTokens()(store.dispatch, store.getState); const {myUserAccessTokens} = store.getState().entities.users; const {userAccessTokensByUser, userAccessTokens} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[data.id]).toBeTruthy(); expect(!myUserAccessTokens[data.id].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][data.id]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][data.id].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[data.id]).toBeTruthy(); expect(!userAccessTokens[data.id].token).toBeTruthy(); }); it('getUserAccessTokensForUser', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; nock(Client4.getBaseRoute()). get(`/users/${currentUserId}/tokens`). query(true). reply(200, [{id: data.id, description: 'test token', user_id: currentUserId}]); await Actions.getUserAccessTokensForUser(currentUserId)(store.dispatch, store.getState); const {myUserAccessTokens} = store.getState().entities.users; const {userAccessTokensByUser, userAccessTokens} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[data.id]).toBeTruthy(); expect(!myUserAccessTokens[data.id].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][data.id]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][data.id].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[data.id]).toBeTruthy(); expect(!userAccessTokens[data.id].token).toBeTruthy(); }); it('revokeUserAccessToken', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; let {myUserAccessTokens} = store.getState().entities.users; let {userAccessTokensByUser, userAccessTokens} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[data.id]).toBeTruthy(); expect(!myUserAccessTokens[data.id].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][data.id]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][data.id].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[data.id]).toBeTruthy(); expect(!userAccessTokens[data.id].token).toBeTruthy(); nock(Client4.getBaseRoute()). post('/users/tokens/revoke'). reply(200, OK_RESPONSE); await Actions.revokeUserAccessToken(data.id)(store.dispatch, store.getState); myUserAccessTokens = store.getState().entities.users.myUserAccessTokens; userAccessTokensByUser = store.getState().entities.admin.userAccessTokensByUser; userAccessTokens = store.getState().entities.admin.userAccessTokens; expect(myUserAccessTokens).toBeTruthy(); expect(!myUserAccessTokens[data.id]).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][data.id]).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(!userAccessTokens[data.id]).toBeTruthy(); }); it('disableUserAccessToken', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; const testId = data.id; let {myUserAccessTokens} = store.getState().entities.users; let {userAccessTokensByUser, userAccessTokens} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[testId]).toBeTruthy(); expect(!myUserAccessTokens[testId].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][testId]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][testId].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[data.id]).toBeTruthy(); expect(!userAccessTokens[data.id].token).toBeTruthy(); nock(Client4.getBaseRoute()). post('/users/tokens/disable'). reply(200, OK_RESPONSE); await Actions.disableUserAccessToken(testId)(store.dispatch, store.getState); myUserAccessTokens = store.getState().entities.users.myUserAccessTokens; userAccessTokensByUser = store.getState().entities.admin.userAccessTokensByUser; userAccessTokens = store.getState().entities.admin.userAccessTokens; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[testId]).toBeTruthy(); expect(!myUserAccessTokens[testId].is_active).toBeTruthy(); expect(!myUserAccessTokens[testId].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][testId]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][testId].is_active).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][testId].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[testId]).toBeTruthy(); expect(!userAccessTokens[testId].is_active).toBeTruthy(); expect(!userAccessTokens[testId].token).toBeTruthy(); }); it('enableUserAccessToken', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); const {data} = await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState) as ActionResult; const testId = data.id; let {myUserAccessTokens} = store.getState().entities.users; let {userAccessTokensByUser, userAccessTokens} = store.getState().entities.admin; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[testId]).toBeTruthy(); expect(!myUserAccessTokens[testId].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][testId]).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][testId].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[testId]).toBeTruthy(); expect(!userAccessTokens[testId].token).toBeTruthy(); nock(Client4.getBaseRoute()). post('/users/tokens/enable'). reply(200, OK_RESPONSE); await Actions.enableUserAccessToken(testId)(store.dispatch, store.getState); myUserAccessTokens = store.getState().entities.users.myUserAccessTokens; userAccessTokensByUser = store.getState().entities.admin.userAccessTokensByUser; userAccessTokens = store.getState().entities.admin.userAccessTokens; expect(myUserAccessTokens).toBeTruthy(); expect(myUserAccessTokens[testId]).toBeTruthy(); expect(myUserAccessTokens[testId].is_active).toBeTruthy(); expect(!myUserAccessTokens[testId].token).toBeTruthy(); expect(userAccessTokensByUser).toBeTruthy(); expect(userAccessTokensByUser[currentUserId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][testId]).toBeTruthy(); expect(userAccessTokensByUser[currentUserId][testId].is_active).toBeTruthy(); expect(!userAccessTokensByUser[currentUserId][testId].token).toBeTruthy(); expect(userAccessTokens).toBeTruthy(); expect(userAccessTokens[testId]).toBeTruthy(); expect(userAccessTokens[testId].is_active).toBeTruthy(); expect(!userAccessTokens[testId].token).toBeTruthy(); }); it('clearUserAccessTokens', async () => { TestHelper.mockLogin(); store.dispatch({ type: UserTypes.LOGIN_SUCCESS, }); await Actions.loadMe()(store.dispatch, store.getState); const currentUserId = store.getState().entities.users.currentUserId; nock(Client4.getBaseRoute()). post(`/users/${currentUserId}/tokens`). reply(201, {id: 'someid', token: 'sometoken', description: 'test token', user_id: currentUserId}); await Actions.createUserAccessToken(currentUserId, 'test token')(store.dispatch, store.getState); await Actions.clearUserAccessTokens()(store.dispatch, store.getState); const {myUserAccessTokens} = store.getState().entities.users; expect(Object.values(myUserAccessTokens).length === 0).toBeTruthy(); }); describe('checkForModifiedUsers', () => { test('should request users by IDs that have changed since the last websocket disconnect', async () => { const lastDisconnectAt = 1500; const user1 = {id: 'user1', update_at: 1000}; const user2 = {id: 'user2', update_at: 1000}; nock(Client4.getBaseRoute()). post('/users/ids'). query({since: lastDisconnectAt}). reply(200, [{...user2, update_at: 2000}]); store = configureStore({ entities: { general: { serverVersion: '5.14.0', }, users: { profiles: { user1, user2, }, }, }, websocket: { lastDisconnectAt, }, }); await store.dispatch(Actions.checkForModifiedUsers()); const profiles = store.getState().entities.users.profiles; expect(profiles.user1).toBe(user1); expect(profiles.user2).not.toBe(user2); expect(profiles.user2).toEqual({id: 'user2', update_at: 2000}); }); test('should do nothing on older servers', async () => { const lastDisconnectAt = 1500; const originalState = deepFreeze({ entities: { general: { serverVersion: '5.13.0', }, users: { profiles: {}, }, }, websocket: { lastDisconnectAt, }, }); store = configureStore(originalState); await store.dispatch(Actions.checkForModifiedUsers()); const profiles = store.getState().entities.users.profiles; expect(profiles).toBe(originalState.entities.users.profiles); }); }); });
4,003
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/admin.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {AdminTypes, UserTypes} from 'mattermost-redux/action_types'; import PluginState from 'mattermost-redux/constants/plugins'; import reducer, {convertAnalyticsRowsToStats} from 'mattermost-redux/reducers/entities/admin'; import type {GenericAction} from 'mattermost-redux/types/actions'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; type ReducerState = ReturnType<typeof reducer>; describe('reducers.entities.admin', () => { describe('pluginStatuses', () => { it('initial state', () => { const state = {}; const action = {}; const expectedState = {}; const actualState = reducer({pluginStatuses: state} as ReducerState, action as GenericAction); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('RECEIVED_PLUGIN_STATUSES, empty initial state', () => { const state = {}; const action = { type: AdminTypes.RECEIVED_PLUGIN_STATUSES, data: [ { plugin_id: 'plugin_0', cluster_id: 'cluster_id_1', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: 'some error', name: 'Plugin 0', description: 'The plugin 0.', }, { plugin_id: 'plugin_1', cluster_id: 'cluster_id_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin.', }, { plugin_id: 'plugin_1', cluster_id: 'cluster_id_2', version: '0.0.2', state: PluginState.PLUGIN_STATE_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin, different description.', }, ], }; const expectedState = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: 'some error', name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('RECEIVED_PLUGIN_STATUSES, previously populated state', () => { const state = { plugin_0: { id: 'plugin_0', version: '0.1.0-old', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: 'existing error', name: 'Plugin 0 - old', description: 'The plugin 0 - old.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, ], }, }; const action = { type: AdminTypes.RECEIVED_PLUGIN_STATUSES, data: [ { plugin_id: 'plugin_0', cluster_id: 'cluster_id_1', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: '', name: 'Plugin 0', description: 'The plugin 0.', }, { plugin_id: 'plugin_1', cluster_id: 'cluster_id_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin.', }, { plugin_id: 'plugin_1', cluster_id: 'cluster_id_2', version: '0.0.2', state: PluginState.PLUGIN_STATE_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin, different description.', }, ], }; const expectedState = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, error: '', name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, error: '', name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('ENABLE_PLUGIN_REQUEST, plugin_0', () => { const state = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const action = { type: AdminTypes.ENABLE_PLUGIN_REQUEST, data: 'plugin_0', }; const expectedState = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_STARTING, name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('DISABLE_PLUGIN_REQUEST, plugin_0', () => { const state = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const action = { type: AdminTypes.DISABLE_PLUGIN_REQUEST, data: 'plugin_0', }; const expectedState = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_STOPPING, name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('DISABLE_PLUGIN_REQUEST, plugin_1', () => { const state = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const action = { type: AdminTypes.DISABLE_PLUGIN_REQUEST, data: 'plugin_1', }; const expectedState = { plugin_0: { id: 'plugin_0', version: '0.1.0', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 0', description: 'The plugin 0.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_STOPPING, name: 'Plugin 1', description: 'The plugin.', active: true, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, { cluster_id: 'cluster_id_2', state: PluginState.PLUGIN_STATE_RUNNING, version: '0.0.2', }, ], }, }; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('REMOVED_PLUGIN, plugin_0', () => { const state = { plugin_0: { id: 'plugin_0', version: '0.1.0-old', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 0 - old', description: 'The plugin 0 - old.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, ], }, }; const action = { type: AdminTypes.REMOVED_PLUGIN, data: 'plugin_0', }; const expectedState = { plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, ], }, }; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('REMOVED_PLUGIN, plugin_1', () => { const state = { plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, ], }, }; const action = { type: AdminTypes.REMOVED_PLUGIN, data: 'plugin_1', }; const expectedState = {}; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); it('LOGOUT_SUCCESS, previously populated state', () => { const state = { plugin_0: { id: 'plugin_0', version: '0.1.0-old', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 0 - old', description: 'The plugin 0 - old.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.1.0', }, ], }, plugin_1: { id: 'plugin_1', version: '0.0.1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, name: 'Plugin 1', description: 'The plugin.', active: false, instances: [ { cluster_id: 'cluster_id_1', state: PluginState.PLUGIN_STATE_NOT_RUNNING, version: '0.0.1', }, ], }, }; const action = { type: UserTypes.LOGOUT_SUCCESS, }; const expectedState = {}; const actualState = reducer({pluginStatuses: state} as ReducerState, action); expect(actualState.pluginStatuses).toEqual(expectedState); }); }); describe('convertAnalyticsRowsToStats', () => { it('data should not be mutated', () => { const data = deepFreezeAndThrowOnMutation([{name: '1', value: 1}, {name: '2', value: 2}, {name: '3', value: 3}]); convertAnalyticsRowsToStats(data, 'post_counts_day'); convertAnalyticsRowsToStats(data, 'bot_post_counts_day'); }); }); describe('ldapGroups', () => { it('initial state', () => { const state = {}; const action = {}; const expectedState = {}; const actualState = reducer({ldapGroups: state} as ReducerState, action as GenericAction); expect(actualState.ldapGroups).toEqual(expectedState); }); it('RECEIVED_LDAP_GROUPS, empty initial state', () => { const state = {}; const action = { type: AdminTypes.RECEIVED_LDAP_GROUPS, data: { count: 2, groups: [ { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, ], }, }; const expectedState = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const actualState = reducer({ldapGroups: state} as ReducerState, action); expect(actualState.ldapGroups).toEqual(expectedState); }); it('RECEIVED_LDAP_GROUPS, previously populated', () => { const state = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const action = { type: AdminTypes.RECEIVED_LDAP_GROUPS, data: { count: 2, groups: [ { primary_key: 'test3', name: 'test3', mattermost_group_id: null, has_syncables: null, }, { primary_key: 'test4', name: 'test4', mattermost_group_id: 'mattermost-id', has_syncables: false, }, ], }, }; const expectedState = { test3: { primary_key: 'test3', name: 'test3', mattermost_group_id: null, has_syncables: null, }, test4: { primary_key: 'test4', name: 'test4', mattermost_group_id: 'mattermost-id', has_syncables: false, }, }; const actualState = reducer({ldapGroups: state} as ReducerState, action); expect(actualState.ldapGroups).toEqual(expectedState); }); it('LINKED_LDAP_GROUP', () => { const state = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const action = { type: AdminTypes.LINKED_LDAP_GROUP, data: { primary_key: 'test1', name: 'test1', mattermost_group_id: 'new-mattermost-id', has_syncables: false, }, }; const expectedState = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: 'new-mattermost-id', has_syncables: false, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const actualState = reducer({ldapGroups: state} as ReducerState, action); expect(actualState.ldapGroups).toEqual(expectedState); }); it('UNLINKED_LDAP_GROUP', () => { const state = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const action = { type: AdminTypes.UNLINKED_LDAP_GROUP, data: 'test2', }; const expectedState = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: undefined, has_syncables: undefined, failed: false, }, }; const actualState = reducer({ldapGroups: state} as ReducerState, action); expect(actualState.ldapGroups).toEqual(expectedState); }); it('LINK_LDAP_GROUP_FAILURE', () => { const state = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const action = { type: AdminTypes.LINK_LDAP_GROUP_FAILURE, data: 'test1', }; const expectedState = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, failed: true, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const actualState = reducer({ldapGroups: state} as ReducerState, action); expect(actualState.ldapGroups).toEqual(expectedState); }); it('LINK_LDAP_GROUP_FAILURE', () => { const state = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, }, }; const action = { type: AdminTypes.LINK_LDAP_GROUP_FAILURE, data: 'test2', }; const expectedState = { test1: { primary_key: 'test1', name: 'test1', mattermost_group_id: null, has_syncables: null, }, test2: { primary_key: 'test2', name: 'test2', mattermost_group_id: 'mattermost-id', has_syncables: true, failed: true, }, }; const actualState = reducer({ldapGroups: state} as ReducerState, action); expect(actualState.ldapGroups).toEqual(expectedState); }); }); describe('Data Retention', () => { it('initial state', () => { const state = {}; const action = {}; const expectedState = {}; const actualState = reducer({dataRetentionCustomPolicies: state} as ReducerState, action as GenericAction); expect(actualState.dataRetentionCustomPolicies).toEqual(expectedState); }); it('RECEIVED_DATA_RETENTION_CUSTOM_POLICIES', () => { const state = {}; const action = { type: AdminTypes.RECEIVED_DATA_RETENTION_CUSTOM_POLICIES, data: { policies: [ { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, { id: 'id2', display_name: 'Test Policy 2', post_duration: 365, team_count: 0, channel_count: 9, }, ], total_count: 2, }, }; const expectedState = { id1: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, id2: { id: 'id2', display_name: 'Test Policy 2', post_duration: 365, team_count: 0, channel_count: 9, }, }; const actualState = reducer({dataRetentionCustomPolicies: state} as ReducerState, action); expect(actualState.dataRetentionCustomPolicies).toEqual(expectedState); }); it('RECEIVED_DATA_RETENTION_CUSTOM_POLICY', () => { const state = {}; const action = { type: AdminTypes.RECEIVED_DATA_RETENTION_CUSTOM_POLICY, data: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, }; const expectedState = { id1: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, }; const actualState = reducer({dataRetentionCustomPolicies: state} as ReducerState, action); expect(actualState.dataRetentionCustomPolicies).toEqual(expectedState); }); it('DELETE_DATA_RETENTION_CUSTOM_POLICY_SUCCESS', () => { const state = { id1: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, }; const action = { type: AdminTypes.DELETE_DATA_RETENTION_CUSTOM_POLICY_SUCCESS, data: { id: 'id1', }, }; const expectedState = {}; const actualState = reducer({dataRetentionCustomPolicies: state} as unknown as ReducerState, action); expect(actualState.dataRetentionCustomPolicies).toEqual(expectedState); }); it('CREATE_DATA_RETENTION_CUSTOM_POLICY_SUCCESS', () => { const state = {}; const action = { type: AdminTypes.CREATE_DATA_RETENTION_CUSTOM_POLICY_SUCCESS, data: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, }; const expectedState = { id1: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, }; const actualState = reducer({dataRetentionCustomPolicies: state} as ReducerState, action); expect(actualState.dataRetentionCustomPolicies).toEqual(expectedState); }); it('UPDATE_DATA_RETENTION_CUSTOM_POLICY_SUCCESS', () => { const state = { id1: { id: 'id1', display_name: 'Test Policy', post_duration: 100, team_count: 2, channel_count: 1, }, }; const action = { type: AdminTypes.CREATE_DATA_RETENTION_CUSTOM_POLICY_SUCCESS, data: { id: 'id1', display_name: 'Test Policy 123', post_duration: 365, team_count: 2, channel_count: 1, }, }; const expectedState = { id1: { id: 'id1', display_name: 'Test Policy 123', post_duration: 365, team_count: 2, channel_count: 1, }, }; const actualState = reducer({dataRetentionCustomPolicies: state} as unknown as ReducerState, action); expect(actualState.dataRetentionCustomPolicies).toEqual(expectedState); }); }); });
4,005
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/apps.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {AppBinding, AppForm} from '@mattermost/types/apps'; import {AppsTypes} from 'mattermost-redux/action_types'; import * as Reducers from './apps'; describe('bindings', () => { const initialState: AppBinding[] = []; const basicSubmitForm: AppForm = { submit: { path: '/submit_url', }, }; test('No element get filtered', () => { const data = [ { app_id: '1', location: '/post_menu', bindings: [ { location: 'locA', label: 'a', form: basicSubmitForm, }, ], }, { app_id: '2', location: '/post_menu', bindings: [ { location: 'locA', label: 'a', form: basicSubmitForm, }, ], }, { app_id: '1', location: '/channel_header', bindings: [ { location: 'locB', label: 'b', icon: 'icon', form: basicSubmitForm, }, ], }, { app_id: '3', location: '/command', bindings: [ { location: 'locC', label: 'c', form: basicSubmitForm, }, ], }, ]; const state = Reducers.mainBindings( initialState, { type: AppsTypes.RECEIVED_APP_BINDINGS, data, }, ); expect(state).toMatchSnapshot(); }); test('Invalid channel header get filtered', () => { const data = [ { app_id: '1', location: '/post_menu', bindings: [ { location: 'locA', label: 'a', form: basicSubmitForm, }, ], }, { app_id: '2', location: '/post_menu', bindings: [ { location: 'locA', label: 'a', form: basicSubmitForm, }, ], }, { app_id: '1', location: '/channel_header', bindings: [ { location: 'locB', label: 'b', icon: 'icon', form: basicSubmitForm, }, { location: 'locC', label: 'c', form: basicSubmitForm, }, ], }, { app_id: '2', location: '/channel_header', bindings: [ { icon: 'icon', form: basicSubmitForm, }, { location: 'locC', label: 'c', icon: 'icon', form: basicSubmitForm, }, ], }, { app_id: '3', location: '/channel_header', bindings: [ { location: 'locB', form: basicSubmitForm, }, { location: 'locC', label: 'c', form: basicSubmitForm, }, ], }, { app_id: '3', location: '/command', bindings: [ { location: 'locC', label: 'c', form: basicSubmitForm, }, ], }, ]; const state = Reducers.mainBindings( initialState, { type: AppsTypes.RECEIVED_APP_BINDINGS, data, }, ); expect(state).toMatchSnapshot(); }); test('Invalid post menu get filtered', () => { const data = [ { app_id: '1', location: '/post_menu', bindings: [ { form: basicSubmitForm, }, { location: 'locB', label: 'a', form: basicSubmitForm, }, ], }, { app_id: '2', location: '/post_menu', bindings: [ { location: 'locA', label: 'a', form: basicSubmitForm, }, { location: 'locB', label: 'b', form: basicSubmitForm, }, ], }, { app_id: '3', location: '/post_menu', bindings: [ { form: basicSubmitForm, }, ], }, { app_id: '1', location: '/channel_header', bindings: [ { location: 'locB', label: 'b', icon: 'icon', form: basicSubmitForm, }, ], }, { app_id: '3', location: '/command', bindings: [ { location: 'locC', label: 'c', form: basicSubmitForm, }, ], }, ]; const state = Reducers.mainBindings( initialState, { type: AppsTypes.RECEIVED_APP_BINDINGS, data, }, ); expect(state).toMatchSnapshot(); }); test('Invalid commands get filtered', () => { const data = [ { app_id: '1', location: '/post_menu', bindings: [ { location: 'locA', label: 'a', form: basicSubmitForm, }, { location: 'locB', label: 'a', form: basicSubmitForm, }, ], }, { app_id: '1', location: '/channel_header', bindings: [ { location: 'locB', label: 'b', icon: 'icon', form: basicSubmitForm, }, ], }, { app_id: '3', location: '/command', bindings: [ { location: 'locC', label: 'c', bindings: [ { form: basicSubmitForm, }, { location: 'subC2', label: 'c2', form: basicSubmitForm, }, ], }, { location: 'locD', label: 'd', bindings: [ { form: basicSubmitForm, }, ], }, ], }, { app_id: '1', location: '/command', bindings: [ { form: basicSubmitForm, }, ], }, { app_id: '2', location: '/command', bindings: [ { location: 'locC', label: 'c', bindings: [ { location: 'subC1', label: 'c1', form: basicSubmitForm, }, { location: 'subC2', label: 'c2', form: basicSubmitForm, }, ], }, ], }, ]; const state = Reducers.mainBindings( initialState, { type: AppsTypes.RECEIVED_APP_BINDINGS, data, }, ); expect(state).toMatchSnapshot(); }); test('Apps plugin gets disabled', () => { const initialState: AppBinding[] = [ { app_id: '1', location: '/post_menu', label: 'post_menu', bindings: [ { app_id: '1', location: 'locA', label: 'a', }, ], }, ] as AppBinding[]; const state = Reducers.mainBindings( initialState, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toEqual([]); }); }); describe('pluginEnabled', () => { test('Apps plugin gets enabled', () => { let state = Reducers.pluginEnabled( true, { type: AppsTypes.APPS_PLUGIN_ENABLED, }, ); expect(state).toBe(true); state = Reducers.pluginEnabled( false, { type: AppsTypes.APPS_PLUGIN_ENABLED, }, ); expect(state).toBe(true); }); test('Apps plugin gets disabled', () => { let state = Reducers.pluginEnabled( true, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toBe(false); state = Reducers.pluginEnabled( false, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toBe(false); }); test('Apps plugin gets disabled', () => { let state = Reducers.pluginEnabled( true, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toBe(false); state = Reducers.pluginEnabled( false, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toBe(false); }); test('Apps plugin gets disabled', () => { let state = Reducers.pluginEnabled( true, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toBe(false); state = Reducers.pluginEnabled( false, { type: AppsTypes.APPS_PLUGIN_DISABLED, }, ); expect(state).toBe(false); }); test('Bindings are succesfully fetched', () => { let state = Reducers.pluginEnabled( true, { type: AppsTypes.RECEIVED_APP_BINDINGS, }, ); expect(state).toBe(true); state = Reducers.pluginEnabled( false, { type: AppsTypes.RECEIVED_APP_BINDINGS, }, ); expect(state).toBe(true); }); test('Bindings fail to fetch', () => { let state = Reducers.pluginEnabled( true, { type: AppsTypes.FAILED_TO_FETCH_APP_BINDINGS, }, ); expect(state).toBe(false); state = Reducers.pluginEnabled( false, { type: AppsTypes.FAILED_TO_FETCH_APP_BINDINGS, }, ); expect(state).toBe(false); }); });
4,012
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/cloud.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {CloudTypes} from 'mattermost-redux/action_types'; import {limits} from './cloud'; const minimalLimits = { limitsLoaded: true, limits: { messages: { history: 10000, }, }, }; describe('limits reducer', () => { test('returns empty limits by default', () => { expect(limits(undefined, {type: 'some action', data: minimalLimits})).toEqual({ limits: {}, limitsLoaded: false, }); }); test('returns prior limits on unmatched action', () => { const unchangedLimits = limits( minimalLimits, { type: 'some action', data: { ...minimalLimits, integrations: { enabled: 10, }, }, }, ); expect(unchangedLimits).toEqual(minimalLimits); }); test('returns new limits on RECEIVED_CLOUD_LIMITS', () => { const updatedLimits = { ...minimalLimits, integrations: { enabled: 10, }, }; const unchangedLimits = limits( minimalLimits, { type: CloudTypes.RECEIVED_CLOUD_LIMITS, data: updatedLimits, }, ); expect(unchangedLimits).toEqual({limits: {...updatedLimits}, limitsLoaded: true}); }); test('clears limits when new subscription received', () => { const emptyLimits = limits( minimalLimits, { type: CloudTypes.RECEIVED_CLOUD_SUBSCRIPTION, data: {}, }, ); expect(emptyLimits).toEqual({limits: {}, limitsLoaded: false}); }); });
4,016
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/files.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {PostTypes} from 'mattermost-redux/action_types'; import { files as filesReducer, filesFromSearch as filesFromSearchReducer, fileIdsByPostId as fileIdsByPostIdReducer, } from 'mattermost-redux/reducers/entities/files'; import deepFreeze from 'mattermost-redux/utils/deep_freeze'; describe('reducers/entities/files', () => { describe('files', () => { const testForSinglePost = (actionType: string) => () => { it('no post metadata attribute', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', }, }; const nextState = filesReducer(state, action); expect(nextState).toEqual(state); }); it('empty post metadata attribute', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', }, metadata: {}, }; const nextState = filesReducer(state, action); expect(nextState).toEqual(state); }); it('no files in post metadata', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: { files: [], }, }, }; const nextState = filesReducer(state, action); expect(nextState).toEqual(state); }); it('should save files', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }; const nextState = filesReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ file1: {id: 'file1', post_id: 'post'}, file2: {id: 'file2', post_id: 'post'}, }); }); it('should save files for permalinks', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post-2', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }, }], }, }, }; const nextState = filesReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ file1: {id: 'file1', post_id: 'post'}, file2: {id: 'file2', post_id: 'post'}, }); }); }; describe('RECEIVED_NEW_POST', testForSinglePost(PostTypes.RECEIVED_NEW_POST)); describe('RECEIVED_POST', testForSinglePost(PostTypes.RECEIVED_POST)); describe('RECEIVED_POSTS', () => { it('no post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', }, }, }, }; const nextState = filesReducer(state, action); expect(nextState).toEqual(state); }); it('no files in post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: {}, }, }, }, }; const nextState = filesReducer(state, action); expect(nextState).toEqual(state); }); it('should save files', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }, }, }; const nextState = filesReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ file1: {id: 'file1', post_id: 'post'}, file2: {id: 'file2', post_id: 'post'}, }); }); it('should save files for multiple posts', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { files: [{id: 'file1', post_id: 'post1'}, {id: 'file2', post_id: 'post1'}], }, }, post2: { id: 'post2', metadata: { files: [{id: 'file3', post_id: 'post2'}, {id: 'file4', post_id: 'post2'}], }, }, }, }, }; const nextState = filesReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ file1: {id: 'file1', post_id: 'post1'}, file2: {id: 'file2', post_id: 'post1'}, file3: {id: 'file3', post_id: 'post2'}, file4: {id: 'file4', post_id: 'post2'}, }); }); it('should save files for permalinks', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post-1-embed', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }, }], }, }, post2: { id: 'post', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post-2-embed', metadata: { files: [{id: 'file3', post_id: 'post'}, {id: 'file4', post_id: 'post'}], }, }, }, }], }, }, }, }, }; const nextState = filesReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ file1: {id: 'file1', post_id: 'post'}, file2: {id: 'file2', post_id: 'post'}, file3: {id: 'file3', post_id: 'post'}, file4: {id: 'file4', post_id: 'post'}, }); }); }); }); describe('filesFromSearch', () => { const state = deepFreeze({}); const action = { type: 'RECEIVED_FILES_FOR_SEARCH', data: { file1: {id: 'file1', post_id: 'post'}, file2: {id: 'file2', post_id: 'post'}, }, }; const nextState = filesFromSearchReducer(state, action); expect(nextState).toEqual({ file1: {id: 'file1', post_id: 'post'}, file2: {id: 'file2', post_id: 'post'}, }); }); describe('fileIdsByPostId', () => { const testForSinglePost = (actionType: string) => () => { describe('no post metadata', () => { const action = { type: actionType, data: { id: 'post', }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); it('with previous state', () => { const state = deepFreeze({ post: ['file1'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); }); describe('no files property in post metadata', () => { const action = { type: actionType, data: { id: 'post', metadata: {}, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); it('with previous state', () => { const state = deepFreeze({ post: ['file1'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); }); describe('empty files property in post metadata', () => { const action = { type: actionType, data: { id: 'post', metadata: { files: [], }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: [], }); }); it('with previous state', () => { const state = deepFreeze({ post: ['file1'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: [], }); }); }); describe('new files', () => { const action = { type: actionType, data: { id: 'post', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); it('with previous state', () => { const state = deepFreeze({ post: ['fileOld'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); }); describe('new files in permalink', () => { const action = { type: actionType, data: { id: 'post1', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }, }], }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); it('with previous state', () => { const state = deepFreeze({ post: ['fileOld'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); }); }; describe('RECEIVED_NEW_POST', testForSinglePost(PostTypes.RECEIVED_NEW_POST)); describe('RECEIVED_POST', testForSinglePost(PostTypes.RECEIVED_POST)); describe('RECEIVED_POSTS', () => { describe('no post metadata', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', }, }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); it('with previous state', () => { const state = deepFreeze({ post: ['file1'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); }); describe('no files property in post metadata', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: {}, }, }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); it('with previous state', () => { const state = deepFreeze({ post: ['file1'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).toEqual(state); }); }); describe('empty files property in post metadata', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: { files: [], }, }, }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: [], }); }); it('with previous state', () => { const state = deepFreeze({ post: ['file1'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: [], }); }); }); describe('new files for single post', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); it('with previous state', () => { const state = deepFreeze({ post: ['fileOld'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); }); describe('new files for single post in permalink', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post', metadata: { files: [{id: 'file1', post_id: 'post'}, {id: 'file2', post_id: 'post'}], }, }, }, }], }, }, }, }, }; it('no previous state', () => { const state = deepFreeze({}); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); it('with previous state', () => { const state = deepFreeze({ post: ['fileOld'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: ['file1', 'file2'], }); }); }); describe('should save files for multiple posts', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { files: [{id: 'file1', post_id: 'post1'}, {id: 'file2', post_id: 'post1'}], }, }, post2: { id: 'post2', metadata: { files: [{id: 'file3', post_id: 'post2'}, {id: 'file4', post_id: 'post2'}], }, }, }, }, }; it('no previous state for post1', () => { const state = deepFreeze({ post2: ['fileOld2'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: ['file1', 'file2'], post2: ['file3', 'file4'], }); }); it('previous state for post1', () => { const state = deepFreeze({ post1: ['fileOld1'], post2: ['fileOld2'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: ['file1', 'file2'], post2: ['file3', 'file4'], }); }); }); describe('should save files for multiple posts with permalinks', () => { const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post3: { id: 'post', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post1', metadata: { files: [{id: 'file1', post_id: 'post1'}, {id: 'file2', post_id: 'post1'}], }, }, }, }], }, }, post4: { id: 'post', metadata: { embeds: [{ type: 'permalink', data: { post: { id: 'post2', metadata: { files: [{id: 'file3', post_id: 'post2'}, {id: 'file4', post_id: 'post2'}], }, }, }, }], }, }, }, }, }; it('no previous state for post1', () => { const state = deepFreeze({ post2: ['fileOld2'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: ['file1', 'file2'], post2: ['file3', 'file4'], }); }); it('previous state for post1', () => { const state = deepFreeze({ post1: ['fileOld1'], post2: ['fileOld2'], }); const nextState = fileIdsByPostIdReducer(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: ['file1', 'file2'], post2: ['file3', 'file4'], }); }); }); }); }); });
4,018
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/general.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {GeneralTypes} from 'mattermost-redux/action_types'; import reducer from 'mattermost-redux/reducers/entities/general'; import type {GenericAction} from 'mattermost-redux/types/actions'; type ReducerState = ReturnType<typeof reducer> describe('reducers.entities.general', () => { describe('firstAdminVisitMarketplaceStatus', () => { it('initial state', () => { const state = {}; const action = {}; const expectedState = {}; const actualState = reducer({firstAdminVisitMarketplaceStatus: state} as ReducerState, action as GenericAction); expect(actualState.firstAdminVisitMarketplaceStatus).toEqual(expectedState); }); it('FIRST_ADMIN_VISIT_MARKETPLACE_STATUS_RECEIVED, empty initial state', () => { const state = {}; const action = { type: GeneralTypes.FIRST_ADMIN_VISIT_MARKETPLACE_STATUS_RECEIVED, data: true, }; const expectedState = true; const actualState = reducer({firstAdminVisitMarketplaceStatus: state} as ReducerState, action); expect(actualState.firstAdminVisitMarketplaceStatus).toEqual(expectedState); }); it('FIRST_ADMIN_VISIT_MARKETPLACE_STATUS_RECEIVED, previously populated state', () => { const state = true; const action = { type: GeneralTypes.FIRST_ADMIN_VISIT_MARKETPLACE_STATUS_RECEIVED, data: true, }; const expectedState = true; const actualState = reducer({firstAdminVisitMarketplaceStatus: state} as ReducerState, action); expect(actualState.firstAdminVisitMarketplaceStatus).toEqual(expectedState); }); }); });
4,020
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/groups.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {GroupTypes} from 'mattermost-redux/action_types'; import reducer from 'mattermost-redux/reducers/entities/groups'; describe('reducers/entities/groups', () => { describe('syncables', () => { it('initial state', () => { const state = undefined; const action = { type: '', }; const expectedState = { syncables: {}, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); it('GroupTypes.RECEIVED_GROUP_TEAMS state', () => { const groupId = '5rgoajywb3nfbdtyafbod47rya'; const data = [ { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', team_display_name: 'dolphins', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542643748412, }, { team_id: 'tdjrcr3hg7yazyos17a53jduna', team_display_name: 'developers', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643825026, delete_at: 0, update_at: 1542643825026, }, ]; const state = { syncables: {}, groups: {}, stats: {}, myGroups: [], }; const action = { type: GroupTypes.RECEIVED_GROUP_TEAMS, data, group_id: groupId, }; const expectedState = { syncables: { [groupId]: { teams: data, }, }, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); it('GroupTypes.RECEIVED_GROUP_CHANNELS state', () => { const groupId = '5rgoajywb3nfbdtyafbod47rya'; const data = [ { channel_id: 'o3tdawqxot8kikzq8bk54zggbc', channel_display_name: 'standup', channel_type: 'P', team_id: 'tdjrcr3hg7yazyos17a53jduna', team_display_name: 'developers', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542644105041, delete_at: 0, update_at: 1542644105041, }, { channel_id: 's6oxu3embpdepyprx1fn5gjhea', channel_display_name: 'swimming', channel_type: 'P', team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', team_display_name: 'dolphins', team_type: 'O', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542644105042, delete_at: 0, update_at: 1542644105042, }, ]; const state = { syncables: {}, groups: {}, stats: {}, myGroups: [], }; const action = { type: GroupTypes.RECEIVED_GROUP_CHANNELS, data, group_id: groupId, }; const expectedState = { syncables: { [groupId]: { channels: data, }, }, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); it('GroupTypes.LINKED_GROUP_TEAM state', () => { const groupId = '5rgoajywb3nfbdtyafbod47rya'; const data = { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const state = { syncables: {}, groups: {}, stats: {}, myGroups: [], }; const action = { type: GroupTypes.LINKED_GROUP_TEAM, data, group_id: groupId, }; const expectedState = { syncables: { [groupId]: { teams: [data], }, }, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); it('GroupTypes.LINKED_GROUP_CHANNEL state', () => { const groupId = '5rgoajywb3nfbdtyafbod47rya'; const data = { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', channel_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const state = { syncables: {}, groups: {}, stats: {}, myGroups: [], }; const action = { type: GroupTypes.LINKED_GROUP_CHANNEL, data, group_id: groupId, }; const expectedState = { syncables: { [groupId]: { channels: [data], }, }, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); it('GroupTypes.UNLINKED_GROUP_TEAM state', () => { const groupId = '5rgoajywb3nfbdtyafbod47rya'; const data = { syncable_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', }; const expectedChannel = { team_id: 'ge63nq31sbfy3duzq5f7yqn7ii', channel_id: 'o3tdawqxot8kikzq8bk54zgccc', group_id: '5rgoajywb3nfbdtyafbod47rya', channel_display_name: 'Test Channel 2', channel_type: 'O', team_display_name: 'Test Team 2', team_type: 'O', scheme_admin: false, auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const state = { syncables: { [groupId]: { teams: [ { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', team_display_name: 'Test Team', team_type: 'O', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, scheme_admin: false, }, ], channels: [ { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', channel_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', channel_display_name: 'Test Channel', channel_type: 'O', team_display_name: 'Test Team', team_type: 'O', scheme_admin: false, auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }, expectedChannel, ], }, }, groups: {}, stats: {}, myGroups: [], }; const action = { type: GroupTypes.UNLINKED_GROUP_TEAM, data, group_id: groupId, }; const expectedState = { syncables: { [groupId]: { teams: [], channels: [expectedChannel], }, }, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); it('GroupTypes.UNLINKED_GROUP_CHANNEL state', () => { const groupId = '5rgoajywb3nfbdtyafbod47rya'; const data = { syncable_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', }; const expectedTeam = { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', group_id: '5rgoajywb3nfbdtyafbod47rya', team_display_name: 'Test Team', team_type: 'O', auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, scheme_admin: false, }; const expectedChannel = { team_id: 'ge63nq31sbfy3duzq5f7yqn7ii', channel_id: 'o3tdawqxot8kikzq8bk54zgccc', group_id: '5rgoajywb3nfbdtyafbod47rya', channel_display_name: 'Test Channel 2', channel_type: 'O', team_display_name: 'Test Team 2', team_type: 'O', scheme_admin: false, auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }; const state = { syncables: { [groupId]: { teams: [ expectedTeam, ], channels: [ { team_id: 'ge63nq31sbfy3duzq5f7yqn1kh', channel_id: 'o3tdawqxot8kikzq8bk54zggbc', group_id: '5rgoajywb3nfbdtyafbod47rya', channel_display_name: 'Test Channel', channel_type: 'O', team_display_name: 'Test Team', team_type: 'O', scheme_admin: false, auto_add: true, create_at: 1542643748412, delete_at: 0, update_at: 1542660566032, }, expectedChannel, ], }, }, groups: {}, stats: {}, myGroups: [], }; const action = { type: GroupTypes.UNLINKED_GROUP_CHANNEL, data, group_id: groupId, }; const expectedState = { syncables: { [groupId]: { teams: [expectedTeam], channels: [expectedChannel], }, }, }; const newState = reducer(state, action); expect(newState.syncables).toEqual(expectedState.syncables); }); }); });
4,026
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/posts.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Post, PostOrderBlock} from '@mattermost/types/posts'; import { ChannelTypes, PostTypes, ThreadTypes, CloudTypes, } from 'mattermost-redux/action_types'; import {Posts} from 'mattermost-redux/constants'; import * as reducers from 'mattermost-redux/reducers/entities/posts'; import deepFreeze from 'mattermost-redux/utils/deep_freeze'; import {TestHelper} from 'utils/test_helper'; function toPostsRecord(partials: Record<string, Partial<Post>>): Record<string, Post> { const result: Record<string, Post> = {}; return Object.keys(partials).reduce((acc, k) => { acc[k] = TestHelper.getPostMock(partials[k]); return acc; }, result); } describe('posts', () => { for (const actionType of [ PostTypes.RECEIVED_POST, PostTypes.RECEIVED_NEW_POST, ]) { describe(`received a single post (${actionType})`, () => { it('should add a new post', () => { const state = deepFreeze({ post1: {id: 'post1'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post2'}, }); expect(nextState).not.toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState).toEqual({ post1: {id: 'post1'}, post2: {id: 'post2'}, }); }); it('should add a new permalink post and remove stored nested permalink data', () => { const state = deepFreeze({ post1: {id: 'post1'}, post2: {id: 'post2', metadata: {embeds: [{type: 'permalink', data: {post_id: 'post1', post: {id: 'post1'}}}]}}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post3', metadata: {embeds: [{type: 'permalink', data: {post_id: 'post2', post: {id: 'post2', metadata: {embeds: [{type: 'permalink', data: {post_id: 'post1', post: {id: 'post1'}}}]}}}}]}}, }); expect(nextState).not.toEqual(state); expect(nextState.post1).toEqual(state.post1); expect(nextState.post2).toEqual(state.post2); expect(nextState).toEqual({ post1: {id: 'post1'}, post2: {id: 'post2', metadata: {embeds: [{type: 'permalink', data: {post_id: 'post1', post: {id: 'post1'}}}]}}, post3: {id: 'post3', metadata: {embeds: [{type: 'permalink', data: {post_id: 'post2'}}]}}, }); }); it('should add a new pending post', () => { const state = deepFreeze({ post1: {id: 'post1'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post2', pending_post_id: 'post2'}, }); expect(nextState).not.toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState).toEqual({ post1: {id: 'post1'}, post2: {id: 'post2', pending_post_id: 'post2'}, }); }); it('should update an existing post', () => { const state = deepFreeze({ post1: {id: 'post1', message: '123'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post1', message: 'abc'}, }); expect(nextState).not.toBe(state); expect(nextState.post1).not.toBe(state.post1); expect(nextState).toEqual({ post1: {id: 'post1', message: 'abc'}, }); }); it('should add a newer post', () => { const state = deepFreeze({ post1: {id: 'post1', message: '123', update_at: 100}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post1', message: 'abc', update_at: 400}, }); expect(nextState).not.toBe(state); expect(nextState.post1).not.toBe(state.post1); expect(nextState).toEqual({ post1: {id: 'post1', message: 'abc', update_at: 400}, }); }); it('should not add an older post', () => { const state = deepFreeze({ post1: {id: 'post1', message: '123', update_at: 400}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post1', message: 'abc', update_at: 100}, }); expect(nextState.post1).toBe(state.post1); }); it('should remove any pending posts when receiving the actual post', () => { const state = deepFreeze({ pending: {id: 'pending'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: {id: 'post1', pending_post_id: 'pending'}, }); expect(nextState).not.toBe(state); expect(nextState).toEqual({ post1: {id: 'post1', pending_post_id: 'pending'}, }); }); }); } describe('received multiple posts', () => { it('should do nothing when post list is empty', () => { const state = deepFreeze({ post1: {id: 'post1'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.RECEIVED_POSTS, data: { order: [], posts: {}, }, }); expect(nextState).toBe(state); }); it('should add new posts', () => { const state = deepFreeze({ post1: {id: 'post1'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.RECEIVED_POSTS, data: { order: ['post2', 'post3'], posts: { post2: {id: 'post2'}, post3: {id: 'post3'}, }, }, }); expect(nextState).not.toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState).toEqual({ post1: {id: 'post1'}, post2: {id: 'post2'}, post3: {id: 'post3'}, }); }); it('should update existing posts unless we have a more recent version', () => { const state = deepFreeze({ post1: {id: 'post1', message: '123', update_at: 1000}, post2: {id: 'post2', message: '456', update_at: 1000}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.RECEIVED_POSTS, data: { order: ['post1', 'post2'], posts: { post1: {id: 'post1', message: 'abc', update_at: 2000}, post2: {id: 'post2', message: 'def', update_at: 500}, }, }, }); expect(nextState).not.toBe(state); expect(nextState.post1).not.toBe(state.post1); expect(nextState.post2).toBe(state.post2); expect(nextState).toEqual({ post1: {id: 'post1', message: 'abc', update_at: 2000}, post2: {id: 'post2', message: '456', update_at: 1000}, }); }); it('should set state for deleted posts', () => { const state = deepFreeze({ post1: {id: 'post1', message: '123', delete_at: 0, file_ids: ['file']}, post2: {id: 'post2', message: '456', delete_at: 0, has_reactions: true}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.RECEIVED_POSTS, data: { order: ['post1', 'post2'], posts: { post1: {id: 'post1', message: '123', delete_at: 2000, file_ids: ['file']}, post2: {id: 'post2', message: '456', delete_at: 500, has_reactions: true}, }, }, }); expect(nextState).not.toBe(state); expect(nextState.post1).not.toBe(state.post1); expect(nextState.post2).not.toBe(state.post2); expect(nextState).toEqual({ post1: {id: 'post1', message: '123', delete_at: 2000, file_ids: [], has_reactions: false, state: Posts.POST_DELETED}, post2: {id: 'post2', message: '456', delete_at: 500, file_ids: [], has_reactions: false, state: Posts.POST_DELETED}, }); }); it('should remove any pending posts when receiving the actual post', () => { const state = deepFreeze({ pending1: {id: 'pending1'}, pending2: {id: 'pending2'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.RECEIVED_POSTS, data: { order: ['post1', 'post2'], posts: { post1: {id: 'post1', pending_post_id: 'pending1'}, post2: {id: 'post2', pending_post_id: 'pending2'}, }, }, }); expect(nextState).not.toBe(state); expect(nextState).toEqual({ post1: {id: 'post1', pending_post_id: 'pending1'}, post2: {id: 'post2', pending_post_id: 'pending2'}, }); }); it('should not add channelId entity to postsInChannel if there were no posts in channel and it has receivedNewPosts on action', () => { const state = deepFreeze({ posts: {}, postsInChannel: {}, }); const action = { type: PostTypes.RECEIVED_POSTS, data: { order: ['postId'], posts: { postId: { id: 'postId', }, }, }, channelId: 'channelId', receivedNewPosts: true, }; const nextState = reducers.handlePosts(state, action); expect(nextState.postsInChannel).toEqual({}); }); }); describe(`deleting a post (${PostTypes.POST_DELETED})`, () => { it('should mark the post as deleted and remove the rest of the thread', () => { const state = deepFreeze({ post1: {id: 'post1', file_ids: ['file'], has_reactions: true}, comment1: {id: 'comment1', root_id: 'post1'}, comment2: {id: 'comment2', root_id: 'post1'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_DELETED, data: {id: 'post1'}, }); expect(nextState).not.toBe(state); expect(nextState.post1).not.toBe(state.post1); expect(nextState).toEqual({ post1: {id: 'post1', file_ids: [], has_reactions: false, state: Posts.POST_DELETED}, }); }); it('should remove deleted post from other post embeds', () => { const post1 = {id: 'post1', message: 'Post 1'}; const post2 = { id: 'post2', message: 'Post 2', metadata: { embeds: [ { type: 'permalink', data: { post_id: 'post1', }, }, ], }, }; const post3 = { id: 'post3', message: 'Post 3', metadata: { embeds: [ { type: 'permalink', data: { post_id: 'post1', }, }, { type: 'permalink', data: { post_id: 'post2', }, }, ], }, }; const state = deepFreeze({ post1, post2, post3, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_DELETED, data: {id: 'post1'}, }); expect(nextState).not.toBe(state); expect(nextState.post2.metadata.embeds.length).toBe(0); expect(nextState.post3.metadata.embeds.length).toBe(1); }); it('should not remove the rest of the thread when deleting a comment', () => { const state = deepFreeze({ post1: {id: 'post1'}, comment1: {id: 'comment1', root_id: 'post1'}, comment2: {id: 'comment2', root_id: 'post1'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_DELETED, data: {id: 'comment1'}, }); expect(nextState).not.toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState.comment1).not.toBe(state.comment1); expect(nextState.comment2).toBe(state.comment2); expect(nextState).toEqual({ post1: {id: 'post1'}, comment1: {id: 'comment1', root_id: 'post1', file_ids: [], has_reactions: false, state: Posts.POST_DELETED}, comment2: {id: 'comment2', root_id: 'post1'}, }); }); it('should do nothing if the post is not loaded', () => { const state = deepFreeze({ post1: {id: 'post1', file_ids: ['file'], has_reactions: true}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_DELETED, data: {id: 'post2'}, }); expect(nextState).toBe(state); expect(nextState.post1).toBe(state.post1); }); }); describe(`removing a post (${PostTypes.POST_REMOVED})`, () => { it('should remove the post and the rest and the rest of the thread', () => { const state = deepFreeze({ post1: {id: 'post1', file_ids: ['file'], has_reactions: true}, comment1: {id: 'comment1', root_id: 'post1'}, comment2: {id: 'comment2', root_id: 'post1'}, post2: {id: 'post2'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_REMOVED, data: {id: 'post1'}, }); expect(nextState).not.toBe(state); expect(nextState.post2).toBe(state.post2); expect(nextState).toEqual({ post2: {id: 'post2'}, }); }); it('should not remove the rest of the thread when removing a comment', () => { const state = deepFreeze({ post1: {id: 'post1'}, comment1: {id: 'comment1', root_id: 'post1'}, comment2: {id: 'comment2', root_id: 'post1'}, post2: {id: 'post2'}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_REMOVED, data: {id: 'comment1'}, }); expect(nextState).not.toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState.comment1).not.toBe(state.comment1); expect(nextState.comment2).toBe(state.comment2); expect(nextState).toEqual({ post1: {id: 'post1'}, comment2: {id: 'comment2', root_id: 'post1'}, post2: {id: 'post2'}, }); }); it('should do nothing if the post is not loaded', () => { const state = deepFreeze({ post1: {id: 'post1', file_ids: ['file'], has_reactions: true}, }); const nextState = reducers.handlePosts(state, { type: PostTypes.POST_REMOVED, data: {id: 'post2'}, }); expect(nextState).toBe(state); expect(nextState.post1).toBe(state.post1); }); }); for (const actionType of [ ChannelTypes.RECEIVED_CHANNEL_DELETED, ChannelTypes.DELETE_CHANNEL_SUCCESS, ChannelTypes.LEAVE_CHANNEL, ]) { describe(`when a channel is deleted (${actionType})`, () => { it('should remove any posts in that channel', () => { const state = deepFreeze({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel2'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: false, }, }); expect(nextState).not.toBe(state); expect(nextState.post3).toBe(state.post3); expect(nextState).toEqual({ post3: {id: 'post3', channel_id: 'channel2'}, }); }); it('should do nothing if no posts in that channel are loaded', () => { const state = deepFreeze({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel2'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: { id: 'channel3', viewArchivedChannels: false, }, }); expect(nextState).toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState.post2).toBe(state.post2); expect(nextState.post3).toBe(state.post3); }); it('should not remove any posts with viewArchivedChannels enabled', () => { const state = deepFreeze({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel2'}, }); const nextState = reducers.handlePosts(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: true, }, }); expect(nextState).toBe(state); expect(nextState.post1).toBe(state.post1); expect(nextState.post2).toBe(state.post2); expect(nextState.post3).toBe(state.post3); }); }); } describe(`follow a post/thread (${ThreadTypes.FOLLOW_CHANGED_THREAD})`, () => { test.each([[true], [false]])('should set is_following to %s', (following) => { const state = deepFreeze({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel2'}, }); const nextState = reducers.handlePosts(state, { type: ThreadTypes.FOLLOW_CHANGED_THREAD, data: { id: 'post1', following, }, }); expect(nextState).not.toBe(state); expect(nextState.post3).toBe(state.post3); expect(nextState.post2).toBe(state.post2); expect(nextState.post1).toEqual({ id: 'post1', channel_id: 'channel1', is_following: following, }); expect(nextState).toEqual({ post1: {id: 'post1', channel_id: 'channel1', is_following: following}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel2'}, }); }); }); }); describe('pendingPostIds', () => { describe('making a new pending post', () => { it('should add new entries for pending posts', () => { const state = deepFreeze(['1234']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.RECEIVED_NEW_POST, data: { pending_post_id: 'abcd', }, }); expect(nextState).not.toBe(state); expect(nextState).toEqual(['1234', 'abcd']); }); it('should not add duplicate entries', () => { const state = deepFreeze(['1234']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.RECEIVED_NEW_POST, data: { pending_post_id: '1234', }, }); expect(nextState).toBe(state); expect(nextState).toEqual(['1234']); }); it('should do nothing for regular posts', () => { const state = deepFreeze(['1234']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.RECEIVED_NEW_POST, data: { id: 'abcd', }, }); expect(nextState).toBe(state); expect(nextState).toEqual(['1234']); }); }); describe('removing a pending post', () => { it('should remove an entry when its post is deleted', () => { const state = deepFreeze(['1234', 'abcd']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.POST_REMOVED, data: { id: 'abcd', }, }); expect(nextState).not.toBe(state); expect(nextState).toEqual(['1234']); }); it('should do nothing without an entry for the post', () => { const state = deepFreeze(['1234', 'abcd']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.POST_REMOVED, data: { id: 'wxyz', }, }); expect(nextState).toBe(state); expect(nextState).toEqual(['1234', 'abcd']); }); }); describe('marking a pending post as completed', () => { it('should remove an entry when its post is successfully created', () => { const state = deepFreeze(['1234', 'abcd']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.RECEIVED_POST, data: { id: 'post', pending_post_id: 'abcd', }, }); expect(nextState).not.toBe(state); expect(nextState).toEqual(['1234']); }); it('should do nothing without an entry for the post', () => { const state = deepFreeze(['1234', 'abcd']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.RECEIVED_POST, data: { id: 'post', pending_post_id: 'wxyz', }, }); expect(nextState).toBe(state); expect(nextState).toEqual(['1234', 'abcd']); }); it('should do nothing when receiving a non-pending post', () => { const state = deepFreeze(['1234', 'abcd']); const nextState = reducers.handlePendingPosts(state, { type: PostTypes.RECEIVED_POST, data: { id: 'post', }, }); expect(nextState).toBe(state); expect(nextState).toEqual(['1234', 'abcd']); }); }); }); describe('postsInChannel', () => { describe('receiving a new post', () => { it('should do nothing without posts loaded for the channel', () => { const state = deepFreeze({}); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post1', channel_id: 'channel1'}, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({}); }); it('should do nothing when a reply-post comes and CRT is ON', () => { const state = deepFreeze({ channel1: [], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post1', channel_id: 'channel1', root_id: 'parent1'}, features: {crtEnabled: true}, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [], }); }); it('should reset when called for (e.g. when CRT is TOGGLED)', () => { const state = deepFreeze({ channel1: [], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RESET_POSTS_IN_CHANNEL, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({}); }); it('should store the new post when the channel is empty', () => { const state = deepFreeze({ channel1: [], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post1', channel_id: 'channel1'}, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1'], recent: true}, ], }); }); it('should store the new post when the channel has recent posts', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post1', channel_id: 'channel1'}, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should not store the new post when the channel only has older posts', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: false}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post1', channel_id: 'channel1'}, }, {}, {}); expect(nextState).toEqual({ channel1: [ {order: ['post2', 'post3'], recent: false}, {order: ['post1'], recent: true}, ], }); }); it('should do nothing for a duplicate post', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post1', channel_id: 'channel1'}, }, {}, {}); expect(nextState).toBe(state); }); it('should remove a previously pending post', () => { const state = deepFreeze({ channel1: [ {order: ['pending', 'post2', 'post1'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post3', channel_id: 'channel1', pending_post_id: 'pending'}, }, {}, toPostsRecord({post1: {create_at: 1}, post2: {create_at: 2}, post3: {create_at: 3}})); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post3', 'post2', 'post1'], recent: true}, ], }); }); it('should just add the new post if the pending post was already removed', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_NEW_POST, data: {id: 'post3', channel_id: 'channel1', pending_post_id: 'pending'}, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post3', 'post1', 'post2'], recent: true}, ], }); }); it('should not include a previously removed post', () => { const state = deepFreeze({ channel1: [ {order: ['post1'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: {id: 'post1', channel_id: 'channel1'}, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [{ order: [], recent: true, }], }); }); }); describe('receiving a postEditHistory', () => { it('should replace the postEditHistory for the post', () => { const state = deepFreeze({ channel1: [ {order: ['post1'], recent: true}, ], }); const nextState = reducers.postEditHistory(state, { type: PostTypes.RECEIVED_POST_HISTORY, data: { postEditHistory: [ {create_at: 1, user_id: 'user1', post_id: 'post2', message: 'message2'}, {create_at: 2, user_id: 'user1', post_id: 'post3', message: 'message3'}, ], }, }); expect(nextState).not.toBe(state); expect(nextState).toEqual({ postEditHistory: [ {create_at: 1, user_id: 'user1', post_id: 'post2', message: 'message2'}, {create_at: 2, user_id: 'user1', post_id: 'post3', message: 'message3'}, ]}, ); }); }); describe('receiving a single post', () => { it('should replace a previously pending post', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'pending', 'post2'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POST, data: {id: 'post3', channel_id: 'channel1', pending_post_id: 'pending'}, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post3', 'post2'], recent: true}, ], }); }); it('should do nothing for a pending post that was already removed', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POST, data: {id: 'post3', channel_id: 'channel1', pending_post_id: 'pending'}, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); }); it('should do nothing for a post that was not previously pending', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'pending', 'post2'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POST, data: {id: 'post3', channel_id: 'channel1'}, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'pending', 'post2'], recent: true}, ], }); }); it('should do nothing for a post without posts loaded for the channel', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POST, data: {id: 'post3', channel_id: 'channel2', pending_post_id: 'pending'}, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); }); }); describe('receiving consecutive recent posts in the channel', () => { it('should save posts in the correct order', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post4'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post3: nextPosts.post3, }, order: ['post1', 'post3'], }, recent: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should not save duplicate posts', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post4: nextPosts.post4, }, order: ['post2', 'post4'], }, recent: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should do nothing when receiving no posts for loaded channel', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: {}, order: [], }, recent: true, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should make entry for channel with no posts', () => { const state = deepFreeze({}); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: {}, order: [], }, recent: true, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [{ order: [], recent: true, }], }); }); it('should not save posts that are not in data.order', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, post3: nextPosts.post3, post4: nextPosts.post4, }, order: ['post1', 'post2'], }, recent: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should not save posts in an older block, even if they may be adjacent', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, recent: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post3', 'post4'], recent: false}, {order: ['post1', 'post2'], recent: true}, ], }); }); it('should not save posts in the recent block even if new posts may be adjacent', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, recent: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post3', 'post4'], recent: false}, {order: ['post1', 'post2'], recent: true}, ], }); }); it('should add posts to non-recent block if there is overlap', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, recent: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); }); describe('receiving consecutive posts in the channel that are not recent', () => { it('should save posts in the correct order', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post4'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post3: nextPosts.post3, }, order: ['post1', 'post3'], }, recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); }); it('should not save duplicate posts', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post4: nextPosts.post4, }, order: ['post2', 'post4'], }, recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); }); it('should do nothing when receiving no posts for loaded channel', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: {}, order: [], }, recent: false, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should make entry for channel with no posts', () => { const state = deepFreeze({}); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: {}, order: [], }, recent: false, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [{ order: [], recent: false, }], }); }); it('should not save posts that are not in data.order', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, post3: nextPosts.post3, post4: nextPosts.post4, }, order: ['post1', 'post2'], }, recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should not save posts in another block without overlap', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post3', 'post4'], recent: false}, {order: ['post1', 'post2'], recent: false}, ], }); }); it('should add posts to recent block if there is overlap', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post3: nextPosts.post3, }, order: ['post2', 'post3'], }, recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should save with chunk as oldest', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_IN_CHANNEL, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post3: nextPosts.post3, }, order: ['post2', 'post3'], }, recent: false, oldest: true, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true, oldest: true}, ], }); }); }); describe('receiving posts since', () => { it('should save posts in the channel in the correct order', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should not save older posts', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post4: nextPosts.post4, }, order: ['post1', 'post4'], }, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should save any posts in between', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post4'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, post5: {id: 'post5', channel_id: 'channel1', create_at: 500}, post6: {id: 'post6', channel_id: 'channel1', create_at: 300}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, post3: nextPosts.post5, post4: nextPosts.post4, post5: nextPosts.post5, post6: nextPosts.post6, }, order: ['post1', 'post2', 'post3', 'post4', 'post5', 'post6'], }, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should do nothing if only receiving updated posts', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post4: nextPosts.post4, }, order: ['post1', 'post4'], }, }, {}, nextPosts); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should not save duplicate posts', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should do nothing when receiving no posts for loaded channel', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: {}, order: [], }, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should do nothing for channel with no posts', () => { const state = deepFreeze({}); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: {}, order: [], }, page: 0, }, {}, {}); expect(nextState).toBe(state); expect(nextState).toEqual({}); }); it('should not save posts that are not in data.order', () => { const state = deepFreeze({ channel1: [ {order: ['post2', 'post3'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post4: nextPosts.post4, }, order: ['post1'], }, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: true}, ], }); }); it('should not save posts in an older block', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, }, {}, nextPosts); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post3', 'post4'], recent: false}, ], }); }); it('should always save posts in the recent block', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_SINCE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); }); describe('receiving posts after', () => { it('should save posts when channel is not loaded', () => { const state = deepFreeze({}); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_AFTER, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, afterPostId: 'post3', recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should save posts when channel is empty', () => { const state = deepFreeze({ channel1: [], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_AFTER, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, afterPostId: 'post3', recent: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should add posts to existing block', () => { const state = deepFreeze({ channel1: [ {order: ['post3', 'post4'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_AFTER, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post2: nextPosts.post2, }, order: ['post1', 'post2'], }, afterPostId: 'post3', }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); }); it('should merge adjacent posts if we have newer posts', () => { const state = deepFreeze({ channel1: [ {order: ['post4'], recent: false}, {order: ['post1', 'post2'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_AFTER, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post3: nextPosts.post3, }, order: ['post2', 'post3'], }, afterPostId: 'post4', }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should do nothing when no posts are received', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_AFTER, channelId: 'channel1', data: { posts: {}, order: [], }, afterPostId: 'post1', }, {}, nextPosts); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); }); }); describe('receiving posts before', () => { it('should save posts when channel is not loaded', () => { const state = deepFreeze({}); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post3: nextPosts.post3, }, order: ['post2', 'post3'], }, beforePostId: 'post1', }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should have oldest set to false', () => { const state = deepFreeze({}); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post3: nextPosts.post3, }, order: ['post2', 'post3'], }, beforePostId: 'post1', oldest: false, }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false, oldest: false}, ], }); }); it('should save posts when channel is empty', () => { const state = deepFreeze({ channel1: [], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channel1', data: { posts: { post2: nextPosts.post2, post3: nextPosts.post3, }, order: ['post2', 'post3'], }, beforePostId: 'post1', }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should add posts to existing block', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: false}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channel1', data: { posts: { post3: nextPosts.post3, post4: nextPosts.post4, }, order: ['post3', 'post4'], }, beforePostId: 'post2', }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); }); it('should merge adjacent posts if we have newer posts', () => { const state = deepFreeze({ channel1: [ {order: ['post4'], recent: false}, {order: ['post1'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, post3: {id: 'post3', channel_id: 'channel1', create_at: 2000}, post4: {id: 'post4', channel_id: 'channel1', create_at: 1000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channel1', data: { posts: { post1: nextPosts.post1, post3: nextPosts.post3, }, order: ['post2', 'post3', 'post4'], }, beforePostId: 'post1', }, {}, nextPosts); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: true}, ], }); }); it('should do nothing when no posts are received', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); const nextPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', create_at: 4000}, post2: {id: 'post2', channel_id: 'channel1', create_at: 3000}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.RECEIVED_POSTS_BEFORE, channelId: 'channel1', data: { posts: {}, order: [], }, beforePostId: 'post2', }, {}, nextPosts); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2'], recent: true}, ], }); }); }); describe('deleting a post', () => { it('should do nothing when deleting a post without comments', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post2, }, prevPosts, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should remove comments on the post when deleting a post with comments', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1', root_id: 'post3'}, post3: {id: 'post3', channel_id: 'channel1'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post3, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post3', 'post4'], recent: false}, ], }); }); it('should remove comments from multiple blocks', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: false}, {order: ['post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1', root_id: 'post4'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post4, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post2'], recent: false}, {order: ['post4'], recent: false}, ], }); }); it('should do nothing to blocks without comments', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: false}, {order: ['post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1', root_id: 'post4'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post4, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState[0]).toBe(state[0]); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2'], recent: false}, {order: ['post4'], recent: false}, ], }); }); it('should do nothing when deleting a comment', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1', root_id: 'post3'}, post3: {id: 'post3', channel_id: 'channel1'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post2, }, prevPosts, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); }); it('should do nothing if the post has not been loaded', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post4, }, prevPosts, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should do nothing if no posts in the channel have been loaded', () => { const state = deepFreeze({}); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post1, }, prevPosts, {}); expect(nextState).toBe(state); expect(nextState).toEqual({}); }); it('should remove empty blocks', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: false}, {order: ['post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1', root_id: 'post4'}, post3: {id: 'post3', channel_id: 'channel1', root_id: 'post4'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_DELETED, data: prevPosts.post4, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post4'], recent: false}, ], }); }); }); describe('removing a post', () => { it('should remove the post', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: prevPosts.post2, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post3'], recent: false}, ], }); }); it('should remove comments on the post', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1', root_id: 'post3'}, post3: {id: 'post3', channel_id: 'channel1'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: prevPosts.post3, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post4'], recent: false}, ], }); }); it('should remove a comment without removing the root post', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1', root_id: 'post3'}, post3: {id: 'post3', channel_id: 'channel1'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: prevPosts.post2, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post3', 'post4'], recent: false}, ], }); }); it('should do nothing if the post has not been loaded', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: prevPosts.post4, }, prevPosts, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], }); }); it('should do nothing if no posts in the channel have been loaded', () => { const state = deepFreeze({}); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: prevPosts.post1, }, prevPosts, {}); expect(nextState).toBe(state); expect(nextState).toEqual({}); }); it('should remove empty blocks', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2'], recent: false}, {order: ['post3', 'post4'], recent: false}, ], }); const prevPosts = toPostsRecord({ post1: {id: 'post1', channel_id: 'channel1', root_id: 'post4'}, post2: {id: 'post2', channel_id: 'channel1'}, post3: {id: 'post3', channel_id: 'channel1', root_id: 'post4'}, post4: {id: 'post4', channel_id: 'channel1'}, }); const nextState = reducers.postsInChannel(state, { type: PostTypes.POST_REMOVED, data: prevPosts.post4, }, prevPosts, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ channel1: [ {order: ['post2'], recent: false}, ], }); }); }); for (const actionType of [ ChannelTypes.RECEIVED_CHANNEL_DELETED, ChannelTypes.DELETE_CHANNEL_SUCCESS, ChannelTypes.LEAVE_CHANNEL, ]) { describe(`when a channel is deleted (${actionType})`, () => { it('should remove any posts in that channel', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, {order: ['post6', 'post7', 'post8'], recent: false}, ], channel2: [ {order: ['post4', 'post5'], recent: false}, ], }); const nextState = reducers.postsInChannel(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: false, }, }, {}, {}); expect(nextState).not.toBe(state); expect(nextState.channel2).toBe(state.channel2); expect(nextState).toEqual({ channel2: [ {order: ['post4', 'post5'], recent: false}, ], }); }); it('should do nothing if no posts in that channel are loaded', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], channel2: [ {order: ['post4', 'post5'], recent: false}, ], }); const nextState = reducers.postsInChannel(state, { type: actionType, data: { id: 'channel3', viewArchivedChannels: false, }, }, {}, {}); expect(nextState).toBe(state); expect(nextState.channel1).toBe(state.channel1); expect(nextState.channel2).toBe(state.channel2); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, ], channel2: [ {order: ['post4', 'post5'], recent: false}, ], }); }); it('should not remove any posts with viewArchivedChannels enabled', () => { const state = deepFreeze({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, {order: ['post6', 'post7', 'post8'], recent: false}, ], channel2: [ {order: ['post4', 'post5'], recent: false}, ], }); const nextState = reducers.postsInChannel(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: true, }, }, {}, {}); expect(nextState).toBe(state); expect(nextState.channel1).toBe(state.channel1); expect(nextState.channel2).toBe(state.channel2); expect(nextState).toEqual({ channel1: [ {order: ['post1', 'post2', 'post3'], recent: false}, {order: ['post6', 'post7', 'post8'], recent: false}, ], channel2: [ {order: ['post4', 'post5'], recent: false}, ], }); }); }); } }); describe('mergePostBlocks', () => { it('should do nothing with no blocks', () => { const blocks: PostOrderBlock[] = []; const posts = {}; const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).toBe(blocks); }); it('should do nothing with only one block', () => { const blocks: PostOrderBlock[] = [ {order: ['a'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).toBe(blocks); }); it('should do nothing with two separate blocks', () => { const blocks = [ {order: ['a'], recent: false}, {order: ['b'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1000}, b: {create_at: 1001}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).toBe(blocks); }); it('should merge two blocks containing exactly the same posts', () => { const blocks = [ {order: ['a'], recent: false}, {order: ['a'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks).toEqual([ {order: ['a'], recent: false}, ]); }); it('should merge two blocks containing overlapping posts', () => { const blocks = [ {order: ['a', 'b', 'c'], recent: false}, {order: ['b', 'c', 'd'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1003}, b: {create_at: 1002}, c: {create_at: 1001}, d: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks).toEqual([ {order: ['a', 'b', 'c', 'd'], recent: false}, ]); }); it('should merge more than two blocks containing overlapping posts', () => { const blocks = [ {order: ['d', 'e'], recent: false}, {order: ['a', 'b'], recent: false}, {order: ['c', 'd'], recent: false}, {order: ['b', 'c'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1004}, b: {create_at: 1003}, c: {create_at: 1002}, d: {create_at: 1001}, e: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks).toEqual([ {order: ['a', 'b', 'c', 'd', 'e'], recent: false}, ]); }); it('should not affect blocks that are not merged', () => { const blocks = [ {order: ['a', 'b'], recent: false}, {order: ['b', 'c'], recent: false}, {order: ['d', 'e'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1004}, b: {create_at: 1003}, c: {create_at: 1002}, d: {create_at: 1001}, e: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks[1]).toBe(blocks[2]); expect(nextBlocks).toEqual([ {order: ['a', 'b', 'c'], recent: false}, {order: ['d', 'e'], recent: false}, ]); }); it('should keep merged blocks marked as recent', () => { const blocks = [ {order: ['a', 'b'], recent: true}, {order: ['b', 'c'], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1002}, b: {create_at: 1001}, c: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks).toEqual([ {order: ['a', 'b', 'c'], recent: true}, ]); }); it('should keep merged blocks marked as oldest', () => { const blocks = [ {order: ['a', 'b'], oldest: true}, {order: ['b', 'c'], oldest: false}, ]; const posts = toPostsRecord({ a: {create_at: 1002}, b: {create_at: 1001}, c: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks).toEqual([ {order: ['a', 'b', 'c'], oldest: true}, ]); }); it('should remove empty blocks', () => { const blocks = [ {order: ['a', 'b'], recent: true}, {order: [], recent: false}, ]; const posts = toPostsRecord({ a: {create_at: 1002}, b: {create_at: 1001}, c: {create_at: 1000}, }); const nextBlocks = reducers.mergePostBlocks(blocks, posts); expect(nextBlocks).not.toBe(blocks); expect(nextBlocks[0]).toBe(blocks[0]); expect(nextBlocks).toEqual([ {order: ['a', 'b'], recent: true}, ]); }); }); describe('mergePostOrder', () => { const tests = [ { name: 'empty arrays', left: [], right: [], expected: [], }, { name: 'empty left array', left: [], right: ['c', 'd'], expected: ['c', 'd'], }, { name: 'empty right array', left: ['a', 'b'], right: [], expected: ['a', 'b'], }, { name: 'distinct arrays', left: ['a', 'b'], right: ['c', 'd'], expected: ['a', 'b', 'c', 'd'], }, { name: 'overlapping arrays', left: ['a', 'b', 'c', 'd'], right: ['c', 'd', 'e', 'f'], expected: ['a', 'b', 'c', 'd', 'e', 'f'], }, { name: 'left array is start of right array', left: ['a', 'b'], right: ['a', 'b', 'c', 'd'], expected: ['a', 'b', 'c', 'd'], }, { name: 'right array is end of left array', left: ['a', 'b', 'c', 'd'], right: ['c', 'd'], expected: ['a', 'b', 'c', 'd'], }, { name: 'left array contains right array', left: ['a', 'b', 'c', 'd'], right: ['b', 'c'], expected: ['a', 'b', 'c', 'd'], }, { name: 'items in second array missing from first', left: ['a', 'c'], right: ['b', 'd', 'e', 'f'], expected: ['a', 'b', 'c', 'd', 'e', 'f'], }, ]; const posts = toPostsRecord({ a: {create_at: 10000}, b: {create_at: 9000}, c: {create_at: 8000}, d: {create_at: 7000}, e: {create_at: 6000}, f: {create_at: 5000}, }); for (const test of tests) { it(test.name, () => { const left = [...test.left]; const right = [...test.right]; const actual = reducers.mergePostOrder(left, right, posts); expect(actual).toEqual(test.expected); // Arguments shouldn't be mutated expect(left).toEqual(test.left); expect(right).toEqual(test.right); }); } }); describe('postsInThread', () => { for (const actionType of [ PostTypes.RECEIVED_POST, PostTypes.RECEIVED_NEW_POST, ]) { describe(`receiving a single post (${actionType})`, () => { it('should replace a previously pending comment', () => { const state = deepFreeze({ root1: ['comment1', 'pending', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: actionType, data: {id: 'comment3', root_id: 'root1', pending_post_id: 'pending'}, }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2', 'comment3'], }); }); it('should do nothing for a pending comment that was already removed', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: actionType, data: {id: 'comment2', root_id: 'root1', pending_post_id: 'pending'}, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); it('should store a comment that was not previously pending', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: actionType, data: {id: 'comment3', root_id: 'root1'}, }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2', 'comment3'], }); }); it('should store a comment without other comments loaded for the thread', () => { const state = deepFreeze({}); const nextState = reducers.postsInThread(state, { type: actionType, data: {id: 'comment1', root_id: 'root1'}, }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1'], }); }); it('should do nothing for a non-comment post', () => { const state = deepFreeze({ root1: ['comment1'], }); const nextState = reducers.postsInThread(state, { type: actionType, data: {id: 'root2'}, }, {}); expect(nextState).toBe(state); expect(nextState.root1).toBe(state.root1); expect(nextState).toEqual({ root1: ['comment1'], }); }); it('should do nothing for a duplicate post', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: actionType, data: {id: 'comment1'}, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); }); } for (const actionType of [ PostTypes.RECEIVED_POSTS_AFTER, PostTypes.RECEIVED_POSTS_BEFORE, PostTypes.RECEIVED_POSTS_IN_CHANNEL, PostTypes.RECEIVED_POSTS_SINCE, ]) { describe(`receiving posts in the channel (${actionType})`, () => { it('should save comments without in the correct threads without sorting', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { comment2: {id: 'comment2', root_id: 'root1'}, comment3: {id: 'comment3', root_id: 'root2'}, comment4: {id: 'comment4', root_id: 'root1'}, }; const nextState = reducers.postsInThread(state, { type: actionType, data: { order: [], posts, }, }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2', 'comment4'], root2: ['comment3'], }); }); it('should not save not-comment posts', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { comment2: {id: 'comment2', root_id: 'root1'}, root2: {id: 'root2'}, comment3: {id: 'comment3', root_id: 'root2'}, }; const nextState = reducers.postsInThread(state, { type: actionType, data: { order: [], posts, }, }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], root2: ['comment3'], }); }); it('should not save duplicate posts', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { comment1: {id: 'comment2', root_id: 'root1'}, comment2: {id: 'comment2', root_id: 'root1'}, }; const nextState = reducers.postsInThread(state, { type: actionType, data: { order: [], posts, }, }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); it('should do nothing when receiving no posts', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = {}; const nextState = reducers.postsInThread(state, { type: actionType, data: { order: [], posts, }, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1'], }); }); it('should do nothing when receiving no comments', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { root2: {id: 'root2'}, }; const nextState = reducers.postsInThread(state, { type: actionType, data: { order: [], posts, }, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1'], }); }); }); } describe('receiving posts in a thread', () => { it('should save comments without sorting', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { comment2: {id: 'comment2', root_id: 'root1'}, comment3: {id: 'comment3', root_id: 'root1'}, }; const nextState = reducers.postsInThread(state, { type: PostTypes.RECEIVED_POSTS_IN_THREAD, data: { order: [], posts, }, rootId: 'root1', }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2', 'comment3'], }); }); it('should not save the root post', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { root2: {id: 'root2'}, comment2: {id: 'comment2', root_id: 'root2'}, comment3: {id: 'comment3', root_id: 'root2'}, }; const nextState = reducers.postsInThread(state, { type: PostTypes.RECEIVED_POSTS_IN_THREAD, data: { order: [], posts, }, rootId: 'root2', }, {}); expect(nextState).not.toBe(state); expect(nextState.root1).toBe(state.root1); expect(nextState).toEqual({ root1: ['comment1'], root2: ['comment2', 'comment3'], }); }); it('should not save duplicate posts', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = { comment1: {id: 'comment1', root_id: 'root1'}, comment2: {id: 'comment2', root_id: 'root1'}, }; const nextState = reducers.postsInThread(state, { type: PostTypes.RECEIVED_POSTS_IN_THREAD, data: { order: [], posts, }, rootId: 'root1', }, {}); expect(nextState).not.toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); it('should do nothing when receiving no posts', () => { const state = deepFreeze({ root1: ['comment1'], }); const posts = {}; const nextState = reducers.postsInThread(state, { type: PostTypes.RECEIVED_POSTS_IN_THREAD, data: { order: [], posts, }, rootId: 'root2', }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1'], }); }); }); describe('deleting a post', () => { it('should remove the thread when deleting the root post', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], root2: ['comment3'], }); const nextState = reducers.postsInThread(state, { type: PostTypes.POST_DELETED, data: {id: 'root1'}, }, {}); expect(nextState).not.toBe(state); expect(nextState.root2).toBe(state.root2); expect(nextState).toEqual({ root2: ['comment3'], }); }); it('should do nothing when deleting a comment', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: PostTypes.POST_DELETED, data: {id: 'comment1'}, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); it('should do nothing if deleting a post without comments', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: PostTypes.POST_DELETED, data: {id: 'root2'}, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); }); describe('removing a post', () => { it('should remove the thread when removing the root post', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], root2: ['comment3'], }); const nextState = reducers.postsInThread(state, { type: PostTypes.POST_REMOVED, data: {id: 'root1'}, }, {}); expect(nextState).not.toBe(state); expect(nextState.root2).toBe(state.root2); expect(nextState).toEqual({ root2: ['comment3'], }); }); it('should remove an entry from the thread when removing a comment', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], root2: ['comment3'], }); const nextState = reducers.postsInThread(state, { type: PostTypes.POST_REMOVED, data: {id: 'comment1', root_id: 'root1'}, }, {}); expect(nextState).not.toBe(state); expect(nextState.root2).toBe(state.root2); expect(nextState).toEqual({ root1: ['comment2'], root2: ['comment3'], }); }); it('should do nothing if removing a thread that has not been loaded', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const nextState = reducers.postsInThread(state, { type: PostTypes.POST_REMOVED, data: {id: 'root2'}, }, {}); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); }); for (const actionType of [ ChannelTypes.RECEIVED_CHANNEL_DELETED, ChannelTypes.DELETE_CHANNEL_SUCCESS, ChannelTypes.LEAVE_CHANNEL, ]) { describe(`when a channel is deleted (${actionType})`, () => { it('should remove any threads in that channel', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], root2: ['comment3'], root3: ['comment4'], }); const prevPosts = toPostsRecord({ root1: {id: 'root1', channel_id: 'channel1'}, comment1: {id: 'comment1', channel_id: 'channel1', root_id: 'root1'}, comment2: {id: 'comment2', channel_id: 'channel1', root_id: 'root1'}, root2: {id: 'root2', channel_id: 'channel2'}, comment3: {id: 'comment3', channel_id: 'channel2', root_id: 'root2'}, root3: {id: 'root3', channel_id: 'channel1'}, comment4: {id: 'comment3', channel_id: 'channel1', root_id: 'root3'}, }); const nextState = reducers.postsInThread(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: false, }, }, prevPosts); expect(nextState).not.toBe(state); expect(nextState.root2).toBe(state.root2); expect(nextState).toEqual({ root2: ['comment3'], }); }); it('should do nothing if no threads in that channel are loaded', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], }); const prevPosts = toPostsRecord({ root1: {id: 'root1', channel_id: 'channel1'}, comment1: {id: 'comment1', channel_id: 'channel1', root_id: 'root1'}, comment2: {id: 'comment2', channel_id: 'channel1', root_id: 'root1'}, }); const nextState = reducers.postsInThread(state, { type: actionType, data: { id: 'channel2', viewArchivedChannels: false, }, }, prevPosts); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], }); }); it('should not remove any posts with viewArchivedChannels enabled', () => { const state = deepFreeze({ root1: ['comment1', 'comment2'], root2: ['comment3'], }); const prevPosts = toPostsRecord({ root1: {id: 'root1', channel_id: 'channel1'}, comment1: {id: 'comment1', channel_id: 'channel1', root_id: 'root1'}, comment2: {id: 'comment2', channel_id: 'channel1', root_id: 'root1'}, root2: {id: 'root2', channel_id: 'channel2'}, comment3: {id: 'comment3', channel_id: 'channel2', root_id: 'root2'}, }); const nextState = reducers.postsInThread(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: true, }, }, prevPosts); expect(nextState).toBe(state); expect(nextState).toEqual({ root1: ['comment1', 'comment2'], root2: ['comment3'], }); }); it('should not error if a post is missing from prevPosts', () => { const state = deepFreeze({ root1: ['comment1'], }); const prevPosts = toPostsRecord({ comment1: {id: 'comment1', channel_id: 'channel1', root_id: 'root1'}, }); const nextState = reducers.postsInThread(state, { type: actionType, data: { id: 'channel1', viewArchivedChannels: false, }, }, prevPosts); expect(nextState).toBe(state); }); }); } }); describe('removeUnneededMetadata', () => { it('without metadata', () => { const post = deepFreeze({ id: 'post', }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).toEqual(post); }); it('with empty metadata', () => { const post = deepFreeze({ id: 'post', metadata: {}, }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).toEqual(post); }); it('should remove emojis', () => { const post = deepFreeze({ id: 'post', metadata: { emojis: [{name: 'emoji'}], }, }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).not.toEqual(post); expect(nextPost).toEqual({ id: 'post', metadata: {}, }); }); it('should remove files', () => { const post = deepFreeze({ id: 'post', metadata: { files: [{id: 'file', post_id: 'post'}], }, }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).not.toEqual(post); expect(nextPost).toEqual({ id: 'post', metadata: {}, }); }); it('should remove reactions', () => { const post = deepFreeze({ id: 'post', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '+1'}, {user_id: 'efgh', emoji_name: '+1'}, {user_id: 'abcd', emoji_name: '-1'}, ], }, }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).not.toEqual(post); expect(nextPost).toEqual({ id: 'post', metadata: {}, }); }); it('should remove OpenGraph data', () => { const post = deepFreeze({ id: 'post', metadata: { embeds: [{ type: 'opengraph', url: 'https://example.com', data: { url: 'https://example.com', images: [{ url: 'https://example.com/logo.png', width: 100, height: 100, }], }, }], }, }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).not.toEqual(post); expect(nextPost).toEqual({ id: 'post', metadata: { embeds: [{ type: 'opengraph', url: 'https://example.com', }], }, }); }); it('should not affect non-OpenGraph embeds', () => { const post = deepFreeze({ id: 'post', metadata: { embeds: [ {type: 'image', url: 'https://example.com/image'}, {type: 'message_attachment'}, ], }, props: { attachments: [ {text: 'This is an attachment'}, ], }, }); const nextPost = reducers.removeUnneededMetadata(post); expect(nextPost).toEqual(post); }); }); describe('reactions', () => { for (const actionType of [ PostTypes.RECEIVED_NEW_POST, PostTypes.RECEIVED_POST, ]) { describe(`single post received (${actionType})`, () => { it('no post metadata', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', }, }; const nextState = reducers.reactions(state, action); expect(nextState).toEqual(state); }); it('no reactions in post metadata', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: {reactions: []}, }, }; const nextState = reducers.reactions(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: {}, }); }); it('should not clobber reactions when metadata empty', () => { const state = deepFreeze({post: {name: 'smiley', post_id: 'post'}}); const action = { type: actionType, data: { id: 'post', metadata: {}, }, }; const nextState = reducers.reactions(state, action); expect(nextState).toEqual({ post: {name: 'smiley', post_id: 'post'}, }); }); it('should save reactions', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '+1'}, {user_id: 'efgh', emoji_name: '+1'}, {user_id: 'abcd', emoji_name: '-1'}, ], }, }, }; const nextState = reducers.reactions(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: { 'abcd-+1': {user_id: 'abcd', emoji_name: '+1'}, 'efgh-+1': {user_id: 'efgh', emoji_name: '+1'}, 'abcd--1': {user_id: 'abcd', emoji_name: '-1'}, }, }); }); it('should not save reaction for a deleted post', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', delete_at: '1571366424287', }, }; const nextState = reducers.reactions(state, action); expect(nextState).toEqual(state); }); }); } describe('receiving multiple posts', () => { it('no post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', }, }, }, }; const nextState = reducers.reactions(state, action); expect(nextState).toEqual(state); }); it('no reactions in post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: {reactions: []}, }, }, }, }; const nextState = reducers.reactions(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: {}, }); }); it('should save reactions', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '+1'}, {user_id: 'efgh', emoji_name: '+1'}, {user_id: 'abcd', emoji_name: '-1'}, ], }, }, }, }, }; const nextState = reducers.reactions(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: { 'abcd-+1': {user_id: 'abcd', emoji_name: '+1'}, 'efgh-+1': {user_id: 'efgh', emoji_name: '+1'}, 'abcd--1': {user_id: 'abcd', emoji_name: '-1'}, }, }); }); it('should save reactions for multiple posts', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '+1'}, ], }, }, post2: { id: 'post2', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '-1'}, ], }, }, }, }, }; const nextState = reducers.reactions(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: { 'abcd-+1': {user_id: 'abcd', emoji_name: '+1'}, }, post2: { 'abcd--1': {user_id: 'abcd', emoji_name: '-1'}, }, }); }); it('should save reactions for multiple posts except deleted posts', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '+1'}, ], }, }, post2: { id: 'post2', delete_at: '1571366424287', metadata: { reactions: [ {user_id: 'abcd', emoji_name: '-1'}, ], }, }, }, }, }; const nextState = reducers.reactions(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: { 'abcd-+1': {user_id: 'abcd', emoji_name: '+1'}, }, }); }); }); }); describe('opengraph', () => { for (const actionType of [ PostTypes.RECEIVED_NEW_POST, PostTypes.RECEIVED_POST, ]) { describe(`single post received (${actionType})`, () => { it('no post metadata', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', }, }; const nextState = reducers.openGraph(state, action); expect(nextState).toEqual(state); }); it('no embeds in post metadata', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: {}, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).toEqual(state); }); it('other types of embeds in post metadata', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: { embeds: [{ type: 'image', url: 'https://example.com/image.png', }, { type: 'message_attachment', }], }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).toEqual(state); }); it('should save opengraph data', () => { const state = deepFreeze({}); const action = { type: actionType, data: { id: 'post', metadata: { embeds: [{ type: 'opengraph', url: 'https://example.com', data: { title: 'Example', description: 'Example description', }, }], }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post: {'https://example.com': action.data.metadata.embeds[0].data}, }); }); }); } describe('receiving multiple posts', () => { it('no post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', }, }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).toEqual(state); }); it('no embeds in post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: {}, }, }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).toEqual(state); }); it('other types of embeds in post metadata', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post: { id: 'post', metadata: { embeds: [{ type: 'image', url: 'https://example.com/image.png', }, { type: 'message_attachment', }], }, }, }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).toEqual(state); }); it('should save opengraph data', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { embeds: [{ type: 'opengraph', url: 'https://example.com', data: { title: 'Example', description: 'Example description', }, }], }, }, }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: {'https://example.com': action.data.posts.post1.metadata.embeds[0].data}, }); }); it('should save reactions for multiple posts', () => { const state = deepFreeze({}); const action = { type: PostTypes.RECEIVED_POSTS, data: { posts: { post1: { id: 'post1', metadata: { embeds: [{ type: 'opengraph', url: 'https://example.com', data: { title: 'Example', description: 'Example description', }, }], }, }, post2: { id: 'post2', metadata: { embeds: [{ type: 'opengraph', url: 'https://google.ca', data: { title: 'Google', description: 'Something about search', }, }], }, }, }, }, }; const nextState = reducers.openGraph(state, action); expect(nextState).not.toEqual(state); expect(nextState).toEqual({ post1: {'https://example.com': action.data.posts.post1.metadata.embeds[0].data}, post2: {'https://google.ca': action.data.posts.post2.metadata.embeds[0].data}, }); }); }); }); describe('removeNonRecentEmptyPostBlocks', () => { it('should filter empty blocks', () => { const blocks = [{ order: [], recent: false, }, { order: ['1', '2'], recent: false, }]; const filteredBlocks = reducers.removeNonRecentEmptyPostBlocks(blocks); expect(filteredBlocks).toEqual([{ order: ['1', '2'], recent: false, }]); }); it('should not filter empty recent block', () => { const blocks = [{ order: [], recent: true, }, { order: ['1', '2'], recent: false, }, { order: [], recent: false, }]; const filteredBlocks = reducers.removeNonRecentEmptyPostBlocks(blocks); expect(filteredBlocks).toEqual([{ order: [], recent: true, }, { order: ['1', '2'], recent: false, }]); }); }); describe('postsReplies', () => { const initialState = { 123: 3, 456: 6, 789: 9, }; describe('received post', () => { const testTable = [ {name: 'pending post (no id)', action: PostTypes.RECEIVED_POST, state: {...initialState}, post: {root_id: '123'}, nextState: {...initialState}}, {name: 'root post (no root_id)', action: PostTypes.RECEIVED_POST, state: {...initialState}, post: {id: '123'}, nextState: {...initialState}}, {name: 'new reply without reply count', action: PostTypes.RECEIVED_POST, state: {...initialState}, post: {id: '123', root_id: '123'}, nextState: {...initialState, 123: 3}}, {name: 'new reply with reply count', action: PostTypes.RECEIVED_POST, state: {...initialState}, post: {id: '123', root_id: '123', reply_count: 7}, nextState: {...initialState, 123: 7}}, {name: 'pending post (no id) (new post action)', action: PostTypes.RECEIVED_NEW_POST, state: {...initialState}, post: {root_id: '123'}, nextState: {...initialState}}, {name: 'root post (no root_id) (new post action)', action: PostTypes.RECEIVED_NEW_POST, state: {...initialState}, post: {id: '123'}, nextState: {...initialState}}, {name: 'new reply without reply count (new post action)', action: PostTypes.RECEIVED_NEW_POST, state: {...initialState}, post: {id: '123', root_id: '123'}, nextState: {...initialState, 123: 3}}, {name: 'new reply with reply count (new post action)', action: PostTypes.RECEIVED_NEW_POST, state: {...initialState}, post: {id: '123', root_id: '123', reply_count: 7}, nextState: {...initialState, 123: 7}}, ]; for (const testCase of testTable) { it(testCase.name, () => { const state = deepFreeze(testCase.state); const nextState = reducers.nextPostsReplies(state, { type: testCase.action, data: testCase.post, }); expect(nextState).toEqual(testCase.nextState); }); } }); describe('received posts', () => { const testTable = [ {name: 'received empty posts list', action: PostTypes.RECEIVED_POSTS, state: {...initialState}, posts: [], nextState: {...initialState}}, { name: 'received posts to existing counters', action: PostTypes.RECEIVED_POSTS, state: {...initialState}, posts: [ {id: '123', reply_count: 1}, {id: '456', reply_count: 8}, ], nextState: {...initialState, 123: 1, 456: 8}, }, { name: 'received replies to existing counters', action: PostTypes.RECEIVED_POSTS, state: {...initialState}, posts: [ {id: '000', root_id: '123', reply_count: 1}, {id: '111', root_id: '456', reply_count: 8}, ], nextState: {...initialState, 123: 1, 456: 8}, }, { name: 'received posts to new counters', action: PostTypes.RECEIVED_POSTS, state: {...initialState}, posts: [ {id: '321', reply_count: 1}, {id: '654', reply_count: 8}, ], nextState: {...initialState, 321: 1, 654: 8}, }, { name: 'received replies to new counters', action: PostTypes.RECEIVED_POSTS, state: {...initialState}, posts: [ {id: '000', root_id: '321', reply_count: 1}, {id: '111', root_id: '654', reply_count: 8}, ], nextState: {...initialState, 321: 1, 654: 8}, }, { name: 'received posts and replies to new and existing counters', action: PostTypes.RECEIVED_POSTS, state: {...initialState}, posts: [ {id: '000', root_id: '123', reply_count: 4}, {id: '111', root_id: '456', reply_count: 7}, {id: '000', root_id: '321', reply_count: 1}, {id: '111', root_id: '654', reply_count: 8}, ], nextState: {...initialState, 123: 4, 456: 7, 321: 1, 654: 8}, }, ]; for (const testCase of testTable) { it(testCase.name, () => { const state = deepFreeze(testCase.state); const nextState = reducers.nextPostsReplies(state, { type: testCase.action, data: {posts: testCase.posts}, }); expect(nextState).toEqual(testCase.nextState); }); } }); describe('deleted posts', () => { const testTable = [ {name: 'deleted not tracked post', action: PostTypes.POST_DELETED, state: {...initialState}, post: {id: '000', root_id: '111'}, nextState: {...initialState}}, {name: 'deleted reply', action: PostTypes.POST_DELETED, state: {...initialState}, post: {id: '000', root_id: '123'}, nextState: {...initialState, 123: 2}}, {name: 'deleted root post', action: PostTypes.POST_DELETED, state: {...initialState}, post: {id: '123'}, nextState: {456: 6, 789: 9}}, ]; for (const testCase of testTable) { it(testCase.name, () => { const state = deepFreeze(testCase.state); const nextState = reducers.nextPostsReplies(state, { type: testCase.action, data: testCase.post, }); expect(nextState).toEqual(testCase.nextState); }); } }); }); describe('limitedViews', () => { const zeroState = deepFreeze(reducers.zeroStateLimitedViews); const receivedPostActions = [ PostTypes.RECEIVED_POSTS, PostTypes.RECEIVED_POSTS_AFTER, PostTypes.RECEIVED_POSTS_BEFORE, PostTypes.RECEIVED_POSTS_SINCE, PostTypes.RECEIVED_POSTS_IN_CHANNEL, ]; const forgetChannelActions = [ ChannelTypes.RECEIVED_CHANNEL_DELETED, ChannelTypes.DELETE_CHANNEL_SUCCESS, ChannelTypes.LEAVE_CHANNEL, ]; receivedPostActions.forEach((action) => { it(`${action} does nothing if all posts are accessible`, () => { const nextState = reducers.limitedViews(zeroState, { type: action, channelId: 'channelId', data: { first_inaccessible_post_time: 0, }, }); expect(nextState).toEqual(zeroState); }); it(`${action} does nothing if action does not contain channelId`, () => { const nextState = reducers.limitedViews(zeroState, { type: action, data: { first_inaccessible_post_time: 123, }, }); expect(nextState).toEqual(zeroState); }); it(`${action} sets channel view to limited if inaccessible post time exists and channel id is present in action`, () => { const nextState = reducers.limitedViews(zeroState, { type: action, channelId: 'channelId', data: { first_inaccessible_post_time: 123, }, }); expect(nextState).toEqual({...zeroState, channels: {channelId: 123}}); }); }); it(`${PostTypes.RECEIVED_POSTS_IN_THREAD} does nothing if inaccessible post time is 0`, () => { const nextState = reducers.limitedViews(zeroState, { type: PostTypes.RECEIVED_POSTS_IN_THREAD, rootId: 'rootId', data: { first_inaccessible_post_time: 0, }, }); expect(nextState).toEqual(zeroState); }); it(`${PostTypes.RECEIVED_POSTS_IN_THREAD} sets threads view to limited if has inaccessible post time and channel id is present in action`, () => { const nextState = reducers.limitedViews(zeroState, { type: PostTypes.RECEIVED_POSTS_IN_THREAD, rootId: 'rootId', data: { first_inaccessible_post_time: 123, }, }); expect(nextState).toEqual({...zeroState, threads: {rootId: 123}}); }); it(`${CloudTypes.RECEIVED_CLOUD_LIMITS} clears out limited views if there are no longer message limits`, () => { const nextState = reducers.limitedViews({...zeroState, threads: {rootId: 123}}, { type: CloudTypes.RECEIVED_CLOUD_LIMITS, data: { limits: {}, }, }); expect(nextState).toEqual(zeroState); }); it(`${CloudTypes.RECEIVED_CLOUD_LIMITS} preserves limited views if there are still message limits`, () => { const initialState = {...zeroState, threads: {rootId: 123}}; const nextState = reducers.limitedViews(initialState, { type: CloudTypes.RECEIVED_CLOUD_LIMITS, data: { limits: { messages: { history: 10000, }, }, }, }); expect(nextState).toEqual(initialState); }); forgetChannelActions.forEach((action) => { const initialState = {...zeroState, channels: {channelId: 123}}; it(`${action} does nothing if archived channel is still visible`, () => { const nextState = reducers.limitedViews(initialState, { type: action, data: { viewArchivedChannels: true, id: 'channelId', }, }); expect(nextState).toEqual(initialState); }); it(`${action} does nothing if archived channel is not limited`, () => { const nextState = reducers.limitedViews(initialState, { type: action, data: { id: 'channelId2', }, }); expect(nextState).toEqual(initialState); // e.g. old state should have been returned; // reference equality should have been preserved expect(nextState).toBe(initialState); }); it(`${action} removes deleted channel`, () => { const nextState = reducers.limitedViews(initialState, { type: action, data: { id: 'channelId', }, }); expect(nextState).toEqual(zeroState); }); }); });
4,031
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/search.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { PostTypes, SearchTypes, UserTypes, } from 'mattermost-redux/action_types'; import reducer from 'mattermost-redux/reducers/entities/search'; import type {GenericAction} from 'mattermost-redux/types/actions'; type SearchState = ReturnType<typeof reducer>; describe('reducers.entities.search', () => { describe('results', () => { it('initial state', () => { const inputState = undefined; // eslint-disable-line no-undef const action = {}; const expectedState: any = []; const actualState = reducer({results: inputState} as SearchState, action as GenericAction); expect(actualState.results).toEqual(expectedState); }); describe('SearchTypes.RECEIVED_SEARCH_POSTS', () => { it('first results received', () => { const inputState: string[] = []; const action = { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: { order: ['abcd', 'efgh'], posts: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, }, }; const expectedState = ['abcd', 'efgh']; const actualState = reducer({results: inputState} as SearchState, action); expect(actualState.results).toEqual(expectedState); }); it('multiple results received', () => { const inputState = ['1234', '1235']; const action = { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: { order: ['abcd', 'efgh'], posts: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, }, }; const expectedState = ['abcd', 'efgh']; const actualState = reducer({results: inputState} as SearchState, action); expect(actualState.results).toEqual(expectedState); }); }); describe('PostTypes.POST_REMOVED', () => { it('post in results', () => { const inputState = ['abcd', 'efgh']; const action = { type: PostTypes.POST_REMOVED, data: { id: 'efgh', }, }; const expectedState = ['abcd']; const actualState = reducer({results: inputState} as SearchState, action); expect(actualState.results).toEqual(expectedState); }); it('post not in results', () => { const inputState = ['abcd', 'efgh']; const action = { type: PostTypes.POST_REMOVED, data: { id: '1234', }, }; const expectedState = ['abcd', 'efgh']; const actualState = reducer({results: inputState} as SearchState, action); expect(actualState.results).toEqual(expectedState); expect(actualState.results).toEqual(inputState); }); }); describe('SearchTypes.REMOVE_SEARCH_POSTS', () => { const inputState = ['abcd', 'efgh']; const action = { type: SearchTypes.REMOVE_SEARCH_POSTS, }; const expectedState: string[] = []; const actualState = reducer({results: inputState} as SearchState, action); expect(actualState.results).toEqual(expectedState); }); describe('UserTypes.LOGOUT_SUCCESS', () => { const inputState = ['abcd', 'efgh']; const action = { type: UserTypes.LOGOUT_SUCCESS, }; const expectedState: string[] = []; const actualState = reducer({results: inputState} as SearchState, action); expect(actualState.results).toEqual(expectedState); }); }); describe('fileResults', () => { it('initial state', () => { const inputState = undefined; // eslint-disable-line no-undef const action = {}; const expectedState: string[] = []; const actualState = reducer({fileResults: inputState} as SearchState, action as GenericAction); expect(actualState.fileResults).toEqual(expectedState); }); describe('SearchTypes.RECEIVED_SEARCH_POSTS', () => { it('first file results received', () => { const inputState: string[] = []; const action = { type: SearchTypes.RECEIVED_SEARCH_FILES, data: { order: ['abcd', 'efgh'], file_infos: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, }, }; const expectedState = ['abcd', 'efgh']; const actualState = reducer({fileResults: inputState} as SearchState, action); expect(actualState.fileResults).toEqual(expectedState); }); it('multiple file results received', () => { const inputState = ['1234', '1235']; const action = { type: SearchTypes.RECEIVED_SEARCH_FILES, data: { order: ['abcd', 'efgh'], file_infos: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, }, }; const expectedState = ['abcd', 'efgh']; const actualState = reducer({fileResults: inputState} as SearchState, action); expect(actualState.fileResults).toEqual(expectedState); }); }); describe('SearchTypes.REMOVE_SEARCH_FILES', () => { const inputState = ['abcd', 'efgh']; const action = { type: SearchTypes.REMOVE_SEARCH_FILES, }; const expectedState: string[] = []; const actualState = reducer({fileResults: inputState} as SearchState, action); expect(actualState.fileResults).toEqual(expectedState); }); describe('UserTypes.LOGOUT_SUCCESS', () => { const inputState = ['abcd', 'efgh']; const action = { type: UserTypes.LOGOUT_SUCCESS, }; const expectedState: string[] = []; const actualState = reducer({fileResults: inputState} as SearchState, action); expect(actualState.fileResults).toEqual(expectedState); }); }); describe('matches', () => { it('initial state', () => { const inputState = undefined; // eslint-disable-line no-undef const action = {}; const expectedState = {}; const actualState = reducer({matches: inputState} as SearchState, action as GenericAction); expect(actualState.matches).toEqual(expectedState); }); describe('SearchTypes.RECEIVED_SEARCH_POSTS', () => { it('no matches received', () => { const inputState = {}; const action = { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: { order: ['abcd', 'efgh'], posts: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, }, }; const expectedState = {}; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); }); it('first results received', () => { const inputState = {}; const action = { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: { order: ['abcd', 'efgh'], posts: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, matches: { abcd: ['test', 'testing'], efgh: ['tests'], }, }, }; const expectedState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); }); it('multiple results received', () => { const inputState = { 1234: ['foo', 'bar'], 5678: ['foo'], }; const action = { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: { order: ['abcd', 'efgh'], posts: { abcd: {id: 'abcd'}, efgh: {id: 'efgh'}, }, matches: { abcd: ['test', 'testing'], efgh: ['tests'], }, }, }; const expectedState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); }); }); describe('PostTypes.POST_REMOVED', () => { it('post in results', () => { const inputState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const action = { type: PostTypes.POST_REMOVED, data: { id: 'efgh', }, }; const expectedState = { abcd: ['test', 'testing'], }; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); }); it('post not in results', () => { const inputState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const action = { type: PostTypes.POST_REMOVED, data: { id: '1234', }, }; const expectedState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); expect(actualState.matches).toEqual(inputState); }); }); describe('SearchTypes.REMOVE_SEARCH_POSTS', () => { const inputState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const action = { type: SearchTypes.REMOVE_SEARCH_POSTS, }; const expectedState = {}; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); }); describe('UserTypes.LOGOUT_SUCCESS', () => { const inputState = { abcd: ['test', 'testing'], efgh: ['tests'], }; const action = { type: UserTypes.LOGOUT_SUCCESS, }; const expectedState = {}; const actualState = reducer({matches: inputState} as SearchState, action); expect(actualState.matches).toEqual(expectedState); }); }); describe('pinned', () => { it('do not show multiples of the same post', () => { const inputState = { abcd: ['1234', '5678'], }; const action = { type: PostTypes.RECEIVED_POST, data: { id: '5678', is_pinned: true, channel_id: 'abcd', }, }; const actualState = reducer({pinned: inputState} as unknown as SearchState, action); expect(actualState.pinned).toEqual(inputState); }); }); });
4,033
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/teams.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {TeamTypes, AdminTypes} from 'mattermost-redux/action_types'; import teamsReducer from 'mattermost-redux/reducers/entities/teams'; import type {GenericAction} from 'mattermost-redux/types/actions'; import deepFreeze from 'mattermost-redux/utils/deep_freeze'; type ReducerState = ReturnType<typeof teamsReducer>; describe('Reducers.teams.myMembers', () => { it('initial state', async () => { let state = {} as ReducerState; state = teamsReducer(state, {} as GenericAction); expect(state.myMembers).toEqual({}); }); it('RECEIVED_MY_TEAM_MEMBER', async () => { const myMember1 = {user_id: 'user_id_1', team_id: 'team_id_1', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const myMember2 = {user_id: 'user_id_2', team_id: 'team_id_2', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const myMember3 = {user_id: 'user_id_3', team_id: 'team_id_3', delete_at: 1, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; let state = {myMembers: {team_id_1: myMember1}} as unknown as ReducerState; const testAction = { type: TeamTypes.RECEIVED_MY_TEAM_MEMBER, data: myMember2, result: {team_id_1: myMember1, team_id_2: myMember2}, }; state = teamsReducer(state, testAction); expect(state.myMembers).toEqual(testAction.result); testAction.data = myMember3; state = teamsReducer(state, {} as GenericAction); expect(state.myMembers).toEqual(testAction.result); }); it('RECEIVED_MY_TEAM_MEMBERS', async () => { let state = {} as ReducerState; const myMember1 = {user_id: 'user_id_1', team_id: 'team_id_1', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const myMember2 = {user_id: 'user_id_2', team_id: 'team_id_2', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const myMember3 = {user_id: 'user_id_3', team_id: 'team_id_3', delete_at: 1, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const testAction = { type: TeamTypes.RECEIVED_MY_TEAM_MEMBERS, data: [myMember1, myMember2, myMember3], result: {team_id_1: myMember1, team_id_2: myMember2}, }; state = teamsReducer(state, testAction); expect(state.myMembers).toEqual(testAction.result); state = teamsReducer(state, {} as GenericAction); expect(state.myMembers).toEqual(testAction.result); }); it('RECEIVED_TEAMS_LIST', async () => { const team1 = {name: 'team-1', id: 'team_id_1', delete_at: 0}; const team2 = {name: 'team-2', id: 'team_id_2', delete_at: 0}; const team3 = {name: 'team-3', id: 'team_id_3', delete_at: 0}; let state = { myMembers: { team_id_1: {...team1, msg_count: 0, mention_count: 0}, team_id_2: {...team2, msg_count: 0, mention_count: 0}, }, } as unknown as ReducerState; const testAction = { type: TeamTypes.RECEIVED_TEAMS_LIST, data: [team3], result: { team_id_1: {...team1, msg_count: 0, mention_count: 0}, team_id_2: {...team2, msg_count: 0, mention_count: 0}, }, }; // do not add a team when it's not on the teams.myMembers list state = teamsReducer(state, testAction); expect(state.myMembers).toEqual(testAction.result); // remove deleted team to teams.myMembers list team2.delete_at = 1; testAction.data = [team2]; state = teamsReducer(state, testAction); expect(state.myMembers).toEqual({team_id_1: {...team1, msg_count: 0, mention_count: 0}}); }); it('RECEIVED_TEAMS', async () => { const myMember1 = {user_id: 'user_id_1', team_id: 'team_id_1', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const myMember2 = {user_id: 'user_id_2', team_id: 'team_id_2', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; const myMember3 = {user_id: 'user_id_3', team_id: 'team_id_3', delete_at: 0, mention_count: 0, mention_count_root: 0, msg_count: 0, msg_count_root: 0}; let state = {myMembers: {team_id_1: myMember1, team_id_2: myMember2}} as unknown as ReducerState; const testAction = { type: TeamTypes.RECEIVED_TEAMS, data: {team_id_3: myMember3}, result: {team_id_1: myMember1, team_id_2: myMember2}, }; // do not add a team when it's not on the teams.myMembers list state = teamsReducer(state, testAction); expect(state.myMembers).toEqual(testAction.result); // remove deleted team to teams.myMembers list myMember2.delete_at = 1; testAction.data = {team_id_2: myMember2} as any; state = teamsReducer(state, testAction); expect(state.myMembers).toEqual({team_id_1: myMember1}); }); }); describe('Data Retention Teams', () => { it('RECEIVED_DATA_RETENTION_CUSTOM_POLICY_TEAMS', async () => { const state = deepFreeze({ currentTeamId: '', teams: { team1: { id: 'team1', }, team2: { id: 'team2', }, team3: { id: 'team3', }, }, myMembers: {}, membersInTeam: {}, totalCount: 0, stats: {}, groupsAssociatedToTeam: {}, }); const nextState = teamsReducer(state, { type: AdminTypes.RECEIVED_DATA_RETENTION_CUSTOM_POLICY_TEAMS, data: { teams: [{ id: 'team4', }], total_count: 1, }, }); expect(nextState).not.toBe(state); expect(nextState.teams.team1).toEqual({ id: 'team1', }); expect(nextState.teams.team2).toEqual({ id: 'team2', }); expect(nextState.teams.team3).toEqual({ id: 'team3', }); expect(nextState.teams.team4).toEqual({ id: 'team4', }); }); it('REMOVE_DATA_RETENTION_CUSTOM_POLICY_TEAMS_SUCCESS', async () => { const state = deepFreeze({ currentTeamId: '', teams: { team1: { id: 'team1', policy_id: 'policy1', }, team2: { id: 'team2', policy_id: 'policy1', }, team3: { id: 'team3', policy_id: 'policy1', }, }, myMembers: {}, membersInTeam: {}, totalCount: 0, stats: {}, groupsAssociatedToTeam: {}, }); const nextState = teamsReducer(state, { type: AdminTypes.REMOVE_DATA_RETENTION_CUSTOM_POLICY_TEAMS_SUCCESS, data: { teams: ['team1', 'team2'], }, }); expect(nextState).not.toBe(state); expect(nextState.teams.team1).toEqual({ id: 'team1', policy_id: null, }); expect(nextState.teams.team2).toEqual({ id: 'team2', policy_id: null, }); expect(nextState.teams.team3).toEqual({ id: 'team3', policy_id: 'policy1', }); }); it('RECEIVED_DATA_RETENTION_CUSTOM_POLICY_TEAMS_SEARCH', async () => { const state = deepFreeze({ currentTeamId: '', teams: { team1: { id: 'team1', }, team2: { id: 'team2', }, team3: { id: 'team3', }, }, myMembers: {}, membersInTeam: {}, totalCount: 0, stats: {}, groupsAssociatedToTeam: {}, }); const nextState = teamsReducer(state, { type: AdminTypes.RECEIVED_DATA_RETENTION_CUSTOM_POLICY_TEAMS_SEARCH, data: [ { id: 'team1', }, { id: 'team4', }, ], }); expect(nextState).not.toBe(state); expect(nextState.teams.team1).toEqual({ id: 'team1', }); expect(nextState.teams.team2).toEqual({ id: 'team2', }); expect(nextState.teams.team3).toEqual({ id: 'team3', }); expect(nextState.teams.team4).toEqual({ id: 'team4', }); }); });
4,035
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/typing.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {WebsocketEvents} from 'mattermost-redux/constants'; import typingReducer from 'mattermost-redux/reducers/entities/typing'; import type {GenericAction} from 'mattermost-redux/types/actions'; import TestHelper from '../../../test/test_helper'; describe('Reducers.Typing', () => { it('initial state', async () => { let state = {}; state = typingReducer( state, {} as GenericAction, ); expect(state).toEqual({}); }); it('WebsocketEvents.TYPING', async () => { let state = {}; const id1 = TestHelper.generateId(); const userId1 = TestHelper.generateId(); const now1 = 1234; state = typingReducer( state, { type: WebsocketEvents.TYPING, data: { id: id1, userId: userId1, now: now1, }, }, ); // first user typing expect(state).toEqual({ [id1]: { [userId1]: now1, }, }); const id2 = TestHelper.generateId(); const now2 = 1235; state = typingReducer( state, { type: WebsocketEvents.TYPING, data: { id: id2, userId: userId1, now: now2, }, }, ); // user typing in second channel expect(state).toEqual({ [id1]: { [userId1]: now1, }, [id2]: { [userId1]: now2, }, }); const userId2 = TestHelper.generateId(); const now3 = 1237; state = typingReducer( state, { type: WebsocketEvents.TYPING, data: { id: id1, userId: userId2, now: now3, }, }, ); // second user typing in channel expect(state).toEqual({ [id1]: { [userId1]: now1, [userId2]: now3, }, [id2]: { [userId1]: now2, }, }); const now4 = 1238; state = typingReducer( state, { type: WebsocketEvents.TYPING, data: { id: id2, userId: userId2, now: now4, }, }, ); // second user typing in second channel expect(state).toEqual({ [id1]: { [userId1]: now1, [userId2]: now3, }, [id2]: { [userId1]: now2, [userId2]: now4, }, }); }); it('WebsocketEvents.STOP_TYPING', async () => { const id1 = TestHelper.generateId(); const id2 = TestHelper.generateId(); const userId1 = TestHelper.generateId(); const userId2 = TestHelper.generateId(); const now1 = 1234; const now2 = 1235; const now3 = 1236; const now4 = 1237; let state = { [id1]: { [userId1]: now1, [userId2]: now3, }, [id2]: { [userId1]: now2, [userId2]: now4, }, }; state = typingReducer( state, { type: WebsocketEvents.STOP_TYPING, data: { id: id1, userId: userId1, now: now1, }, }, ); // deleting first user from first channel expect(state).toEqual({ [id1]: { [userId2]: now3, }, [id2]: { [userId1]: now2, [userId2]: now4, }, }); state = typingReducer( state, { type: WebsocketEvents.STOP_TYPING, data: { id: id2, userId: userId1, now: now2, }, }, ); // deleting first user from second channel expect(state).toEqual({ [id1]: { [userId2]: now3, }, [id2]: { [userId2]: now4, }, }); state = typingReducer( state, { type: WebsocketEvents.STOP_TYPING, data: { id: id1, userId: userId2, now: now3, }, }, ); // deleting second user from first channel expect(state).toEqual({ [id2]: { [userId2]: now4, }, }, ); state = typingReducer( state, { type: WebsocketEvents.STOP_TYPING, data: { id: id2, userId: userId2, now: now4, }, }, ); // deleting second user from second channel expect(state).toEqual({}); state = { [id1]: { [userId1]: now2, }, }; state = typingReducer( state, { type: WebsocketEvents.STOP_TYPING, data: { id: id1, userId: userId1, now: now1, }, }, ); // shouldn't delete when the timestamp is older expect(state).toEqual({ [id1]: { [userId1]: now2, }, }); state = typingReducer( state, { type: WebsocketEvents.STOP_TYPING, data: { id: id1, userId: userId1, now: now3, }, }, ); // should delete when the timestamp is newer expect(state).toEqual({}); }); });
4,038
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/users.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {UserProfile} from '@mattermost/types/users'; import type {IDMappedObjects} from '@mattermost/types/utilities'; import {UserTypes, ChannelTypes} from 'mattermost-redux/action_types'; import reducer from 'mattermost-redux/reducers/entities/users'; import type {GenericAction} from 'mattermost-redux/types/actions'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import {TestHelper} from 'utils/test_helper'; type ReducerState = ReturnType<typeof reducer>; describe('Reducers.users', () => { describe('profilesInChannel', () => { it('initial state', () => { const state = undefined; const action = {}; const expectedState = { profilesInChannel: {}, }; const newState = reducer(state, action as GenericAction); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILE_IN_CHANNEL, no existing profiles', () => { const state = { profilesInChannel: {}, }; const action = { type: UserTypes.RECEIVED_PROFILE_IN_CHANNEL, data: { id: 'id', user_id: 'user_id', }, }; const expectedState = { profilesInChannel: { id: new Set().add('user_id'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILE_IN_CHANNEL, existing profiles', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILE_IN_CHANNEL, data: { id: 'id', user_id: 'user_id', }, }; const expectedState = { profilesInChannel: { id: new Set().add('old_user_id').add('user_id'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILES_LIST_IN_CHANNEL, no existing profiles', () => { const state = { profilesInChannel: {}, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST_IN_CHANNEL, id: 'id', data: [ { id: 'user_id', }, { id: 'user_id_2', }, ], }; const expectedState = { profilesInChannel: { id: new Set().add('user_id').add('user_id_2'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILES_LIST_IN_CHANNEL, existing profiles', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST_IN_CHANNEL, id: 'id', data: [ { id: 'user_id', }, { id: 'user_id_2', }, ], }; const expectedState = { profilesInChannel: { id: new Set().add('old_user_id').add('user_id').add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILES_IN_CHANNEL, no existing profiles', () => { const state = { profilesInChannel: {}, }; const action = { type: UserTypes.RECEIVED_PROFILES_IN_CHANNEL, id: 'id', data: { user_id: { id: 'user_id', }, user_id_2: { id: 'user_id_2', }, }, }; const expectedState = { profilesInChannel: { id: new Set().add('user_id').add('user_id_2'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILES_IN_CHANNEL, existing profiles', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILES_IN_CHANNEL, id: 'id', data: { user_id: { id: 'user_id', }, user_id_2: { id: 'user_id_2', }, }, }; const expectedState = { profilesInChannel: { id: new Set().add('old_user_id').add('user_id').add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, unknown user id', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, data: { id: 'id', user_id: 'unknkown_user_id', }, }; const expectedState = state; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, known user id', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, data: { id: 'id', user_id: 'old_user_id', }, }; const expectedState = { profilesInChannel: { id: new Set(), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('ChannelTypes.CHANNEL_MEMBER_REMOVED, unknown user id', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: ChannelTypes.CHANNEL_MEMBER_REMOVED, data: { channel_id: 'id', user_id: 'unknkown_user_id', }, }; const expectedState = state; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('ChannelTypes.CHANNEL_MEMBER_REMOVED, known user id', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: ChannelTypes.CHANNEL_MEMBER_REMOVED, data: { channel_id: 'id', user_id: 'old_user_id', }, }; const expectedState = { profilesInChannel: { id: new Set(), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); it('UserTypes.LOGOUT_SUCCESS, existing profiles', () => { const state = { profilesInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.LOGOUT_SUCCESS, }; const expectedState = { profilesInChannel: {}, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesInChannel).toEqual(expectedState.profilesInChannel); }); }); describe('profilesNotInChannel', () => { it('initial state', () => { const state = undefined; const action = {}; const expectedState = { profilesNotInChannel: {}, }; const newState = reducer(state, action as GenericAction); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, no existing profiles', () => { const state = { profilesNotInChannel: {}, }; const action = { type: UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, data: { id: 'id', user_id: 'user_id', }, }; const expectedState = { profilesNotInChannel: { id: new Set().add('user_id'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, existing profiles', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILE_NOT_IN_CHANNEL, data: { id: 'id', user_id: 'user_id', }, }; const expectedState = { profilesNotInChannel: { id: new Set().add('old_user_id').add('user_id'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_CHANNEL, no existing profiles', () => { const state = { profilesNotInChannel: {}, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_CHANNEL, id: 'id', data: [ { id: 'user_id', }, { id: 'user_id_2', }, ], }; const expectedState = { profilesNotInChannel: { id: new Set().add('user_id').add('user_id_2'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_CHANNEL, existing profiles', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_CHANNEL, id: 'id', data: [ { id: 'user_id', }, { id: 'user_id_2', }, ], }; const expectedState = { profilesNotInChannel: { id: new Set().add('old_user_id').add('user_id').add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILES_NOT_IN_CHANNEL, no existing profiles', () => { const state = { profilesNotInChannel: {}, }; const action = { type: UserTypes.RECEIVED_PROFILES_NOT_IN_CHANNEL, id: 'id', data: { user_id: { id: 'user_id', }, user_id_2: { id: 'user_id_2', }, }, }; const expectedState = { profilesNotInChannel: { id: new Set().add('user_id').add('user_id_2'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILES_NOT_IN_CHANNEL, existing profiles', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILES_NOT_IN_CHANNEL, id: 'id', data: { user_id: { id: 'user_id', }, user_id_2: { id: 'user_id_2', }, }, }; const expectedState = { profilesNotInChannel: { id: new Set().add('old_user_id').add('user_id').add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILE_IN_CHANNEL, unknown user id', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILE_IN_CHANNEL, data: { id: 'id', user_id: 'unknkown_user_id', }, }; const expectedState = state; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_PROFILE_IN_CHANNEL, known user id', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILE_IN_CHANNEL, data: { id: 'id', user_id: 'old_user_id', }, }; const expectedState = { profilesNotInChannel: { id: new Set(), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('ChannelTypes.CHANNEL_MEMBER_ADDED, unknown user id', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: ChannelTypes.CHANNEL_MEMBER_ADDED, data: { channel_id: 'id', user_id: 'unknkown_user_id', }, }; const expectedState = state; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('ChannelTypes.CHANNEL_MEMBER_ADDED, known user id', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: ChannelTypes.CHANNEL_MEMBER_ADDED, data: { channel_id: 'id', user_id: 'old_user_id', }, }; const expectedState = { profilesNotInChannel: { id: new Set(), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.LOGOUT_SUCCESS, existing profiles', () => { const state = { profilesNotInChannel: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.LOGOUT_SUCCESS, }; const expectedState = { profilesNotInChannel: {}, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInChannel).toEqual(expectedState.profilesNotInChannel); }); it('UserTypes.RECEIVED_FILTERED_USER_STATS', () => { const state = {}; const action = { type: UserTypes.RECEIVED_FILTERED_USER_STATS, data: {total_users_count: 1}, }; const expectedState = { filteredStats: {total_users_count: 1}, }; const newState = reducer(state as ReducerState, action); expect(newState.filteredStats).toEqual(expectedState.filteredStats); }); }); describe('profilesNotInGroup', () => { it('initial state', () => { const state = undefined; const action = {}; const expectedState = { profilesNotInGroup: {}, }; const newState = reducer(state, action as GenericAction); expect(newState.profilesNotInGroup).toEqual(expectedState.profilesNotInGroup); }); it('UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_GROUP, no existing profiles', () => { const state = { profilesNotInGroup: {}, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_GROUP, id: 'id', data: [ { id: 'user_id', }, { id: 'user_id_2', }, ], }; const expectedState = { profilesNotInGroup: { id: new Set().add('user_id').add('user_id_2'), }, }; const newState = reducer(state as ReducerState, action); expect(newState.profilesNotInGroup).toEqual(expectedState.profilesNotInGroup); }); it('UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_GROUP, existing profiles', () => { const state = { profilesNotInGroup: { id: new Set().add('old_user_id'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_GROUP, id: 'id', data: [ { id: 'user_id', }, { id: 'user_id_2', }, ], }; const expectedState = { profilesNotInGroup: { id: new Set().add('old_user_id').add('user_id').add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInGroup).toEqual(expectedState.profilesNotInGroup); }); it('UserTypes.RECEIVED_PROFILES_FOR_GROUP, existing profiles', () => { const state = { profilesNotInGroup: { id: new Set().add('user_id').add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const action = { type: UserTypes.RECEIVED_PROFILES_FOR_GROUP, id: 'id', data: [ { user_id: 'user_id', }, ], }; const expectedState = { profilesNotInGroup: { id: new Set().add('user_id_2'), other_id: new Set().add('other_user_id'), }, }; const newState = reducer(state as unknown as ReducerState, action); expect(newState.profilesNotInGroup).toEqual(expectedState.profilesNotInGroup); }); }); describe('profiles', () => { function sanitizeUser(user: UserProfile) { const sanitized = { ...user, email: '', first_name: '', last_name: '', auth_service: '', }; Reflect.deleteProperty(sanitized, 'email_verify'); Reflect.deleteProperty(sanitized, 'last_password_update'); Reflect.deleteProperty(sanitized, 'notify_props'); Reflect.deleteProperty(sanitized, 'terms_of_service_id'); Reflect.deleteProperty(sanitized, 'terms_of_service_create_at'); return sanitized; } for (const actionType of [UserTypes.RECEIVED_ME, UserTypes.RECEIVED_PROFILE]) { test(`should store a new user (${actionType})`, () => { const user1 = TestHelper.getUserMock({id: 'user_id1'}); const user2 = TestHelper.getUserMock({id: 'user_id2'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const nextState = reducer(state, { type: actionType, data: user2, }); expect(nextState.profiles).toEqual({ [user1.id]: user1, [user2.id]: user2, }); }); test(`should update an existing user (${actionType})`, () => { const user1 = TestHelper.getUserMock({id: 'user_id1'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const nextState = reducer(state, { type: actionType, data: { ...user1, username: 'a different username', }, }); expect(nextState.profiles).toEqual({ [user1.id]: { ...user1, username: 'a different username', }, }); }); test(`should not overwrite unsanitized data with sanitized data (${actionType})`, () => { const user1 = TestHelper.getUserMock({ id: 'user_id1', email: '[email protected]', first_name: 'User', last_name: 'One', auth_service: 'saml', }); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const nextState = reducer(state, { type: actionType, data: { ...sanitizeUser(user1), username: 'a different username', }, }); expect(nextState.profiles).toEqual({ [user1.id]: { ...user1, username: 'a different username', }, }); expect(nextState.profiles[user1.id].email).toBe(user1.email); expect(nextState.profiles[user1.id].auth_service).toBe(user1.auth_service); }); test(`should return the same state when given an identical user object (${actionType})`, () => { const user1 = TestHelper.getUserMock({id: 'user_id1'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const nextState = reducer(state, { type: actionType, data: user1, }); expect(nextState.profiles).toBe(state.profiles); }); test(`should return the same state when given an sanitized but otherwise identical user object (${actionType})`, () => { const user1 = TestHelper.getUserMock({ id: 'user_id1', email: '[email protected]', first_name: 'User', last_name: 'One', auth_service: 'saml', }); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const nextState = reducer(state, { type: actionType, data: sanitizeUser(user1), }); expect(nextState.profiles).toBe(state.profiles); }); } for (const actionType of [UserTypes.RECEIVED_PROFILES, UserTypes.RECEIVED_PROFILES_LIST]) { function usersToData(users: UserProfile[]) { if (actionType === UserTypes.RECEIVED_PROFILES) { const userMap: IDMappedObjects<UserProfile> = {}; for (const user of users) { userMap[user.id] = user; } return userMap; } return users; } test(`should store new users (${actionType})`, () => { const user1 = TestHelper.getUserMock({id: 'user_id1'}); const user2 = TestHelper.getUserMock({id: 'user_id2'}); const user3 = TestHelper.getUserMock({id: 'user_id3'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const nextState = reducer(state, { type: actionType, data: usersToData([user2, user3]), }); expect(nextState.profiles).toEqual({ [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }); }); test(`should update existing users (${actionType})`, () => { const user1 = TestHelper.getUserMock({id: 'user_id1'}); const user2 = TestHelper.getUserMock({id: 'user_id2'}); const user3 = TestHelper.getUserMock({id: 'user_id3'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }, }); const newUser1 = { ...user1, username: 'a different username', }; const newUser2 = { ...user2, nickname: 'a different nickname', }; const nextState = reducer(state, { type: actionType, data: usersToData([newUser1, newUser2]), }); expect(nextState.profiles).toEqual({ [user1.id]: newUser1, [user2.id]: newUser2, [user3.id]: user3, }); }); test(`should not overwrite unsanitized data with sanitized data (${actionType})`, () => { const user1 = TestHelper.getUserMock({ id: 'user_id1', email: '[email protected]', first_name: 'User', last_name: 'One', auth_service: 'saml', }); const user2 = TestHelper.getUserMock({id: 'user_id2'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, }, }); const newUser1 = { ...sanitizeUser(user1), username: 'a different username', }; const newUser2 = { ...sanitizeUser(user2), nickname: 'a different nickname', }; const nextState = reducer(state, { type: actionType, data: usersToData([newUser1, newUser2]), }); expect(nextState.profiles).toEqual({ [user1.id]: { ...user1, username: 'a different username', }, [user2.id]: newUser2, }); expect(nextState.profiles[user1.id].email).toBe(user1.email); expect(nextState.profiles[user1.id].auth_service).toBe(user1.auth_service); }); test(`should return the same state when given identical user objects (${actionType})`, () => { const user1 = TestHelper.getUserMock({id: 'user_id1'}); const user2 = TestHelper.getUserMock({id: 'user_id2'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, [user2.id]: user2, }, }); const nextState = reducer(state, { type: actionType, data: usersToData([user1, user2]), }); expect(nextState.profiles).toBe(state.profiles); }); test(`should return the same state when given an sanitized but otherwise identical user object (${actionType})`, () => { const user1 = TestHelper.getUserMock({ id: 'user_id1', email: '[email protected]', first_name: 'User', last_name: 'One', auth_service: 'saml', }); const user2 = TestHelper.getUserMock({id: 'user_id2'}); const state = deepFreezeAndThrowOnMutation({ profiles: { [user1.id]: user1, [user2.id]: user2, }, }); const nextState = reducer(state, { type: actionType, data: usersToData([sanitizeUser(user1), sanitizeUser(user2)]), }); expect(nextState.profiles).toBe(state.profiles); }); } test('UserTypes.RECEIVED_PROFILES_LIST, should merge existing users with new ones', () => { const firstUser = TestHelper.getUserMock({id: 'first_user_id'}); const secondUser = TestHelper.getUserMock({id: 'seocnd_user_id'}); const thirdUser = TestHelper.getUserMock({id: 'third_user_id'}); const partialUpdatedFirstUser = { ...firstUser, update_at: 123456789, }; Reflect.deleteProperty(partialUpdatedFirstUser, 'email'); Reflect.deleteProperty(partialUpdatedFirstUser, 'notify_props'); const state = { profiles: { first_user_id: firstUser, second_user_id: secondUser, }, }; const action = { type: UserTypes.RECEIVED_PROFILES_LIST, data: [ partialUpdatedFirstUser, thirdUser, ], }; const {profiles: newProfiles} = reducer(state as unknown as ReducerState, action); expect(newProfiles.first_user_id).toEqual({...firstUser, ...partialUpdatedFirstUser}); expect(newProfiles.second_user_id).toEqual(secondUser); expect(newProfiles.third_user_id).toEqual(thirdUser); }); }); });
4,040
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/__snapshots__/apps.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`bindings Invalid channel header get filtered 1`] = ` Array [ Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locA", }, ], "location": "/post_menu", }, Object { "app_id": "2", "bindings": Array [ Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locA", }, ], "location": "/post_menu", }, Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "icon": "icon", "label": "b", "location": "/channel_header/locB", }, ], "location": "/channel_header", }, Object { "app_id": "2", "bindings": Array [ Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "icon": "icon", "label": "c", "location": "/channel_header/locC", }, ], "location": "/channel_header", }, Object { "app_id": "3", "bindings": Array [ Object { "app_id": "3", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "c", "location": "/command/locC", }, ], "location": "/command", }, ] `; exports[`bindings Invalid commands get filtered 1`] = ` Array [ Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locA", }, Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locB", }, ], "location": "/post_menu", }, Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "icon": "icon", "label": "b", "location": "/channel_header/locB", }, ], "location": "/channel_header", }, Object { "app_id": "3", "bindings": Array [ Object { "app_id": "3", "bindings": Array [ Object { "app_id": "3", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "c2", "location": "/command/locC/subC2", }, ], "label": "c", "location": "/command/locC", }, ], "location": "/command", }, Object { "app_id": "2", "bindings": Array [ Object { "app_id": "2", "bindings": Array [ Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "c1", "location": "/command/locC/subC1", }, Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "c2", "location": "/command/locC/subC2", }, ], "label": "c", "location": "/command/locC", }, ], "location": "/command", }, ] `; exports[`bindings Invalid post menu get filtered 1`] = ` Array [ Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locB", }, ], "location": "/post_menu", }, Object { "app_id": "2", "bindings": Array [ Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locA", }, Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "b", "location": "/post_menu/locB", }, ], "location": "/post_menu", }, Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "icon": "icon", "label": "b", "location": "/channel_header/locB", }, ], "location": "/channel_header", }, Object { "app_id": "3", "bindings": Array [ Object { "app_id": "3", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "c", "location": "/command/locC", }, ], "location": "/command", }, ] `; exports[`bindings No element get filtered 1`] = ` Array [ Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locA", }, ], "location": "/post_menu", }, Object { "app_id": "2", "bindings": Array [ Object { "app_id": "2", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "a", "location": "/post_menu/locA", }, ], "location": "/post_menu", }, Object { "app_id": "1", "bindings": Array [ Object { "app_id": "1", "form": Object { "submit": Object { "path": "/submit_url", }, }, "icon": "icon", "label": "b", "location": "/channel_header/locB", }, ], "location": "/channel_header", }, Object { "app_id": "3", "bindings": Array [ Object { "app_id": "3", "form": Object { "submit": Object { "path": "/submit_url", }, }, "label": "c", "location": "/command/locC", }, ], "location": "/command", }, ] `;
4,041
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/channels/message_counts.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ServerChannel} from '@mattermost/types/channels'; import {updateMessageCount} from './message_counts'; describe('reducers.entities.channels', () => { describe('updateMessageCounts', () => { it('root and total should be different if there are threads', () => { const state = { myid: { total: 0, root: 0, }, }; const channel = { id: 'myid', total_msg_count_root: 1, total_msg_count: 5, }; const results = updateMessageCount(state, channel as ServerChannel); expect(results.myid.root).toBe(1); expect(results.myid.total).toBe(5); }); }); });
4,046
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/reducers/entities/threads/threadsInTeam.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {ThreadTypes} from 'mattermost-redux/action_types'; import deepFreeze from 'mattermost-redux/utils/deep_freeze'; import {handleFollowChanged} from './threadsInTeam'; import type {ExtraData} from './types'; describe('handleFollowChanged', () => { const state = deepFreeze({ team_id1: ['id1_1', 'id1_2'], team_id2: ['id2_1', 'id2_2'], }); const makeAction = (id: string, following: boolean) => ({ type: ThreadTypes.FOLLOW_CHANGED_THREAD, data: { team_id: 'team_id1', id, following, }, }); const extra = { threads: { id1_0: { id: 'id1_0', last_reply_at: 0, }, id1_1: { id: 'id1_1', last_reply_at: 10, }, id1_2: { id: 'id1_1', last_reply_at: 20, }, id1_3: { id: 'id1_3', last_reply_at: 30, }, id2_1: { id: 'id2_1', last_reply_at: 100, }, id2_2: { id: 'id2_2', last_reply_at: 200, }, }, } as unknown as ExtraData; test('follow existing thread', () => { const action = makeAction('id1_1', true); expect(handleFollowChanged(state, action, extra)).toEqual({ team_id1: ['id1_1', 'id1_2'], team_id2: ['id2_1', 'id2_2'], }); }); test.each([ ['id1_1', false, ['id1_2']], ['id1_3', false, ['id1_1', 'id1_2']], ['id1_1', true, ['id1_1', 'id1_2']], ['id1_3', true, ['id1_1', 'id1_2', 'id1_3']], ['id1_0', true, ['id1_1', 'id1_2']], ])('should return correct state for thread id %s and following state of %s', (id, following, expected) => { const action = makeAction(id, following); expect(handleFollowChanged(state, action, extra)).toEqual({ team_id1: expected, team_id2: ['id2_1', 'id2_2'], }); }); });
4,065
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/apps.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {AppBinding} from '@mattermost/types/apps'; import type {GlobalState} from '@mattermost/types/store'; import {AppBindingLocations} from 'mattermost-redux/constants/apps'; import * as Selectors from 'mattermost-redux/selectors/entities/apps'; const makeNewState = (pluginEnabled: boolean, flag?: string, bindings?: AppBinding[]) => ({ entities: { general: { config: { FeatureFlagAppsEnabled: flag, }, }, apps: { main: { bindings, forms: {}, }, pluginEnabled, }, }, }) as unknown as GlobalState; describe('Selectors.Apps', () => { describe('appsEnabled', () => { it('should return true when feature flag is enabled', () => { const state: GlobalState = makeNewState(true, 'true'); const result = Selectors.appsEnabled(state); expect(result).toEqual(true); }); it('should return false when feature flag is disabled', () => { let state: GlobalState = makeNewState(true, 'false'); let result = Selectors.appsEnabled(state); expect(result).toEqual(false); state = makeNewState(false, 'false'); result = Selectors.appsEnabled(state); expect(result).toEqual(false); state = makeNewState(true, ''); result = Selectors.appsEnabled(state); expect(result).toEqual(false); state = makeNewState(true); result = Selectors.appsEnabled(state); expect(result).toEqual(false); }); }); describe('makeAppBindingsSelector', () => { const allBindings = [ { location: '/post_menu', bindings: [ { app_id: 'app1', location: 'post-menu-1', label: 'App 1 Post Menu', }, { app_id: 'app2', location: 'post-menu-2', label: 'App 2 Post Menu', }, ], }, { location: '/channel_header', bindings: [ { app_id: 'app1', location: 'channel-header-1', label: 'App 1 Channel Header', }, { app_id: 'app2', location: 'channel-header-2', label: 'App 2 Channel Header', }, ], }, { location: '/command', bindings: [ { app_id: 'app1', location: 'command-1', label: 'App 1 Command', }, { app_id: 'app2', location: 'command-2', label: 'App 2 Command', }, ], }, ] as AppBinding[]; it('should return an empty array when plugin is disabled', () => { const state = makeNewState(false, 'true', allBindings); const selector = Selectors.makeAppBindingsSelector(AppBindingLocations.POST_MENU_ITEM); const result = selector(state); expect(result).toEqual([]); }); it('should return an empty array when feature flag is false', () => { const state = makeNewState(true, 'false', allBindings); const selector = Selectors.makeAppBindingsSelector(AppBindingLocations.POST_MENU_ITEM); const result = selector(state); expect(result).toEqual([]); }); it('should return post menu bindings', () => { const state = makeNewState(true, 'true', allBindings); const selector = Selectors.makeAppBindingsSelector(AppBindingLocations.POST_MENU_ITEM); const result = selector(state); expect(result).toEqual([ { app_id: 'app1', location: 'post-menu-1', label: 'App 1 Post Menu', }, { app_id: 'app2', location: 'post-menu-2', label: 'App 2 Post Menu', }, ]); }); it('should return channel header bindings', () => { const state = makeNewState(true, 'true', allBindings); const selector = Selectors.makeAppBindingsSelector(AppBindingLocations.CHANNEL_HEADER_ICON); const result = selector(state); expect(result).toEqual([ { app_id: 'app1', location: 'channel-header-1', label: 'App 1 Channel Header', }, { app_id: 'app2', location: 'channel-header-2', label: 'App 2 Channel Header', }, ]); }); it('should return command bindings', () => { const state = makeNewState(true, 'true', allBindings); const selector = Selectors.makeAppBindingsSelector(AppBindingLocations.COMMAND); const result = selector(state); expect(result).toEqual([ { app_id: 'app1', location: 'command-1', label: 'App 1 Command', }, { app_id: 'app2', location: 'command-2', label: 'App 2 Command', }, ]); }); }); });
4,067
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/bots.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Selectors from 'mattermost-redux/selectors/entities/bots'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; describe('Selectors.Bots', () => { const userID1 = 'currentUser'; const userID2 = 'otherUser1'; const userID3 = 'otherUser2'; const currentUser = {id: userID1, username: 'currentUser', first_name: 'Current', last_name: 'User', locale: 'en'}; const otherUser1 = {id: userID2, username: 'otherUser1', first_name: 'Other', last_name: 'User', locale: 'en'}; const otherUser2 = {id: userID3, username: 'mattermost-advisor', first_name: 'Another', last_name: 'User', locale: 'en'}; const bot1 = { user_id: userID1, username: 'currentUser', display_name: 'abc', description: '', owner_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, }; const bot2 = { user_id: userID3, username: 'mattermost-advisor', display_name: 'xyz', description: '', owner_id: 'xyz', create_at: 1553808972099, update_at: 1553808972099, delete_at: 0, }; const testState = deepFreezeAndThrowOnMutation({ entities: { bots: { syncables: {}, members: {}, accounts: { [userID1]: bot1, [userID3]: bot2, }, }, users: { profiles: { currentUser, otherUser1, otherUser2, }, }, }, }); it('getBotAccounts', () => { const botsById = Selectors.getBotAccounts(testState); expect(botsById[bot1.user_id]).toEqual(bot1); expect(botsById[bot2.user_id]).toEqual(bot2); expect(Object.keys(botsById).length).toEqual(2); }); it('getExternalBotAccounts', () => { const expected = { currentUser: bot1, }; expect(Selectors.getExternalBotAccounts(testState)).toEqual(expected); }); });
4,069
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/channel_categories.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {CategorySorting} from '@mattermost/types/channel_categories'; import type {GlobalState} from '@mattermost/types/store'; import {General, Preferences} from 'mattermost-redux/constants'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import {MarkUnread} from 'mattermost-redux/constants/channels'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import * as Selectors from './channel_categories'; import mergeObjects from '../../../test/merge_objects'; import TestHelper from '../../../test/test_helper'; const ch = TestHelper.getChannelMock; describe('getCategoryInTeamByType', () => { const favoritesCategory1 = {id: 'favoritesCategory1', team_id: 'team1', type: CategoryTypes.FAVORITES}; const channelsCategory1 = {id: 'channelsCategory1', team_id: 'team1', type: CategoryTypes.CHANNELS}; const directMessagesCategory1 = {id: 'directMessagesCategory1', team_id: 'team1', type: CategoryTypes.DIRECT_MESSAGES}; const channelsCategory2 = {id: 'channelsCategory2', team_id: 'team2', type: CategoryTypes.CHANNELS}; const state = { entities: { channelCategories: { byId: { channelsCategory1, channelsCategory2, directMessagesCategory1, favoritesCategory1, }, }, }, } as unknown as GlobalState; test('should return categories from each team', () => { expect(Selectors.getCategoryInTeamByType(state, 'team1', CategoryTypes.FAVORITES)).toBe(favoritesCategory1); expect(Selectors.getCategoryInTeamByType(state, 'team1', CategoryTypes.CHANNELS)).toBe(channelsCategory1); expect(Selectors.getCategoryInTeamByType(state, 'team1', CategoryTypes.DIRECT_MESSAGES)).toBe(directMessagesCategory1); expect(Selectors.getCategoryInTeamByType(state, 'team2', CategoryTypes.CHANNELS)).toBe(channelsCategory2); }); test('should return null for a team that does not exist', () => { expect(Selectors.getCategoryInTeamByType(state, 'team3', CategoryTypes.CHANNELS)).toBeUndefined(); }); test('should return null for a category that does not exist', () => { expect(Selectors.getCategoryInTeamByType(state, 'team2', CategoryTypes.FAVORITES)).toBeUndefined(); }); }); describe('getCategoryInTeamWithChannel', () => { const category1 = {id: 'category1', team_id: 'team1', channel_ids: ['channel1', 'channel2']}; const category2 = {id: 'category2', team_id: 'team1', channel_ids: ['dmChannel1']}; const category3 = {id: 'category3', team_id: 'team2', channel_ids: ['dmChannel1']}; const state = { entities: { channelCategories: { byId: { category1, category2, category3, }, }, }, } as unknown as GlobalState; test('should return the category containing a given channel', () => { expect(Selectors.getCategoryInTeamWithChannel(state, 'team1', 'channel1')).toBe(category1); expect(Selectors.getCategoryInTeamWithChannel(state, 'team1', 'channel2')).toBe(category1); }); test('should return the category on the correct team for a cross-team channel', () => { expect(Selectors.getCategoryInTeamWithChannel(state, 'team1', 'dmChannel1')).toBe(category2); expect(Selectors.getCategoryInTeamWithChannel(state, 'team2', 'dmChannel1')).toBe(category3); }); }); describe('makeGetCategoriesForTeam', () => { const category1 = {id: 'category1', display_name: 'Category One', type: CategoryTypes.CUSTOM}; const category2 = {id: 'category2', display_name: 'Category Two', type: CategoryTypes.CUSTOM}; const state = { entities: { channelCategories: { byId: { category1, category2, }, orderByTeam: { team1: [category2.id, category1.id], }, }, }, } as unknown as GlobalState; test('should return categories for team in order', () => { const getCategoriesForTeam = Selectors.makeGetCategoriesForTeam(); expect(getCategoriesForTeam(state, 'team1')).toEqual([ state.entities.channelCategories.byId.category2, state.entities.channelCategories.byId.category1, ]); }); test('should memoize properly', () => { const getCategoriesForTeam = Selectors.makeGetCategoriesForTeam(); const result = getCategoriesForTeam(state, 'team1'); // Repeat calls should return the same array expect(getCategoriesForTeam(state, 'team1')).toBe(result); // Calls to a difference instance of the selector won't return the same array expect(result).not.toBe(Selectors.makeGetCategoriesForTeam()(state, 'team1')); // Calls with different arguments won't return the same array expect(getCategoriesForTeam(state, 'team2')).not.toBe(result); // Calls after different argumetns won't return the same array expect(getCategoriesForTeam(state, 'team1')).not.toBe(result); }); }); describe('makeFilterAutoclosedDMs', () => { const currentUser = {id: 'currentUser'}; const tigerKing = {id: 'tigerKing'}; const bojackHorseman = {id: 'bojackHorseman'}; const jeffWinger = {id: 'jeffWinger'}; const baseState = { entities: { channels: { currentChannelId: 'channel1', messageCounts: {}, myMembers: { channel2: { channel_id: 'channel2', last_viewed_at: 0, }, channel1: {}, channel3: {}, }, }, general: { config: {}, }, posts: { posts: {}, postsInChannel: { channel1: [], }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '0'}, }, }, users: { currentUserId: currentUser.id, profiles: { currentUser, tigerKing, bojackHorseman, jeffWinger, }, }, }, }; test('Should always show an unread channel', () => { const filterAutoclosedDMs = Selectors.makeFilterAutoclosedDMs(); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL}); const gmChannel2 = ch({id: 'gmChannel2', type: General.GM_CHANNEL}); const state = mergeObjects(baseState, { entities: { channels: { messageCounts: { gmChannel1: {total: 5}, gmChannel2: {total: 0}, }, myMembers: { gmChannel1: {msg_count: 1, notify_props: {mark_unread: MarkUnread.ALL}}, gmChannel2: {msg_count: 0, notify_props: {mark_unread: MarkUnread.ALL}}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '1'}, }, }, }, }); expect(filterAutoclosedDMs(state, [gmChannel1, gmChannel2], CategoryTypes.DIRECT_MESSAGES)).toEqual([gmChannel1]); }); test('Should always show the current channel', () => { const filterAutoclosedDMs = Selectors.makeFilterAutoclosedDMs(); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, name: `${currentUser.id}__${jeffWinger.id}`}); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL}); let state = mergeObjects(baseState, { entities: { channels: { currentChannelId: dmChannel1.id, myMembers: { [gmChannel1.id]: {last_viewed_at: 1000}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '1'}, }, }, }, }); expect(filterAutoclosedDMs(state, [dmChannel1, gmChannel1], CategoryTypes.DIRECT_MESSAGES)).toEqual([dmChannel1]); state = mergeObjects(baseState, { entities: { channels: { currentChannelId: gmChannel1.id, myMembers: { [dmChannel1.id]: {last_viewed_at: 1000}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '1'}, }, }, }, }); expect(filterAutoclosedDMs(state, [gmChannel1, dmChannel1], CategoryTypes.DIRECT_MESSAGES)).toEqual([gmChannel1]); }); describe('Should always show the exact number of channels specified by the user', () => { const filterAutoclosedDMs = Selectors.makeFilterAutoclosedDMs(); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, name: `${currentUser.id}__${tigerKing.id}`}); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL, name: 'WhatsApp'}); const gmChannel2 = ch({id: 'gmChannel2', type: General.GM_CHANNEL, name: 'Telegram'}); const dmChannel2 = ch({id: 'dmChannel2', type: General.DM_CHANNEL, name: `${currentUser.id}__${bojackHorseman.id}`}); const dmChannel3 = ch({id: 'dmChannel3', type: General.DM_CHANNEL, name: `${currentUser.id}__${jeffWinger.id}`}); test('User specified 5 DMs to be shown', () => { const state = mergeObjects(baseState, { entities: { channels: { currentChannelId: dmChannel1.id, myMembers: { [dmChannel1.id]: {last_viewed_at: 1000}, [dmChannel2.id]: {last_viewed_at: 500}, [dmChannel3.id]: {last_viewed_at: 0}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '5'}, }, }, }, }); expect(filterAutoclosedDMs(state, [dmChannel1, gmChannel1, gmChannel2, dmChannel2, dmChannel3], CategoryTypes.DIRECT_MESSAGES)).toEqual([dmChannel1, gmChannel1, gmChannel2, dmChannel2, dmChannel3]); }); test('User specified 2 DMs to be shown', () => { const state = mergeObjects(baseState, { entities: { channels: { currentChannelId: dmChannel1.id, myMembers: { [dmChannel1.id]: {last_viewed_at: 1000}, [dmChannel2.id]: {last_viewed_at: 500}, [dmChannel3.id]: {last_viewed_at: 0}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '2'}, }, }, }, }); expect(filterAutoclosedDMs(state, [dmChannel1, gmChannel1, gmChannel2, dmChannel2, dmChannel3], CategoryTypes.DIRECT_MESSAGES)).toEqual([dmChannel1, dmChannel2]); }); }); test('should consider approximate view time and open time preferences for most recently viewed channel', () => { const filterAutoclosedDMs = Selectors.makeFilterAutoclosedDMs(); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, name: `${currentUser.id}__${tigerKing.id}`}); const dmChannel2 = ch({id: 'dmChannel2', type: General.DM_CHANNEL, name: `${currentUser.id}__${bojackHorseman.id}`}); const dmChannel3 = ch({id: 'dmChannel3', type: General.DM_CHANNEL, name: `${currentUser.id}__${jeffWinger.id}`}); let state = mergeObjects(baseState, { entities: { channels: { channels: { dmChannel1, dmChannel2, dmChannel3, }, myMembers: { [dmChannel1.id]: {last_viewed_at: 1000}, [dmChannel2.id]: {last_viewed_at: 500}, [dmChannel3.id]: {last_viewed_at: 0}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '2'}, }, }, }, }); expect(filterAutoclosedDMs(state, [dmChannel1, dmChannel2, dmChannel3], CategoryTypes.DIRECT_MESSAGES)).toEqual([dmChannel1, dmChannel2]); state = mergeObjects(state, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_CHANNEL_OPEN_TIME, dmChannel3.id)]: {value: '3000'}, }, }, }, }); expect(filterAutoclosedDMs(state, [dmChannel1, dmChannel2, dmChannel3], CategoryTypes.DIRECT_MESSAGES)).toEqual([dmChannel1, dmChannel3]); state = mergeObjects(state, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_CHANNEL_APPROXIMATE_VIEW_TIME, dmChannel2.id)]: {value: '2000'}, }, }, }, }); expect(filterAutoclosedDMs(state, [dmChannel1, dmChannel2, dmChannel3], CategoryTypes.DIRECT_MESSAGES)).toEqual([dmChannel2, dmChannel3]); }); }); describe('makeFilterManuallyClosedDMs', () => { const currentUser = {id: 'currentUser'}; const otherUser1 = {id: 'otherUser1'}; const otherUser2 = {id: 'otherUser2'}; const baseState = { entities: { general: { config: {}, }, channels: { messageCounts: {}, myMembers: {}, }, preferences: { myPreferences: {}, }, users: { currentUserId: currentUser.id, }, }, } as unknown as GlobalState; test('should filter DMs based on preferences', () => { const filterManuallyClosedDMs = Selectors.makeFilterManuallyClosedDMs(); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, name: `${currentUser.id}__${otherUser1.id}`}); const dmChannel2 = ch({id: 'dmChannel2', type: General.DM_CHANNEL, name: `${currentUser.id}__${otherUser2.id}`}); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser1.id)]: {value: 'false'}, [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser2.id)]: {value: 'true'}, }, }, }, }); expect(filterManuallyClosedDMs(state, [dmChannel1, dmChannel2])).toMatchObject([dmChannel2]); }); test('should filter GMs based on preferences', () => { const filterManuallyClosedDMs = Selectors.makeFilterManuallyClosedDMs(); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL}); const gmChannel2 = ch({id: 'gmChannel2', type: General.GM_CHANNEL}); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel2.id)]: {value: 'false'}, }, }, }, }); expect(filterManuallyClosedDMs(state, [gmChannel1, gmChannel2])).toMatchObject([gmChannel1]); }); test('should show unread DMs and GMs, regardless of preferences', () => { const filterManuallyClosedDMs = Selectors.makeFilterManuallyClosedDMs(); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, name: `${currentUser.id}__${otherUser1.id}`}); const dmChannel2 = ch({id: 'dmChannel2', type: General.DM_CHANNEL, name: `${currentUser.id}__${otherUser2.id}`}); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL}); const gmChannel2 = ch({id: 'gmChannel2', type: General.GM_CHANNEL}); const state = mergeObjects(baseState, { entities: { channels: { messageCounts: { dmChannel1: {total: 1}, dmChannel2: {total: 0}, gmChannel1: {total: 1}, gmChannel2: {total: 0}, }, myMembers: { dmChannel1: {msg_count: 0}, dmChannel2: {msg_count: 0}, gmChannel1: {msg_count: 0}, gmChannel2: {msg_count: 0}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser1.id)]: {value: 'false'}, [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser2.id)]: {value: 'false'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'false'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel2.id)]: {value: 'false'}, }, }, }, }); expect(filterManuallyClosedDMs(state, [dmChannel1, dmChannel2, gmChannel1, gmChannel2])).toEqual([dmChannel1, gmChannel1]); }); test('should show the current channel, regardless of preferences', () => { const filterManuallyClosedDMs = Selectors.makeFilterManuallyClosedDMs(); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, name: `${currentUser.id}__${otherUser1.id}`}); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL}); let state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser1.id)]: {value: 'false'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'false'}, }, }, }, }); expect(filterManuallyClosedDMs(state, [dmChannel1, gmChannel1])).toEqual([]); state = mergeObjects(baseState, { entities: { channels: { currentChannelId: dmChannel1.id, }, }, }); expect(filterManuallyClosedDMs(state, [dmChannel1, gmChannel1])).toEqual([dmChannel1]); state = mergeObjects(baseState, { entities: { channels: { currentChannelId: gmChannel1.id, }, }, }); expect(filterManuallyClosedDMs(state, [dmChannel1, gmChannel1])).toEqual([gmChannel1]); }); test('should not filter other channels', () => { const filterManuallyClosedDMs = Selectors.makeFilterManuallyClosedDMs(); const channel1 = ch({id: 'channel1', type: General.OPEN_CHANNEL}); const channel2 = ch({id: 'channel2', type: General.PRIVATE_CHANNEL}); const state = baseState; const channels = [channel1, channel2]; expect(filterManuallyClosedDMs(state, channels)).toBe(channels); }); }); describe('makeSortChannelsByName', () => { const currentUser = {id: 'currentUser', locale: 'en'}; const baseState = { entities: { channels: { myMembers: {}, }, users: { currentUserId: currentUser.id, profiles: { currentUser, }, }, general: { config: {}, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; test('should sort channels by display name', () => { const sortChannelsByName = Selectors.makeSortChannelsByName(); const channel1 = ch({id: 'channel1', display_name: 'Carrot'}); const channel2 = ch({id: 'channel2', display_name: 'Apple'}); const channel3 = ch({id: 'channel3', display_name: 'Banana'}); const channels = [channel1, channel2, channel3]; expect(sortChannelsByName(baseState, channels)).toEqual([channel2, channel3, channel1]); }); test('should sort channels by display name with numbers', () => { const sortChannelsByName = Selectors.makeSortChannelsByName(); const channel1 = ch({id: 'channel1', display_name: 'Channel 10'}); const channel2 = ch({id: 'channel2', display_name: 'Channel 1'}); const channel3 = ch({id: 'channel3', display_name: 'Channel 11'}); const channel4 = ch({id: 'channel4', display_name: 'Channel 1a'}); const channels = [channel1, channel2, channel3, channel4]; expect(sortChannelsByName(baseState, channels)).toEqual([channel2, channel4, channel1, channel3]); }); test('should sort muted channels last', () => { const sortChannelsByName = Selectors.makeSortChannelsByName(); const state = mergeObjects(baseState, { entities: { channels: { myMembers: { channel1: {notify_props: {mark_unread: MarkUnread.MENTION}}, channel3: {notify_props: {mark_unread: MarkUnread.MENTION}}, channel4: {notify_props: {mark_unread: MarkUnread.ALL}}, }, }, }, }); const channel1 = ch({id: 'channel1', display_name: 'Carrot'}); const channel2 = ch({id: 'channel2', display_name: 'Apple'}); const channel3 = ch({id: 'channel3', display_name: 'Banana'}); const channel4 = ch({id: 'channel4', display_name: 'Dragonfruit'}); const channels = [channel1, channel2, channel3, channel4]; expect(sortChannelsByName(state, channels)).toEqual([channel2, channel4, channel3, channel1]); }); }); describe('makeSortChannelsByNameWithDMs', () => { const currentUser = {id: 'currentUser', username: 'currentUser', first_name: 'Current', last_name: 'User', locale: 'en'}; const otherUser1 = {id: 'otherUser1', username: 'otherUser1', first_name: 'Other', last_name: 'User', locale: 'en'}; const otherUser2 = {id: 'otherUser2', username: 'otherUser2', first_name: 'Another', last_name: 'User', locale: 'en'}; const channel1 = ch({id: 'channel1', type: General.OPEN_CHANNEL, display_name: 'Zebra'}); const channel2 = ch({id: 'channel2', type: General.PRIVATE_CHANNEL, display_name: 'Aardvark'}); const channel3 = ch({id: 'channel3', type: General.OPEN_CHANNEL, display_name: 'Bear'}); const dmChannel1 = ch({id: 'dmChannel1', type: General.DM_CHANNEL, display_name: '', name: `${currentUser.id}__${otherUser1.id}`}); const dmChannel2 = ch({id: 'dmChannel2', type: General.DM_CHANNEL, display_name: '', name: `${otherUser2.id}__${currentUser.id}`}); const gmChannel1 = ch({id: 'gmChannel1', type: General.GM_CHANNEL, display_name: `${currentUser.username}, ${otherUser1.username}, ${otherUser2.username}`, name: 'gmChannel1'}); const baseState = { entities: { channels: { myMembers: {}, }, general: { config: {}, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.NAME_NAME_FORMAT)]: {value: Preferences.DISPLAY_PREFER_FULL_NAME}, }, }, users: { currentUserId: currentUser.id, profiles: { currentUser, otherUser1, otherUser2, }, }, }, } as unknown as GlobalState; test('should sort regular channels by display name', () => { const sortChannelsByNameWithDMs = Selectors.makeSortChannelsByNameWithDMs(); expect(sortChannelsByNameWithDMs(baseState, [ channel1, channel2, channel3, ])).toMatchObject([ channel2, // Aardvark channel3, // Bear channel1, // Zebra ]); }); test('should sort DM channels by the display name of the other user', () => { const sortChannelsByNameWithDMs = Selectors.makeSortChannelsByNameWithDMs(); expect(sortChannelsByNameWithDMs(baseState, [ channel1, channel2, channel3, dmChannel1, dmChannel2, ])).toMatchObject([ channel2, // Aardvark dmChannel2, // Another User channel3, // Bear dmChannel1, // Other User channel1, // Zebra ]); }); test('should sort GM channels by the display name of the other users', () => { const sortChannelsByNameWithDMs = Selectors.makeSortChannelsByNameWithDMs(); let state = baseState; expect(sortChannelsByNameWithDMs(state, [ channel1, channel2, channel3, gmChannel1, ])).toMatchObject([ channel2, // Aardvark gmChannel1, // Another User, Other User channel3, // Bear channel1, // Zebra ]); state = mergeObjects(state, { entities: { users: { currentUserId: otherUser2.id, }, }, }); expect(sortChannelsByNameWithDMs(state, [ channel1, channel2, channel3, gmChannel1, ])).toMatchObject([ channel2, // Aardvark channel3, // Bear gmChannel1, // Current User, Other User channel1, // Zebra ]); }); test('should sort muted channels last', () => { const sortChannelsByNameWithDMs = Selectors.makeSortChannelsByNameWithDMs(); const state = mergeObjects(baseState, { entities: { channels: { myMembers: { channel3: {notify_props: {mark_unread: MarkUnread.MENTION}}, dmChannel1: {notify_props: {mark_unread: MarkUnread.MENTION}}, dmChannel2: {notify_props: {mark_unread: MarkUnread.ALL}}, gmChannel1: {notify_props: {mark_unread: MarkUnread.MENTION}}, }, }, }, }); expect(sortChannelsByNameWithDMs(state, [ channel1, channel2, channel3, dmChannel1, dmChannel2, gmChannel1, ])).toMatchObject([ channel2, // Aardvark dmChannel2, // Another User channel1, // Zebra gmChannel1, // Another User, Other User (Muted) channel3, // Bear (Muted) dmChannel1, // Other User (Muted) ]); }); }); describe('makeSortChannelsByRecency', () => { const channel1 = ch({id: 'channel1', display_name: 'Apple', last_post_at: 1000, last_root_post_at: 3000, create_at: 0}); const channel2 = ch({id: 'channel2', display_name: 'Banana', last_post_at: 2000, last_root_post_at: 1000, create_at: 0}); const channel3 = ch({id: 'channel3', display_name: 'Zucchini', last_post_at: 3000, last_root_post_at: 2000, create_at: 0}); const baseState = { entities: { posts: { posts: {}, postsInChannel: {}, }, general: { config: { CollapsedThreads: 'default_off', }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; test('should sort channels by their last_post_at when no posts are loaded', () => { const sortChannelsByRecency = Selectors.makeSortChannelsByRecency(); const state = baseState; expect(sortChannelsByRecency(state, [channel1, channel2, channel3])).toMatchObject([channel3, channel2, channel1]); expect(sortChannelsByRecency(state, [channel3, channel2, channel1])).toMatchObject([channel3, channel2, channel1]); }); test('should sort channels by their last_post_at when no posts are loaded and CRT in enabled', () => { const sortChannelsByRecency = Selectors.makeSortChannelsByRecency(); const state = { ...baseState, entities: { ...baseState.entities, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.COLLAPSED_REPLY_THREADS}`]: { value: 'on', }, }, }, }, } as unknown as GlobalState; expect(sortChannelsByRecency(state, [channel3, channel2, channel1])).toMatchObject([channel1, channel3, channel2]); expect(sortChannelsByRecency(state, [channel1, channel3, channel2])).toMatchObject([channel1, channel3, channel2]); }); }); describe('makeGetChannelIdsForCategory', () => { const currentUser = {id: 'currentUser', username: 'currentUser', first_name: 'Current', last_name: 'User', locale: 'en'}; const otherUser1 = {id: 'otherUser1', username: 'otherUser1', first_name: 'Other', last_name: 'User', locale: 'en'}; const otherUser2 = {id: 'otherUser2', username: 'otherUser2', first_name: 'Another', last_name: 'User', locale: 'en'}; const channel1 = {id: 'channel1', type: General.OPEN_CHANNEL, team_id: 'team1', display_name: 'Zebra', delete_at: 0, create_at: 0}; const channel2 = {id: 'channel2', type: General.PRIVATE_CHANNEL, team_id: 'team1', display_name: 'Aardvark', delete_at: 0, create_at: 0}; const channel3 = {id: 'channel3', type: General.OPEN_CHANNEL, team_id: 'team1', display_name: 'Bear', delete_at: 0, create_at: 0}; const dmChannel1 = {id: 'dmChannel1', type: General.DM_CHANNEL, team_id: '', display_name: '', name: `${currentUser.id}__${otherUser1.id}`, delete_at: 0, last_post_at: 2000, create_at: 0}; const dmChannel2 = {id: 'dmChannel2', type: General.DM_CHANNEL, team_id: '', display_name: '', name: `${otherUser2.id}__${currentUser.id}`, delete_at: 0, create_at: 0}; const gmChannel1 = {id: 'gmChannel1', type: General.GM_CHANNEL, team_id: '', display_name: `${currentUser.username}, ${otherUser1.username}, ${otherUser2.username}`, name: 'gmChannel1', delete_at: 0, create_at: 0}; const baseState = { entities: { channels: { channels: { channel1, channel2, channel3, dmChannel1, dmChannel2, gmChannel1, }, messageCounts: {}, myMembers: { [channel1.id]: {}, [channel2.id]: {}, [channel3.id]: {}, [dmChannel1.id]: {}, [dmChannel2.id]: {}, [gmChannel1.id]: {}, }, }, general: { config: {}, }, posts: { posts: {}, postsInChannel: {}, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.NAME_NAME_FORMAT)]: {value: Preferences.DISPLAY_PREFER_FULL_NAME}, [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser1.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser2.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'true'}, }, }, users: { currentUserId: currentUser.id, profiles: { currentUser, otherUser1, otherUser2, }, }, }, } as unknown as GlobalState; test('should return sorted and filtered channels for favorites category', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const favoritesCategory = { id: 'favoritesCategory', team_id: 'team1', display_name: CategoryTypes.FAVORITES, type: CategoryTypes.FAVORITES, sorting: CategorySorting.Default, channel_ids: [dmChannel2.id, channel1.id], user_id: '', muted: false, collapsed: false, }; expect(getChannelIdsForCategory(baseState, favoritesCategory)).toMatchObject([dmChannel2.id, channel1.id]); }); test('should return sorted and filtered channels for channels category with manual sorting', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const publicCategory = { id: 'publicCategory', team_id: 'team1', display_name: 'Public Channels', type: CategoryTypes.PUBLIC, sorting: CategorySorting.Manual, channel_ids: [channel3.id, channel2.id], user_id: '', muted: false, collapsed: false, }; expect(getChannelIdsForCategory(baseState, publicCategory)).toMatchObject([channel3.id, channel2.id]); }); test('should return sorted and filtered channels for channels category with alphabetical sorting', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const publicCategory = { id: 'publicCategory', team_id: 'team1', display_name: 'Public Channels', type: CategoryTypes.PUBLIC, sorting: CategorySorting.Alphabetical, channel_ids: [channel3.id, channel2.id], user_id: '', muted: false, collapsed: false, }; expect(getChannelIdsForCategory(baseState, publicCategory)).toMatchObject([channel2.id, channel3.id]); }); test('should return sorted and filtered channels for channels category with alphabetical sorting and a muted channel', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const state = mergeObjects(baseState, { entities: { channels: { myMembers: { [channel2.id]: {notify_props: {mark_unread: MarkUnread.MENTION}}, }, }, }, }); const publicCategory = { id: 'publicCategory', team_id: 'team1', display_name: 'Public Channels', type: CategoryTypes.PUBLIC, sorting: CategorySorting.Alphabetical, channel_ids: [channel2.id, channel3.id], user_id: '', muted: false, collapsed: false, }; expect(getChannelIdsForCategory(state, publicCategory)).toMatchObject([channel3.id, channel2.id]); }); test('should return sorted and filtered channels for direct messages category with alphabetical sorting', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '2'}, }, }, }, }); const directMessagesCategory = { id: 'directMessagesCategory', team_id: 'team1', display_name: 'Direct Messages', type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Alphabetical, channel_ids: [gmChannel1.id, dmChannel1.id], user_id: '', muted: false, collapsed: false, }; expect(getChannelIdsForCategory(state, directMessagesCategory)).toMatchObject([gmChannel1.id, dmChannel1.id]); }); test('should return sorted and filtered channels for direct messages category with recency sorting', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const otherUser3 = {id: 'otherUser3', username: 'otherUser3', first_name: 'Third', last_name: 'User', locale: 'en'}; const gmChannel2 = {id: 'gmChannel2', type: General.GM_CHANNEL, team_id: '', display_name: `${currentUser.username}, ${otherUser1.username}, ${otherUser3.username}`, name: 'gmChannel2', delete_at: 0, last_post_at: 2000, create_at: 0}; const directMessagesCategory = { id: 'directMessagesCategory', team_id: 'team1', display_name: 'Direct Messages', type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Recency, channel_ids: [gmChannel1.id, dmChannel1.id, gmChannel2.id], user_id: '', muted: false, collapsed: false, }; const state = mergeObjects(baseState, { entities: { channels: { channels: { dmChannel1: {last_post_at: 3000}, gmChannel1: {last_post_at: 1000}, gmChannel2, }, myMembers: { [gmChannel2.id]: {}, }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '3'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel2.id)]: {value: 'true'}, }, }, users: { profiles: { otherUser3, }, }, }, }); expect(getChannelIdsForCategory(state, directMessagesCategory)).toMatchObject(['dmChannel1', 'gmChannel2', 'gmChannel1']); }); describe('memoization', () => { test('should return the same result when called twice with the same category', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const favoritesCategory = { id: 'favoritesCategory', team_id: 'team1', display_name: CategoryTypes.FAVORITES, type: CategoryTypes.FAVORITES, sorting: CategorySorting.Default, channel_ids: [dmChannel1.id, channel1.id], user_id: '', muted: false, collapsed: false, }; const originalResult = getChannelIdsForCategory(baseState, favoritesCategory); expect(getChannelIdsForCategory(baseState, favoritesCategory)).toBe(originalResult); }); test('should return a different result when called twice with a different category', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const favoritesCategory = { id: 'favoritesCategory', team_id: 'team1', display_name: CategoryTypes.FAVORITES, type: CategoryTypes.FAVORITES, sorting: CategorySorting.Default, channel_ids: [dmChannel1.id, channel1.id], user_id: '', muted: false, collapsed: false, }; const publicCategory = { id: 'publicCategory', team_id: 'team1', display_name: 'Public Channels', type: CategoryTypes.PUBLIC, sorting: CategorySorting.Manual, channel_ids: [channel3.id, channel2.id], user_id: '', muted: false, collapsed: false, }; const originalResult = getChannelIdsForCategory(baseState, favoritesCategory); expect(getChannelIdsForCategory(baseState, publicCategory)).not.toBe(originalResult); }); test('should return a different result when called with a different sorting method', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const favoritesCategory = { id: 'favoritesCategory', team_id: 'team1', display_name: CategoryTypes.FAVORITES, type: CategoryTypes.FAVORITES, sorting: CategorySorting.Default, channel_ids: [dmChannel1.id, dmChannel2.id], user_id: '', muted: false, collapsed: false, }; const originalResult = getChannelIdsForCategory(baseState, favoritesCategory); expect(getChannelIdsForCategory(baseState, { ...favoritesCategory, sorting: CategorySorting.Recency, })).not.toBe(originalResult); }); test('should return the same result when called with a different sorting method but only a single channel', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const favoritesCategory = { id: 'favoritesCategory', team_id: 'team1', display_name: CategoryTypes.FAVORITES, type: CategoryTypes.FAVORITES, sorting: CategorySorting.Default, channel_ids: [dmChannel2.id], user_id: '', muted: false, collapsed: false, }; const originalResult = getChannelIdsForCategory(baseState, favoritesCategory); expect(getChannelIdsForCategory(baseState, { ...favoritesCategory, sorting: CategorySorting.Alphabetical, })).toBe(originalResult); expect(getChannelIdsForCategory(baseState, { ...favoritesCategory, sorting: CategorySorting.Recency, })).toBe(originalResult); }); test('should return a new result when DM category limit changes', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); let state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '2'}, }, }, }, }); const directMessagesCategory = { id: 'directMessagesCategory', team_id: 'team1', display_name: 'Direct Messages', type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Alphabetical, channel_ids: [gmChannel1.id, dmChannel1.id], user_id: '', muted: false, collapsed: false, }; const originalResult = getChannelIdsForCategory(state, directMessagesCategory); state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '1'}, }, }, }, }); expect(getChannelIdsForCategory(state, directMessagesCategory)).not.toBe(originalResult); }); test('should return a different result for DMs only when a name change causes an order change', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const directMessagesCategory = { id: 'directMessagesCategory', team_id: 'team1', display_name: 'Direct Messages', type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Alphabetical, channel_ids: [dmChannel1.id, dmChannel2.id], user_id: '', muted: false, collapsed: false, }; // otherUser2 (Another User), otherUser1 (Other User) let result = getChannelIdsForCategory(baseState, directMessagesCategory); expect(result).toEqual([dmChannel2.id, dmChannel1.id]); let previousResult = result; let state = mergeObjects(baseState, { entities: { users: { profiles: { otherUser2: {...otherUser2, first_name: 'User', last_name: 'User'}, }, }, }, }); // otherUser1 (Other User), otherUser2 (User User) result = getChannelIdsForCategory(state, directMessagesCategory); expect(result).toEqual([dmChannel1.id, dmChannel2.id]); expect(result).not.toBe(previousResult); previousResult = result; state = mergeObjects(state, { entities: { users: { profiles: { otherUser1: {...otherUser1, first_name: 'Zoo', last_name: 'User'}, }, }, }, }); // otherUser2 (User User), otherUser1 (Zoo User) result = getChannelIdsForCategory(state, directMessagesCategory); expect(result).toEqual([dmChannel2.id, dmChannel1.id]); expect(result).not.toBe(previousResult); previousResult = result; state = mergeObjects(state, { entities: { users: { profiles: { otherUser2: {...otherUser2, first_name: 'Some', last_name: 'User'}, }, }, }, }); // otherUser2 (Some User), otherUser1 (Zoo User) result = getChannelIdsForCategory(state, directMessagesCategory); expect(result).toEqual([dmChannel2.id, dmChannel1.id]); expect(result).toBe(previousResult); }); test('should return a different result for alphabetically sorted DMs when the display name setting causes an order change', () => { const getChannelIdsForCategory = Selectors.makeGetChannelIdsForCategory(); const directMessagesCategory = { id: 'directMessagesCategory', team_id: 'team1', display_name: 'Direct Messages', type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Alphabetical, channel_ids: [dmChannel1.id, dmChannel2.id], user_id: '', muted: false, collapsed: false, }; // otherUser2 (Another User), otherUser1 (Other User) const originalResult = getChannelIdsForCategory(baseState, directMessagesCategory); expect(originalResult).toEqual([dmChannel2.id, dmChannel1.id]); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.NAME_NAME_FORMAT)]: {value: Preferences.DISPLAY_PREFER_USERNAME}, }, }, }, }); // otherUser1, otherUser2 const result = getChannelIdsForCategory(state, directMessagesCategory); expect(result).toEqual([dmChannel1.id, dmChannel2.id]); expect(result).not.toBe(originalResult); }); }); }); describe('makeGetChannelsByCategory', () => { const currentUser = {id: 'currentUser', username: 'currentUser', first_name: 'Current', last_name: 'User', locale: 'en'}; const otherUser1 = {id: 'otherUser1', username: 'otherUser1', first_name: 'Other', last_name: 'User', locale: 'en'}; const otherUser2 = {id: 'otherUser2', username: 'otherUser2', first_name: 'Another', last_name: 'User', locale: 'en'}; const channel1 = {id: 'channel1', type: General.OPEN_CHANNEL, team_id: 'team1', display_name: 'Zebra', delete_at: 0}; const channel2 = {id: 'channel2', type: General.PRIVATE_CHANNEL, team_id: 'team1', display_name: 'Aardvark', delete_at: 0}; const channel3 = {id: 'channel3', type: General.OPEN_CHANNEL, team_id: 'team1', display_name: 'Bear', delete_at: 0}; const dmChannel1 = {id: 'dmChannel1', type: General.DM_CHANNEL, team_id: '', display_name: '', name: `${currentUser.id}__${otherUser1.id}`, delete_at: 0, last_post_at: 2000}; const dmChannel2 = {id: 'dmChannel2', type: General.DM_CHANNEL, team_id: '', display_name: '', name: `${otherUser2.id}__${currentUser.id}`, delete_at: 0}; const gmChannel1 = {id: 'gmChannel1', type: General.GM_CHANNEL, team_id: '', display_name: `${currentUser.username}, ${otherUser1.username}, ${otherUser2.username}`, name: 'gmChannel1', delete_at: 0, last_post_at: 1000}; const favoritesCategory = { id: 'favoritesCategory', team_id: 'team1', display_name: CategoryTypes.FAVORITES, type: CategoryTypes.FAVORITES, sorting: CategorySorting.Alphabetical, channel_ids: [channel1.id, dmChannel2.id], user_id: '', muted: false, collapsed: false, }; const channelsCategory = { id: 'channelsCategory', team_id: 'team1', display_name: 'Channels', type: CategoryTypes.CHANNELS, sorting: CategorySorting.Default, channel_ids: [channel2.id, channel3.id], user_id: '', muted: false, collapsed: false, }; const directMessagesCategory = { id: 'directMessagesCategory', team_id: 'team1', display_name: 'Direct Messages', type: CategoryTypes.DIRECT_MESSAGES, sorting: CategorySorting.Recency, channel_ids: [dmChannel1.id, gmChannel1.id], user_id: '', muted: false, collapsed: false, }; const baseState = { entities: { channelCategories: { byId: { favoritesCategory, channelsCategory, directMessagesCategory, }, orderByTeam: { team1: [ favoritesCategory.id, channelsCategory.id, directMessagesCategory.id, ], }, }, channels: { channels: { channel1, channel2, channel3, dmChannel1, dmChannel2, gmChannel1, }, messageCounts: {}, myMembers: { [channel1.id]: {}, [channel2.id]: {}, [channel3.id]: {}, [dmChannel1.id]: {}, [dmChannel2.id]: {}, [gmChannel1.id]: {}, }, }, general: { config: {}, }, posts: { posts: {}, postsInChannel: {}, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.NAME_NAME_FORMAT)]: {value: Preferences.DISPLAY_PREFER_FULL_NAME}, [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser1.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser2.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '3'}, }, }, users: { currentUserId: currentUser.id, profiles: { currentUser, otherUser1, otherUser2, }, }, }, } as unknown as GlobalState; test('should return channels for all categories', () => { const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '2'}, }, }, }, }); const result = getChannelsByCategory(state, 'team1'); expect(result.favoritesCategory).toEqual([dmChannel2, channel1]); expect(result.channelsCategory).toEqual([channel2, channel3]); expect(result.directMessagesCategory).toEqual([dmChannel1, gmChannel1]); }); describe('memoization', () => { test('should return the same object when called with the same state', () => { const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); expect(getChannelsByCategory(baseState, 'team1')).toBe(getChannelsByCategory(baseState, 'team1')); }); test('should return the same object when unrelated state changes', () => { const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); const state = mergeObjects(baseState, { views: { something: 7, }, }); const previousResult = getChannelsByCategory(baseState, 'team1'); const result = getChannelsByCategory(state, 'team1'); expect(result).toBe(previousResult); }); test('should return a new object when user profiles change', () => { // This behaviour isn't ideal, but it's better than the previous version which returns a new object // whenever anything user-related changes const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); const state = mergeObjects(baseState, { entities: { users: { profiles: { newUser: {id: 'newUser'}, }, }, }, }); const previousResult = getChannelsByCategory(baseState, 'team1'); const result = getChannelsByCategory(state, 'team1'); expect(result).not.toBe(previousResult); expect(result).toEqual(previousResult); // Categories not containing DMs/GMs and sorted alphabetically should still remain the same expect(result.favoritesCategory).not.toBe(previousResult.favoritesCategory); expect(result.favoritesCategory).toEqual(previousResult.favoritesCategory); expect(result.channelsCategory).toBe(previousResult.channelsCategory); expect(result.directMessagesCategory).toEqual(previousResult.directMessagesCategory); expect(result.directMessagesCategory).toEqual(previousResult.directMessagesCategory); }); test('should return the same object when other user state changes', () => { const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); const state = mergeObjects(baseState, { entities: { users: { statuses: { otherUser1: 'offline', }, }, }, }); const previousResult = getChannelsByCategory(baseState, 'team1'); const result = getChannelsByCategory(state, 'team1'); expect(result).toBe(previousResult); }); test('should not return a new object when unrelated preferences change', () => { const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey('abc', '123')]: {value: 'true'}, }, }, }, }); const previousResult = getChannelsByCategory(baseState, 'team1'); const result = getChannelsByCategory(state, 'team1'); expect(result).toBe(previousResult); }); test('should return a new object when a DM is closed', () => { const getChannelsByCategory = Selectors.makeGetChannelsByCategory(); const state = mergeObjects(baseState, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, otherUser1.id)]: {value: 'false'}, }, }, }, }); const previousResult = getChannelsByCategory(baseState, 'team1'); const result = getChannelsByCategory(state, 'team1'); expect(result).not.toBe(previousResult); expect(result.favoritesCategory).toEqual(previousResult.favoritesCategory); expect(result.channelsCategory).toEqual(previousResult.channelsCategory); expect(result.directMessagesCategory).not.toEqual(previousResult.directMessagesCategory); }); }); });
4,071
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/channels.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel} from '@mattermost/types/channels'; import type {GlobalState} from '@mattermost/types/store'; import {General, Permissions} from 'mattermost-redux/constants'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import {sortChannelsByDisplayName, getDirectChannelName} from 'mattermost-redux/utils/channel_utils'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import * as Selectors from './channels'; import TestHelper from '../../..//test/test_helper'; import mergeObjects from '../../../test/merge_objects'; const sortUsernames = (a: string, b: string) => a.localeCompare(b, General.DEFAULT_LOCALE, {numeric: true}); describe('Selectors.Channels.getChannelsInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); it('should return channels in current team', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team2.id); const channel3 = TestHelper.fakeChannelWithId(team1.id); const channel4 = TestHelper.fakeChannelWithId(''); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, }; const channelsInTeam = { [team1.id]: [channel1.id, channel3.id], [team2.id]: [channel2.id], '': [channel4.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, }, }, }); const channelsInCurrentTeam = [channel1, channel3].sort(sortChannelsByDisplayName.bind(null, 'en')); expect(Selectors.getChannelsInCurrentTeam(testState)).toEqual(channelsInCurrentTeam); }); it('should order by user locale', () => { const userDe = { ...TestHelper.fakeUserWithId(), locale: 'de', }; const userSv = { ...TestHelper.fakeUserWithId(), locale: 'sv', }; const profilesDe = { [userDe.id]: userDe, }; const profilesSv = { [userSv.id]: userSv, }; const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'z', }; const channel2 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'ä', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, }; const channelsInTeam = { [team1.id]: [channel1.id, channel2.id], }; const testStateDe = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userDe.id, profiles: profilesDe, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, }, }, }); const testStateSv = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userSv.id, profiles: profilesSv, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, }, }, }); const channelsInCurrentTeamDe = [channel1, channel2].sort(sortChannelsByDisplayName.bind(null, userDe.locale)); const channelsInCurrentTeamSv = [channel1, channel2].sort(sortChannelsByDisplayName.bind(null, userSv.locale)); expect(Selectors.getChannelsInCurrentTeam(testStateDe)).toEqual(channelsInCurrentTeamDe); expect(Selectors.getChannelsInCurrentTeam(testStateSv)).toEqual(channelsInCurrentTeamSv); }); }); describe('Selectors.Channels.getMyChannels', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const user = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, [user2.id]: user2, [user3.id]: user3, }; const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'Channel Name', }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), display_name: 'Channel Name', }; const channel3 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'Channel Name', }; const channel4 = { ...TestHelper.fakeChannelWithId(''), display_name: 'Channel Name', type: General.DM_CHANNEL as 'D', name: getDirectChannelName(user.id, user2.id), }; const channel5 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: [user.username, user2.username, user3.username].join(', '), type: General.GM_CHANNEL, name: '', } as Channel; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, [channel5.id]: channel5, }; const channelsInTeam = { [team1.id]: [channel1.id, channel3.id], [team2.id]: [channel2.id], '': [channel4.id, channel5.id], }; const myMembers = { [channel1.id]: {}, [channel3.id]: {}, [channel4.id]: {}, [channel5.id]: {}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, statuses: {}, profilesInChannel: { [channel4.id]: new Set([user.id, user2.id]), [channel5.id]: new Set([user.id, user2.id, user3.id]), }, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, myMembers, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('get my channels in current team and DMs', () => { const channelsInCurrentTeam = [channel1, channel3].sort(sortChannelsByDisplayName.bind(null, 'en')); expect(Selectors.getMyChannels(testState)).toEqual([ ...channelsInCurrentTeam, {...channel4, display_name: user2.username, status: 'offline', teammate_id: user2.id}, {...channel5, display_name: [user2.username, user3.username].sort(sortUsernames).join(', ')}, ]); }); }); describe('Selectors.Channels.getMembersInCurrentChannel', () => { const channel1 = TestHelper.fakeChannelWithId(''); const user = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const membersInChannel = { [channel1.id]: { [user.id]: {}, [user2.id]: {}, [user3.id]: {}, }, }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { currentChannelId: channel1.id, membersInChannel, }, }, }); it('should return members in current channel', () => { expect(Selectors.getMembersInCurrentChannel(testState)).toEqual(membersInChannel[channel1.id]); }); }); describe('Selectors.Channels.getOtherChannels', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'Channel Name', type: General.OPEN_CHANNEL as 'O', }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), display_name: 'Channel Name', type: General.OPEN_CHANNEL as 'O', }; const channel3 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'Channel Name', type: General.PRIVATE_CHANNEL as 'P', }; const channel4 = { ...TestHelper.fakeChannelWithId(''), display_name: 'Channel Name', type: General.DM_CHANNEL as 'D', }; const channel5 = { ...TestHelper.fakeChannelWithId(''), display_name: 'Channel Name', type: General.OPEN_CHANNEL as 'O', delete_at: 444, }; const channel6 = { ...TestHelper.fakeChannelWithId(team1.id), display_name: 'Channel Name', type: General.OPEN_CHANNEL as 'O', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, [channel5.id]: channel5, [channel6.id]: channel6, }; const channelsInTeam = { [team1.id]: [channel1.id, channel3.id, channel5.id, channel6.id], [team2.id]: [channel2.id], '': [channel4.id], }; const myMembers = { [channel4.id]: {}, [channel6.id]: {}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, myMembers, }, }, }); it('get public channels not member of', () => { expect(Selectors.getOtherChannels(testState)).toEqual([channel1, channel5].sort(sortChannelsByDisplayName.bind(null, 'en'))); }); it('get public, unarchived channels not member of', () => { expect(Selectors.getOtherChannels(testState, false)).toEqual([channel1]); }); }); describe('getChannel', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const user = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, [user2.id]: user2, [user3.id]: user3, }; const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), type: General.OPEN_CHANNEL, }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), type: General.DM_CHANNEL, name: getDirectChannelName(user.id, user2.id), }; const channel3 = { ...TestHelper.fakeChannelWithId(team2.id), type: General.GM_CHANNEL, display_name: [user.username, user2.username, user3.username].join(', '), }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, statuses: {}, profilesInChannel: { [channel2.id]: new Set([user.id, user2.id]), [channel3.id]: new Set([user.id, user2.id, user3.id]), }, }, channels: { channels, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); test('should return channels directly from the store', () => { expect(Selectors.getChannel(testState, channel1.id)).toBe(channel1); expect(Selectors.getChannel(testState, channel2.id)).toBe(channel2); expect(Selectors.getChannel(testState, channel3.id)).toBe(channel3); }); }); describe('makeGetChannel', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const user = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, [user2.id]: user2, [user3.id]: user3, }; const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), type: General.OPEN_CHANNEL, }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), type: General.DM_CHANNEL, name: getDirectChannelName(user.id, user2.id), }; const channel3 = { ...TestHelper.fakeChannelWithId(team2.id), type: General.GM_CHANNEL, display_name: [user.username, user2.username, user3.username].join(', '), }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, statuses: {}, profilesInChannel: { [channel2.id]: new Set([user.id, user2.id]), [channel3.id]: new Set([user.id, user2.id, user3.id]), }, }, channels: { channels, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); test('should return non-DM/non-GM channels directly from the store', () => { const getChannel = Selectors.makeGetChannel(); expect(getChannel(testState, {id: channel1.id})).toBe(channel1); }); test('should return DMs with computed data added', () => { const getChannel = Selectors.makeGetChannel(); expect(getChannel(testState, {id: channel2.id})).toEqual({ ...channel2, display_name: user2.username, status: 'offline', teammate_id: user2.id, }); }); test('should return GMs with computed data added', () => { const getChannel = Selectors.makeGetChannel(); expect(getChannel(testState, {id: channel3.id})).toEqual({ ...channel3, display_name: [user2.username, user3.username].sort(sortUsernames).join(', '), }); }); }); describe('Selectors.Channels.getChannelByName', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'ch1', }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), name: 'ch2', }; const channel3 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'ch3', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { channels, }, }, }); it('get first channel that matches by name', () => { expect(Selectors.getChannelByName(testState, channel3.name)).toEqual(channel3); }); it('return undefined if no channel matches by name', () => { expect(Selectors.getChannelByName(testState, 'noChannel')).toEqual(undefined); }); }); describe('Selectors.Channels.getChannelByTeamIdAndChannelName', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'ch1', }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), name: 'ch2', }; const channel3 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'ch3', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { channels, }, }, }); it('get channel1 matching team id and name', () => { expect(Selectors.getChannelByTeamIdAndChannelName(testState, team1.id, channel1.name)).toEqual(channel1); }); it('get channel2 matching team id and name', () => { expect(Selectors.getChannelByTeamIdAndChannelName(testState, team2.id, channel2.name)).toEqual(channel2); }); it('get channel3 matching team id and name', () => { expect(Selectors.getChannelByTeamIdAndChannelName(testState, team1.id, channel3.name)).toEqual(channel3); }); it('return undefined if no channel matches team id and name', () => { expect(Selectors.getChannelByTeamIdAndChannelName(testState, team1.id, channel2.name)).toEqual(undefined); }); it('return undefined on empty team id', () => { expect(Selectors.getChannelByTeamIdAndChannelName(testState, '', channel1.name)).toEqual(undefined); }); }); describe('Selectors.Channels.getChannelsNameMapInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'Ch1', }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), name: 'Ch2', }; const channel3 = { ...TestHelper.fakeChannelWithId(team2.id), name: 'Ch3', }; const channel4 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'Ch4', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, }; const channelsInTeam = { [team1.id]: [channel1.id, channel4.id], [team2.id]: [channel2.id, channel3.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, }, }, }); it('get channel map for current team', () => { const channelMap = { [channel1.name]: channel1, [channel4.name]: channel4, }; expect(Selectors.getChannelsNameMapInCurrentTeam(testState)).toEqual(channelMap); }); describe('memoization', () => { it('should return memoized result with no changes', () => { const originalResult = Selectors.getChannelsNameMapInCurrentTeam(testState); expect(Selectors.getChannelsNameMapInCurrentTeam(testState)).toBe(originalResult); }); it('should not return memoized result when channels on another team changes', () => { // This is a known issue with the current implementation of the selector. Ideally, it would return the // memoized result. const originalResult = Selectors.getChannelsNameMapInCurrentTeam(testState); const state = deepFreezeAndThrowOnMutation(mergeObjects(testState, { entities: { channels: { channels: { [channel3.id]: {...channel3, display_name: 'Some other name'}, }, }, }, })); expect(Selectors.getChannelsNameMapInCurrentTeam(state)).not.toBe(originalResult); }); it('should not return memozied result when a returned channel changes its display name', () => { const originalResult = Selectors.getChannelsNameMapInCurrentTeam(testState); const state = deepFreezeAndThrowOnMutation(mergeObjects(testState, { entities: { channels: { channels: { [channel4.id]: {...channel4, display_name: 'Some other name'}, }, }, }, })); const result = Selectors.getChannelsNameMapInCurrentTeam(state); expect(result).not.toBe(originalResult); expect(result[channel4.name].display_name).toBe('Some other name'); }); it('should not return memozied result when a returned channel changes something else', () => { const originalResult = Selectors.getChannelsNameMapInCurrentTeam(testState); const state = deepFreezeAndThrowOnMutation(mergeObjects(testState, { entities: { channels: { channels: { [channel4.id]: {...channel4, last_post_at: 10000}, }, }, }, })); const result = Selectors.getChannelsNameMapInCurrentTeam(state); expect(result).not.toBe(originalResult); expect(result[channel4.name].last_post_at).toBe(10000); }); }); }); describe('Selectors.Channels.getChannelsNameMapInTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'Ch1', }; const channel2 = { ...TestHelper.fakeChannelWithId(team2.id), name: 'Ch2', }; const channel3 = { ...TestHelper.fakeChannelWithId(team2.id), name: 'Ch3', }; const channel4 = { ...TestHelper.fakeChannelWithId(team1.id), name: 'Ch4', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, }; const channelsInTeam = { [team1.id]: [channel1.id, channel4.id], [team2.id]: [channel2.id, channel3.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { channels, channelsInTeam, }, }, }); it('get channel map for team', () => { const channelMap = { [channel1.name]: channel1, [channel4.name]: channel4, }; expect(Selectors.getChannelsNameMapInTeam(testState, team1.id)).toEqual(channelMap); }); it('get empty map for non-existing team', () => { expect(Selectors.getChannelsNameMapInTeam(testState, 'junk')).toEqual({}); }); }); describe('Selectors.Channels.getChannelNameToDisplayNameMap', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), id: 'channel1', }; const channel2 = { ...TestHelper.fakeChannelWithId(team1.id), id: 'channel2', }; const channel3 = { ...TestHelper.fakeChannelWithId(team1.id), id: 'channel3', }; const channel4 = { ...TestHelper.fakeChannelWithId(team2.id), id: 'channel4', }; const baseState = { entities: { channels: { channels: { channel1, channel2, channel3, channel4, }, channelsInTeam: { [team1.id]: [channel1.id, channel2.id, channel3.id], [team2.id]: [channel4.id], }, }, teams: { currentTeamId: team1.id, }, }, } as unknown as GlobalState; test('should return a map of channel names to display names for the current team', () => { let state = baseState; expect(Selectors.getChannelNameToDisplayNameMap(state)).toEqual({ [channel1.name]: channel1.display_name, [channel2.name]: channel2.display_name, [channel3.name]: channel3.display_name, }); state = mergeObjects(baseState, { entities: { teams: { currentTeamId: team2.id, }, }, }); expect(Selectors.getChannelNameToDisplayNameMap(state)).toEqual({ [channel4.name]: channel4.display_name, }); }); describe('memoization', () => { test('should return the same object when called twice with the same state', () => { const originalResult = Selectors.getChannelNameToDisplayNameMap(baseState); expect(Selectors.getChannelNameToDisplayNameMap(baseState)).toBe(originalResult); }); test('should return the same object when a channel on another team changes', () => { const originalResult = Selectors.getChannelNameToDisplayNameMap(baseState); const state = mergeObjects(baseState, { entities: { channels: { channels: { [channel4.id]: { ...channel4, display_name: 'something else entirely', }, }, }, }, }); expect(Selectors.getChannelNameToDisplayNameMap(state)).toBe(originalResult); }); test('should return the same object when a channel receives a new post', () => { const originalResult = Selectors.getChannelNameToDisplayNameMap(baseState); const state = mergeObjects(baseState, { entities: { channels: { channels: { [channel1.id]: { ...channel1, last_post_at: 1234, }, }, }, }, }); expect(Selectors.getChannelNameToDisplayNameMap(state)).toBe(originalResult); }); test('should return a new object when a channel is renamed', () => { const originalResult = Selectors.getChannelNameToDisplayNameMap(baseState); const state = mergeObjects(baseState, { entities: { channels: { channels: { [channel2.id]: { ...channel2, display_name: 'something else', }, }, }, }, }); const result = Selectors.getChannelNameToDisplayNameMap(state); expect(result).not.toBe(originalResult); expect(result).toEqual({ [channel1.name]: channel1.display_name, [channel2.name]: 'something else', [channel3.name]: channel3.display_name, }); }); test('should return a new object when a new team is added', () => { const originalResult = Selectors.getChannelNameToDisplayNameMap(baseState); const newChannel = { ...TestHelper.fakeChannelWithId(team1.id), id: 'newChannel', }; const state = mergeObjects(baseState, { entities: { channels: { channels: { newChannel, }, channelsInTeam: { [team1.id]: [channel1.id, channel2.id, channel3.id, newChannel.id], }, }, }, }); const result = Selectors.getChannelNameToDisplayNameMap(state); expect(result).not.toBe(originalResult); expect(result).toEqual({ ...originalResult, [newChannel.name]: newChannel.display_name, }); }); }); }); describe('Selectors.Channels.getGroupChannels', () => { const team1 = TestHelper.fakeTeamWithId(); const user = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, [user2.id]: user2, [user3.id]: user3, }; const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), type: General.OPEN_CHANNEL, display_name: 'Channel Name', }; const channel2 = { ...TestHelper.fakeChannelWithId(team1.id), type: General.PRIVATE_CHANNEL, display_name: 'Channel Name', }; const channel3 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: [user.username, user3.username].join(', '), name: '', }; const channel4 = { ...TestHelper.fakeChannelWithId(''), type: General.DM_CHANNEL, display_name: 'Channel Name', name: getDirectChannelName(user.id, user2.id), }; const channel5 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, display_name: [user.username, user2.username, user3.username].join(', '), name: '', }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, [channel5.id]: channel5, }; const channelsInTeam = { [team1.id]: [channel1.id, channel2.id], '': [channel3.id, channel4.id, channel5.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, statuses: {}, profilesInChannel: { [channel3.id]: new Set([user.id, user3.id]), [channel4.id]: new Set([user.id, user2.id]), [channel5.id]: new Set([user.id, user2.id, user3.id]), }, }, channels: { channels, channelsInTeam, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('get group channels', () => { expect(Selectors.getGroupChannels(testState)).toEqual([ {...channel3, display_name: [user3.username].sort(sortUsernames).join(', ')}, {...channel5, display_name: [user2.username, user3.username].sort(sortUsernames).join(', ')}, ]); }); }); describe('Selectors.Channels.getChannelIdsInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const channel3 = TestHelper.fakeChannelWithId(team2.id); const channel4 = TestHelper.fakeChannelWithId(team2.id); const channel5 = TestHelper.fakeChannelWithId(''); const channelsInTeam = { [team1.id]: [channel1.id, channel2.id], [team2.id]: [channel3.id, channel4.id], // eslint-disable-next-line no-useless-computed-key ['']: [channel5.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, channels: { channelsInTeam, }, }, }); it('get channel ids in current team strict equal', () => { const newChannel = TestHelper.fakeChannelWithId(team2.id); const modifiedState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channelsInTeam: { ...testState.entities.channels.channelsInTeam, [team2.id]: [ ...testState.entities.channels.channelsInTeam[team2.id], newChannel.id, ], }, }, }, }; const fromOriginalState = Selectors.getChannelIdsInCurrentTeam(testState); const fromModifiedState = Selectors.getChannelIdsInCurrentTeam(modifiedState); expect(fromOriginalState).toBe(fromModifiedState); // it should't have a direct channel expect(fromModifiedState.includes(channel5.id)).toBe(false); }); }); describe('Selectors.Channels.getChannelIdsForCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const channel3 = TestHelper.fakeChannelWithId(team2.id); const channel4 = TestHelper.fakeChannelWithId(team2.id); const channel5 = TestHelper.fakeChannelWithId(''); const channelsInTeam = { [team1.id]: [channel1.id, channel2.id], [team2.id]: [channel3.id, channel4.id], // eslint-disable-next-line no-useless-computed-key ['']: [channel5.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, channels: { channelsInTeam, }, }, }); it('get channel ids for current team strict equal', () => { const anotherChannel = TestHelper.fakeChannelWithId(team2.id); const modifiedState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channelsInTeam: { ...testState.entities.channels.channelsInTeam, [team2.id]: [ ...testState.entities.channels.channelsInTeam[team2.id], anotherChannel.id, ], }, }, }, }; const fromOriginalState = Selectors.getChannelIdsForCurrentTeam(testState); const fromModifiedState = Selectors.getChannelIdsForCurrentTeam(modifiedState); expect(fromOriginalState).toBe(fromModifiedState); // it should have a direct channel expect(fromModifiedState.includes(channel5.id)).toBe(true); }); }); describe('Selectors.Channels.isCurrentChannelMuted', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const myMembers = { [channel1.id]: {channel_id: channel1.id}, [channel2.id]: {channel_id: channel2.id, notify_props: {mark_unread: 'mention'}}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { currentChannelId: channel1.id, myMembers, }, }, }); it('isCurrentChannelMuted', () => { expect(Selectors.isCurrentChannelMuted(testState)).toBe(false); const newState = { entities: { channels: { ...testState.entities.channels, currentChannelId: channel2.id, }, }, } as unknown as GlobalState; expect(Selectors.isCurrentChannelMuted(newState)).toBe(true); }); }); describe('Selectors.Channels.isCurrentChannelArchived', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = { ...TestHelper.fakeChannelWithId(team1.id), delete_at: 1, }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { currentChannelId: channel1.id, channels, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('isCurrentChannelArchived', () => { expect(Selectors.isCurrentChannelArchived(testState)).toBe(false); const newState = { entities: { ...testState.entities, channels: { ...testState.entities.channels, currentChannelId: channel2.id, }, }, } as unknown as GlobalState; expect(Selectors.isCurrentChannelArchived(newState)).toBe(true); }); }); describe('Selectors.Channels.isCurrentChannelDefault', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = { ...TestHelper.fakeChannelWithId(team1.id), name: General.DEFAULT_CHANNEL, }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, }; const testState = deepFreezeAndThrowOnMutation({ entities: { channels: { currentChannelId: channel1.id, channels, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('isCurrentChannelDefault', () => { expect(Selectors.isCurrentChannelDefault(testState)).toBe(false); const newState = { entities: { ...testState.entities, channels: { ...testState.entities.channels, currentChannelId: channel2.id, }, }, } as unknown as GlobalState; expect(Selectors.isCurrentChannelDefault(newState)).toBe(true); }); }); describe('Selectors.Channels.getChannelsWithUserProfiles', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, }; const channelsInTeam = { [team1.id]: [channel1.id], '': [channel2.id], }; const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles = { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }; const profilesInChannel = { [channel1.id]: new Set([user1.id, user2.id]), [channel2.id]: new Set([user1.id, user2.id, user3.id]), }; const baseState = deepFreezeAndThrowOnMutation({ entities: { channels: { channels, channelsInTeam, }, users: { currentUserId: user1.id, profiles, profilesInChannel, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); test('should return the only GM channel with profiles', () => { const channelsWithUserProfiles = Selectors.getChannelsWithUserProfiles(baseState); expect(channelsWithUserProfiles.length).toBe(1); expect(channelsWithUserProfiles[0].id).toBe(channel2.id); expect(channelsWithUserProfiles[0].profiles.length).toBe(2); }); test('shouldn\'t error for channel without profiles loaded', () => { const unloadedChannel = { ...TestHelper.fakeChannelWithId(''), type: General.GM_CHANNEL, }; const state = mergeObjects(baseState, { entities: { channels: { channels: { [unloadedChannel.id]: unloadedChannel, }, channelsInTeam: { '': [channel2.id, unloadedChannel.id], }, }, }, }); const channelsWithUserProfiles = Selectors.getChannelsWithUserProfiles(state); expect(channelsWithUserProfiles.length).toBe(2); expect(channelsWithUserProfiles[0].id).toBe(channel2.id); expect(channelsWithUserProfiles[1].id).toBe(unloadedChannel.id); expect(channelsWithUserProfiles[1].profiles).toEqual([]); }); }); describe('Selectors.Channels.getRedirectChannelNameForTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const teams = { [team1.id]: team1, [team2.id]: team2, }; const myTeamMembers = { [team1.id]: {}, [team2.id]: {}, }; const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const channel3 = TestHelper.fakeChannelWithId(team1.id); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const user1 = TestHelper.fakeUserWithId(); const profiles = { [user1.id]: user1, }; const myChannelMembers = { [channel1.id]: {channel_id: channel1.id}, [channel2.id]: {channel_id: channel2.id}, [channel3.id]: {channel_id: channel3.id}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { teams, myMembers: myTeamMembers, }, channels: { channels, myMembers: myChannelMembers, }, users: { currentUserId: user1.id, profiles, }, general: {}, }, }); it('getRedirectChannelNameForTeam with advanced permissions but without JOIN_PUBLIC_CHANNELS permission', () => { const modifiedState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channels: { ...testState.entities.channels.channels, 'new-not-member-channel': { id: 'new-not-member-channel', display_name: '111111', name: 'new-not-member-channel', team_id: team1.id, }, [channel1.id]: { id: channel1.id, display_name: 'aaaaaa', name: 'test-channel', team_id: team1.id, }, }, }, roles: { roles: { system_user: {permissions: []}, }, }, general: { ...testState.entities.general, serverVersion: '5.12.0', }, }, }; expect(Selectors.getRedirectChannelNameForTeam(modifiedState, team1.id)).toEqual('test-channel'); }); it('getRedirectChannelNameForTeam with advanced permissions and with JOIN_PUBLIC_CHANNELS permission', () => { const modifiedState = { ...testState, entities: { ...testState.entities, roles: { roles: { system_user: {permissions: ['join_public_channels']}, }, }, general: { ...testState.entities.general, serverVersion: '5.12.0', }, }, }; expect(Selectors.getRedirectChannelNameForTeam(modifiedState, team1.id)).toEqual(General.DEFAULT_CHANNEL); }); it('getRedirectChannelNameForTeam with advanced permissions but without JOIN_PUBLIC_CHANNELS permission but being member of town-square', () => { const modifiedState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channels: { ...testState.entities.channels.channels, 'new-not-member-channel': { id: 'new-not-member-channel', display_name: '111111', name: 'new-not-member-channel', team_id: team1.id, }, [channel1.id]: { id: channel1.id, display_name: 'Town Square', name: 'town-square', team_id: team1.id, }, }, }, roles: { roles: { system_user: {permissions: []}, }, }, general: { ...testState.entities.general, serverVersion: '5.12.0', }, }, }; expect(Selectors.getRedirectChannelNameForTeam(modifiedState, team1.id)).toEqual(General.DEFAULT_CHANNEL); }); it('getRedirectChannelNameForTeam with advanced permissions but without JOIN_PUBLIC_CHANNELS permission in not current team', () => { const modifiedState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channels: { ...testState.entities.channels.channels, 'new-not-member-channel': { id: 'new-not-member-channel', display_name: '111111', name: 'new-not-member-channel', team_id: team2.id, }, [channel3.id]: { id: channel3.id, display_name: 'aaaaaa', name: 'test-channel', team_id: team2.id, }, }, }, roles: { roles: { system_user: {permissions: []}, }, }, general: { ...testState.entities.general, serverVersion: '5.12.0', }, }, }; expect(Selectors.getRedirectChannelNameForTeam(modifiedState, team2.id)).toEqual('test-channel'); }); it('getRedirectChannelNameForTeam with advanced permissions and with JOIN_PUBLIC_CHANNELS permission in not current team', () => { const modifiedState = { ...testState, entities: { ...testState.entities, roles: { roles: { system_user: {permissions: ['join_public_channels']}, }, }, general: { ...testState.entities.general, serverVersion: '5.12.0', }, }, }; expect(Selectors.getRedirectChannelNameForTeam(modifiedState, team2.id)).toEqual(General.DEFAULT_CHANNEL); }); it('getRedirectChannelNameForTeam with advanced permissions but without JOIN_PUBLIC_CHANNELS permission but being member of town-square in not current team', () => { const modifiedState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channels: { ...testState.entities.channels.channels, 'new-not-member-channel': { id: 'new-not-member-channel', display_name: '111111', name: 'new-not-member-channel', team_id: team2.id, }, [channel3.id]: { id: channel3.id, display_name: 'Town Square', name: 'town-square', team_id: team2.id, }, }, }, roles: { roles: { system_user: {permissions: []}, }, }, general: { ...testState.entities.general, serverVersion: '5.12.0', }, }, }; expect(Selectors.getRedirectChannelNameForTeam(modifiedState, team2.id)).toEqual(General.DEFAULT_CHANNEL); }); }); describe('Selectors.Channels.getDirectAndGroupChannels', () => { const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(''), display_name: [user1.username, user2.username, user3.username].join(', '), type: General.GM_CHANNEL, }; const channel2 = { ...TestHelper.fakeChannelWithId(''), name: getDirectChannelName(user1.id, user2.id), type: General.DM_CHANNEL, }; const channel3 = { ...TestHelper.fakeChannelWithId(''), name: getDirectChannelName(user1.id, user3.id), type: General.DM_CHANNEL, }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const profiles = { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, }; const profilesInChannel = { [channel1.id]: new Set([user1.id, user2.id, user3.id]), [channel2.id]: new Set([user1.id, user2.id]), [channel3.id]: new Set([user1.id, user3.id]), }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user1.id, profiles, profilesInChannel, }, channels: { channels, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('will return no channels if there is no active user', () => { const state = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, currentUserId: null, }, }, }; expect(Selectors.getDirectAndGroupChannels(state)).toEqual([]); }); it('will return only direct and group message channels', () => { const state = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, }, }, }; expect(Selectors.getDirectAndGroupChannels(state)).toEqual([ {...channel1, display_name: [user2.username, user3.username].sort(sortUsernames).join(', ')}, {...channel2, display_name: user2.username}, {...channel3, display_name: user3.username}, ]); }); it('will not error out on undefined channels', () => { const state = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, }, channels: { ...testState.entities.channels, channels: { ...testState.entities.channels.channels, ['undefined']: undefined, //eslint-disable-line no-useless-computed-key }, }, }, }; expect(Selectors.getDirectAndGroupChannels(state)).toEqual([ {...channel1, display_name: [user2.username, user3.username].sort(sortUsernames).join(', ')}, {...channel2, display_name: user2.username}, {...channel3, display_name: user3.username}, ]); }); }); describe('Selectors.Channels.canManageAnyChannelMembersInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = { ...TestHelper.fakeChannelWithId(team1.id), type: General.OPEN_CHANNEL, }; const channel2 = { ...TestHelper.fakeChannelWithId(team1.id), type: General.PRIVATE_CHANNEL, }; const channels = { [channel1.id]: channel1, [channel2.id]: channel2, }; const user1 = TestHelper.fakeUserWithId(); const profiles = { [user1.id]: user1, }; const myChannelMembers = { [channel1.id]: {}, [channel2.id]: {}, }; const channelRoles = { [channel1.id]: [], [channel2.id]: [], }; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, channels: { channels, myMembers: myChannelMembers, roles: channelRoles, }, users: { profiles, currentUserId: user1.id, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('will return false if channel_user does not have permissions to manage channel members', () => { const newState = { entities: { ...testState.entities, roles: { roles: { channel_user: { permissions: [], }, }, }, channels: { ...testState.entities.channels, myMembers: { ...testState.entities.channels.myMembers, [channel1.id]: { ...testState.entities.channels.myMembers[channel1.id], roles: 'channel_user', }, [channel2.id]: { ...testState.entities.channels.myMembers[channel2.id], roles: 'channel_user', }, }, roles: { [channel1.id]: [ 'channel_user', ], [channel2.id]: [ 'channel_user', ], }, }, }, } as unknown as GlobalState; expect(Selectors.canManageAnyChannelMembersInCurrentTeam(newState)).toEqual(false); }); it('will return true if channel_user has permissions to manage public channel members', () => { const newState = { entities: { ...testState.entities, roles: { roles: { channel_user: { permissions: ['manage_public_channel_members'], }, }, }, channels: { ...testState.entities.channels, myMembers: { ...testState.entities.channels.myMembers, [channel1.id]: { ...testState.entities.channels.myMembers[channel1.id], roles: 'channel_user', }, [channel2.id]: { ...testState.entities.channels.myMembers[channel2.id], roles: 'channel_user', }, }, roles: { [channel1.id]: [ 'channel_user', ], [channel2.id]: [ 'channel_user', ], }, }, }, } as unknown as GlobalState; expect(Selectors.canManageAnyChannelMembersInCurrentTeam(newState)).toEqual(true); }); it('will return true if channel_user has permissions to manage private channel members', () => { const newState = { entities: { ...testState.entities, roles: { roles: { channel_user: { permissions: ['manage_private_channel_members'], }, }, }, channels: { ...testState.entities.channels, myMembers: { ...testState.entities.channels.myMembers, [channel1.id]: { ...testState.entities.channels.myMembers[channel1.id], roles: 'channel_user', }, [channel2.id]: { ...testState.entities.channels.myMembers[channel2.id], roles: 'channel_user', }, }, roles: { [channel1.id]: [ 'channel_user', ], [channel2.id]: [ 'channel_user', ], }, }, }, } as unknown as GlobalState; expect(Selectors.canManageAnyChannelMembersInCurrentTeam(newState)).toEqual(true); }); it('will return false if channel admins have permissions, but the user is not a channel admin of any channel', () => { const newState = { entities: { ...testState.entities, roles: { roles: { channel_admin: { permissions: ['manage_public_channel_members'], }, }, }, channels: { ...testState.entities.channels, myMembers: { ...testState.entities.channels.myMembers, [channel1.id]: { ...testState.entities.channels.myMembers[channel1.id], roles: 'channel_user', }, [channel2.id]: { ...testState.entities.channels.myMembers[channel2.id], roles: 'channel_user', }, }, roles: { [channel1.id]: [ 'channel_user', ], [channel2.id]: [ 'channel_user', ], }, }, }, } as unknown as GlobalState; expect(Selectors.canManageAnyChannelMembersInCurrentTeam(newState)).toEqual(false); }); it('will return true if channel admins have permission, and the user is a channel admin of some channel', () => { const newState = { entities: { ...testState.entities, roles: { roles: { channel_admin: { permissions: ['manage_public_channel_members'], }, }, }, channels: { ...testState.entities.channels, myMembers: { ...testState.entities.channels.myMembers, [channel1.id]: { ...testState.entities.channels.myMembers[channel1.id], roles: 'channel_user channel_admin', }, [channel2.id]: { ...testState.entities.channels.myMembers[channel2.id], roles: 'channel_user', }, }, roles: { [channel1.id]: [ 'channel_user', 'channel_admin', ], [channel2.id]: [ 'channel_user', ], }, }, }, } as unknown as GlobalState; expect(Selectors.canManageAnyChannelMembersInCurrentTeam(newState)).toEqual(true); }); it('will return true if team admins have permission, and the user is a team admin', () => { const newState = { entities: { ...testState.entities, roles: { roles: { team_admin: { permissions: ['manage_public_channel_members'], }, }, }, users: { ...testState.entities.users, profiles: { ...testState.entities.users.profiles, [user1.id]: { ...testState.entities.users.profiles[user1.id], roles: 'team_admin', }, }, }, }, } as unknown as GlobalState; expect(Selectors.canManageAnyChannelMembersInCurrentTeam(newState)).toEqual(true); }); }); describe('Selectors.Channels.getUnreadStatusInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const channel3 = TestHelper.fakeChannelWithId(team1.id); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const myChannelMembers = { [channel1.id]: {notify_props: {}, mention_count: 1, msg_count: 0}, [channel2.id]: {notify_props: {}, mention_count: 4, msg_count: 0}, [channel3.id]: {notify_props: {}, mention_count: 4, msg_count: 5}, }; const channelsInTeam = { [team1.id]: [channel1.id, channel2.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, threads: { counts: {}, }, channels: { currentChannelId: channel1.id, channels, channelsInTeam, messageCounts: { [channel1.id]: {total: 2}, [channel2.id]: {total: 8}, [channel3.id]: {total: 5}, }, myMembers: myChannelMembers, }, users: { profiles: {}, }, preferences: { myPreferences: {}, }, general: { config: {}, }, }, }); it('get unreads for current team', () => { expect(Selectors.getUnreadStatusInCurrentTeam(testState)).toEqual(4); }); it('get unreads for current read channel', () => { const testState2 = {...testState, entities: {...testState.entities, channels: {...testState.entities.channels, currentChannelId: channel3.id, }, }, }; expect(Selectors.countCurrentChannelUnreadMessages(testState2)).toEqual(0); }); it('get unreads for current unread channel', () => { expect(Selectors.countCurrentChannelUnreadMessages(testState)).toEqual(2); }); it('get unreads for channel not on members', () => { const testState2 = {...testState, entities: {...testState.entities, channels: {...testState.entities.channels, currentChannelId: 'some_other_id', }, }, }; expect(Selectors.countCurrentChannelUnreadMessages(testState2)).toEqual(0); }); it('get unreads with a missing profile entity', () => { const newProfiles = { ...testState.entities.users.profiles, }; Reflect.deleteProperty(newProfiles, 'fakeUserId'); const newState = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, profiles: newProfiles, }, }, }; expect(Selectors.getUnreadStatusInCurrentTeam(newState)).toEqual(4); }); it('get unreads with a deactivated user', () => { const newProfiles = { ...testState.entities.users.profiles, fakeUserId: { ...testState.entities.users.profiles.fakeUserId, delete_at: 100, }, }; const newState = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, profiles: newProfiles, }, }, }; expect(Selectors.getUnreadStatusInCurrentTeam(newState)).toEqual(4); }); it('get unreads with a deactivated channel', () => { const newChannels = { ...testState.entities.channels.channels, [channel2.id]: { ...testState.entities.channels.channels[channel2.id], delete_at: 100, }, }; const newState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channels: newChannels, }, }, }; expect(Selectors.getUnreadStatusInCurrentTeam(newState)).toEqual(false); }); }); describe('Selectors.Channels.getUnreadStatus', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const teams = { [team1.id]: team1, [team2.id]: team2, }; const myTeamMembers = { [team1.id]: {mention_count: 16, msg_count: 32}, [team2.id]: {mention_count: 64, msg_count: 128}, }; const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, }; const myChannelMembers = { [channel1.id]: {notify_props: {}, mention_count: 1, msg_count: 0}, [channel2.id]: {notify_props: {}, mention_count: 4, msg_count: 0}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, teams: { currentTeamId: team1.id, teams, myMembers: myTeamMembers, }, channels: { channels, messageCounts: { [channel1.id]: {total: 2}, [channel2.id]: {total: 8}, }, myMembers: myChannelMembers, }, users: { profiles: {}, }, }, }); it('get unreads', () => { expect(Selectors.getUnreadStatus(testState)).toBe(69); }); it('get unreads with a missing profile entity', () => { const newProfiles = { ...testState.entities.users.profiles, }; Reflect.deleteProperty(newProfiles, 'fakeUserId'); const newState = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, profiles: newProfiles, }, }, }; expect(Selectors.getUnreadStatus(newState)).toBe(69); }); it('get unreads with a deactivated user', () => { const newProfiles = { ...testState.entities.users.profiles, fakeUserId: { ...testState.entities.users.profiles.fakeUserId, delete_at: 100, }, }; const newState = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, profiles: newProfiles, }, }, }; expect(Selectors.getUnreadStatus(newState)).toBe(69); }); it('get unreads with a deactivated channel', () => { const newChannels = { ...testState.entities.channels.channels, [channel2.id]: { ...testState.entities.channels.channels[channel2.id], delete_at: 100, }, }; const newState = { ...testState, entities: { ...testState.entities, channels: { ...testState.entities.channels, channels: newChannels, }, }, }; expect(Selectors.getUnreadStatus(newState)).toBe(65); }); }); describe('Selectors.Channels.getUnreadStatus', () => { const team1 = {id: 'team1', delete_at: 0}; const team2 = {id: 'team2', delete_at: 0}; const channelA = {id: 'channelA', name: 'channelA', team_id: 'team1', delete_at: 0}; const channelB = {id: 'channelB', name: 'channelB', team_id: 'team1', delete_at: 0}; const channelC = {id: 'channelB', name: 'channelB', team_id: 'team2', delete_at: 0}; const dmChannel = {id: 'dmChannel', name: 'user1__user2', team_id: '', delete_at: 0, type: General.DM_CHANNEL}; const gmChannel = {id: 'gmChannel', name: 'gmChannel', team_id: 'team1', delete_at: 0, type: General.GM_CHANNEL}; test('should return the correct number of messages and mentions from channels on the current team', () => { const myMemberA = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const myMemberB = {mention_count: 5, msg_count: 7, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, channels: { channels: { channelA, channelB, }, messageCounts: { channelA: {total: 11}, channelB: {total: 13}, }, myMembers: { channelA: myMemberA, channelB: myMemberB, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const unreadStatus = Selectors.getUnreadStatus(state); const unreadMeta = Selectors.basicUnreadMeta(unreadStatus); expect(unreadMeta.isUnread).toBe(true); // channelA and channelB are unread expect(unreadMeta.unreadMentionCount).toBe(myMemberA.mention_count + myMemberB.mention_count); }); test('should not count messages from channel with mark_unread set to "mention"', () => { const myMemberA = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'mention'}}; const myMemberB = {mention_count: 5, msg_count: 7, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, channels: { channels: { channelA, channelB, }, messageCounts: { channelA: {total: 11}, channelB: {total: 13}, }, myMembers: { channelA: myMemberA, channelB: myMemberB, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const unreadStatus = Selectors.getUnreadStatus(state); const unreadMeta = Selectors.basicUnreadMeta(unreadStatus); expect(unreadMeta.isUnread).toBe(true); // channelA and channelB are unread, but only channelB is counted because of its mark_unread expect(unreadStatus).toBe(myMemberB.mention_count); // channelA and channelB are unread, but only channelB is counted because of its mark_unread }); test('should count mentions from DM channels', () => { const dmMember = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, channels: { channels: { dmChannel, }, messageCounts: { dmChannel: {total: 11}, }, myMembers: { dmChannel: dmMember, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, }, }, users: { currentUserId: 'user1', profiles: { user2: {delete_at: 0}, }, }, }, } as unknown as GlobalState; const unreadStatus = Selectors.getUnreadStatus(state); const unreadMeta = Selectors.basicUnreadMeta(unreadStatus); expect(unreadMeta.isUnread).toBe(true); // dmChannel is unread expect(unreadMeta.unreadMentionCount).toBe(dmMember.mention_count); }); test('should not count mentions from DM channel with archived user', () => { const dmMember = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, channels: { channels: { dmChannel, }, messageCounts: { dmChannel: {total: 11}, }, myMembers: { dmChannel: dmMember, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, }, }, users: { currentUserId: 'user1', profiles: { user2: {delete_at: 1}, }, }, }, } as unknown as GlobalState; const unreadStatus = Selectors.getUnreadStatus(state); expect(unreadStatus).toBe(false); }); test('should count mentions from GM channels', () => { const gmMember = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, general: {config: {}}, preferences: { myPreferences: {}, }, channels: { channels: { gmChannel, }, messageCounts: { gmChannel: {total: 11}, }, myMembers: { gmChannel: gmMember, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const unreadStatus = Selectors.getUnreadStatus(state); const unreadMeta = Selectors.basicUnreadMeta(unreadStatus); expect(unreadMeta.isUnread).toBe(true); // gmChannel is unread expect(unreadMeta.unreadMentionCount).toBe(gmMember.mention_count); }); test('should count mentions and messages for other teams from team members', () => { const myMemberA = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const myMemberC = {mention_count: 5, msg_count: 7, notify_props: {mark_unread: 'all'}}; const teamMember1 = {msg_count: 1, mention_count: 2}; const teamMember2 = {msg_count: 3, mention_count: 6}; const state = { entities: { general: {config: {}}, preferences: { myPreferences: {}, }, threads: { counts: {}, }, channels: { channels: { channelA, channelC, }, messageCounts: { channelA: {total: 11}, channelC: {total: 17}, }, myMembers: { channelA: myMemberA, channelC: myMemberC, }, }, teams: { currentTeamId: 'team1', myMembers: { team1: teamMember1, team2: teamMember2, }, teams: { team1, team2, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const unreadStatus = Selectors.getUnreadStatus(state); const unreadMeta = Selectors.basicUnreadMeta(unreadStatus); expect(unreadMeta.isUnread).toBe(true); // channelA and channelC are unread expect(unreadMeta.unreadMentionCount).toBe(myMemberA.mention_count + teamMember2.mention_count); }); }); describe('Selectors.Channels.getUnreadStatus', () => { const team1 = {id: 'team1', delete_at: 0}; const team2 = {id: 'team2', delete_at: 0}; const channelA = {id: 'channelA', name: 'channelA', team_id: 'team1', delete_at: 0}; const channelB = {id: 'channelB', name: 'channelB', team_id: 'team1', delete_at: 0}; const channelC = {id: 'channelC', name: 'channelC', team_id: 'team2', delete_at: 0}; const dmChannel = {id: 'dmChannel', name: 'user1__user2', team_id: '', delete_at: 0, type: General.DM_CHANNEL}; const gmChannel = {id: 'gmChannel', name: 'gmChannel', team_id: 'team1', delete_at: 0, type: General.GM_CHANNEL}; test('should unread and mentions correctly for channels across teams', () => { const myMemberA = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const myMemberB = {mention_count: 5, msg_count: 7, notify_props: {mark_unread: 'all'}}; const dmMember = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const gmMember = {mention_count: 2, msg_count: 7, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, channels: { channels: { channelA, channelB, channelC, dmChannel, gmChannel, }, messageCounts: { channelA: {total: 11}, channelB: {total: 13}, dmChannel: {total: 11}, gmChannel: {total: 17}, }, myMembers: { channelA: myMemberA, channelB: myMemberB, dmChannel: dmMember, gmChannel: gmMember, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, team2, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const teamUnreadStatus = Selectors.getTeamsUnreadStatuses(state); expect(teamUnreadStatus[0].has('team1')).toBe(true); expect(teamUnreadStatus[0].has('team2')).toBe(false); expect(teamUnreadStatus[1].get('team1')).toBe(7); }); test('should not count team unreads for DMs and GMs', () => { const myMemberA = {mention_count: 0, msg_count: 0, notify_props: {mark_unread: 'all'}}; const myMemberB = {mention_count: 0, msg_count: 0, notify_props: {mark_unread: 'all'}}; const dmMember = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const gmMember = {mention_count: 2, msg_count: 7, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: {}, }, preferences: { myPreferences: {}, }, general: {config: {}}, channels: { channels: { channelA, channelB, channelC, dmChannel, gmChannel, }, messageCounts: { channelA: {total: 11}, channelB: {total: 13}, dmChannel: {total: 11}, gmChannel: {total: 17}, }, myMembers: { channelA: myMemberA, channelB: myMemberB, dmChannel: dmMember, gmChannel: gmMember, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, team2, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const teamUnreadStatus = Selectors.getTeamsUnreadStatuses(state); expect(teamUnreadStatus[0].has('team1')).toBe(true); expect(teamUnreadStatus[0].has('team2')).toBe(false); expect(teamUnreadStatus[1].size).toBe(0); }); test('should include threads in team count', () => { const myMemberA = {mention_count: 1, msg_count: 5, notify_props: {mark_unread: 'all'}}; const myMemberB = {mention_count: 0, msg_count: 0, notify_props: {mark_unread: 'all'}}; const dmMember = {mention_count: 2, msg_count: 3, notify_props: {mark_unread: 'all'}}; const gmMember = {mention_count: 2, msg_count: 7, notify_props: {mark_unread: 'all'}}; const state = { entities: { threads: { counts: { team2: { total: 20, total_unread_threads: 10, total_unread_mentions: 2, }, }, }, preferences: { myPreferences: {}, }, general: { config: { CollapsedThreads: 'always_on', }, }, channels: { channels: { channelA, channelB, channelC, dmChannel, gmChannel, }, messageCounts: { channelA: {total: 11}, channelB: {total: 13}, dmChannel: {total: 11}, gmChannel: {total: 17}, }, myMembers: { channelA: myMemberA, channelB: myMemberB, dmChannel: dmMember, gmChannel: gmMember, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, team2, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const teamUnreadStatus = Selectors.getTeamsUnreadStatuses(state); expect(teamUnreadStatus[0].has('team1')).toBe(false); expect(teamUnreadStatus[0].has('team2')).toBe(true); expect(teamUnreadStatus[1].get('team2')).toBe(2); }); test('should not have mention count of muted channel and have its unread status', () => { const myMemberA = {mention_count: 0, msg_count: 5, notify_props: {mark_unread: 'mention'}}; const myMemberB = {mention_count: 0, msg_count: 5, notify_props: {mark_unread: 'mention'}}; const myMemberC = {mention_count: 3, msg_count: 5, notify_props: {mark_unread: 'mention'}}; const state = { entities: { threads: { counts: { }, }, preferences: { myPreferences: {}, }, general: { config: { }, }, channels: { channels: { channelA, channelB, channelC, }, messageCounts: { channelA: {total: 50}, channelB: {total: 60}, channelC: {total: 70}, }, myMembers: { channelA: myMemberA, channelB: myMemberB, channelC: myMemberC, }, }, teams: { currentTeamId: 'team1', myMembers: {}, teams: { team1, team2, }, }, users: { currentUserId: 'user1', profiles: {}, }, }, } as unknown as GlobalState; const teamUnreadStatus = Selectors.getTeamsUnreadStatuses(state); expect(teamUnreadStatus[0].has('team1')).toBe(false); expect(teamUnreadStatus[0].has('team2')).toBe(false); expect(teamUnreadStatus[1].get('team1')).toBe(undefined); expect(teamUnreadStatus[1].get('team2')).toBe(undefined); }); }); describe('Selectors.Channels.getMyFirstChannelForTeams', () => { test('should return the first channel in each team', () => { const state = { entities: { channels: { channels: { channelA: {id: 'channelA', name: 'channelA', team_id: 'team1'}, channelB: {id: 'channelB', name: 'channelB', team_id: 'team2'}, channelC: {id: 'channelC', name: 'channelC', team_id: 'team1'}, }, myMembers: { channelA: {}, channelB: {}, channelC: {}, }, }, teams: { myMembers: { team1: {}, team2: {}, }, teams: { team1: {id: 'team1', delete_at: 0}, team2: {id: 'team2', delete_at: 0}, }, }, users: { currentUserId: 'user', profiles: { user: {}, }, }, }, } as unknown as GlobalState; expect(Selectors.getMyFirstChannelForTeams(state)).toEqual({ team1: state.entities.channels.channels.channelA, team2: state.entities.channels.channels.channelB, }); }); test('should only return channels that the current user is a member of', () => { const state = { entities: { channels: { channels: { channelA: {id: 'channelA', name: 'channelA', team_id: 'team1'}, channelB: {id: 'channelB', name: 'channelB', team_id: 'team1'}, }, myMembers: { channelB: {}, }, }, teams: { myMembers: { team1: {}, }, teams: { team1: {id: 'team1', delete_at: 0}, }, }, users: { currentUserId: 'user', profiles: { user: {}, }, }, }, } as unknown as GlobalState; expect(Selectors.getMyFirstChannelForTeams(state)).toEqual({ team1: state.entities.channels.channels.channelB, }); }); test('should only return teams that the current user is a member of', () => { const state = { entities: { channels: { channels: { channelA: {id: 'channelA', name: 'channelA', team_id: 'team1'}, channelB: {id: 'channelB', name: 'channelB', team_id: 'team2'}, }, myMembers: { channelA: {}, channelB: {}, }, }, teams: { myMembers: { team1: {}, }, teams: { team1: {id: 'team1', delete_at: 0}, team2: {id: 'team2', delete_at: 0}, }, }, users: { currentUserId: 'user', profiles: { user: {}, }, }, }, } as unknown as GlobalState; expect(Selectors.getMyFirstChannelForTeams(state)).toEqual({ team1: state.entities.channels.channels.channelA, }); }); }); test('Selectors.Channels.isManuallyUnread', () => { const state = { entities: { channels: { manuallyUnread: { channel1: true, channel2: false, }, }, }, } as unknown as GlobalState; expect(Selectors.isManuallyUnread(state, 'channel1')).toBe(true); expect(Selectors.isManuallyUnread(state, undefined)).toBe(false); expect(Selectors.isManuallyUnread(state, 'channel2')).toBe(false); expect(Selectors.isManuallyUnread(state, 'channel3')).toBe(false); }); test('Selectors.Channels.getChannelModerations', () => { const moderations = [{ name: Permissions.CHANNEL_MODERATED_PERMISSIONS.CREATE_POST, roles: { members: true, }, }]; const state = { entities: { channels: { channelModerations: { channel1: moderations, }, }, }, } as unknown as GlobalState; expect(Selectors.getChannelModerations(state, 'channel1')).toEqual(moderations); expect(Selectors.getChannelModerations(state, 'undefined')).toEqual(undefined); }); test('Selectors.Channels.getChannelMemberCountsByGroup', () => { const memberCounts = { 'group-1': { group_id: 'group-1', channel_member_count: 1, channel_member_timezones_count: 1, }, 'group-2': { group_id: 'group-2', channel_member_count: 999, channel_member_timezones_count: 131, }, }; const state = { entities: { channels: { channelMemberCountsByGroup: { channel1: memberCounts, }, }, }, } as unknown as GlobalState; expect(Selectors.getChannelMemberCountsByGroup(state, 'channel1')).toEqual(memberCounts); expect(Selectors.getChannelMemberCountsByGroup(state, 'undefined')).toEqual({}); }); describe('isFavoriteChannel', () => { test('should use channel categories to determine favorites', () => { const currentTeamId = 'currentTeamId'; const channel = {id: 'channel'}; const favoritesCategory = { id: 'favoritesCategory', team_id: currentTeamId, type: CategoryTypes.FAVORITES, channel_ids: [], }; let state = { entities: { channels: { channels: { channel, }, }, channelCategories: { byId: { favoritesCategory, }, orderByTeam: { [currentTeamId]: [favoritesCategory.id], }, }, preferences: { myPreferences: {}, }, teams: { currentTeamId, }, general: { config: {}, }, }, } as unknown as GlobalState; expect(Selectors.isFavoriteChannel(state, channel.id)).toBe(false); state = mergeObjects(state, { entities: { channelCategories: { byId: { [favoritesCategory.id]: { ...favoritesCategory, channel_ids: [channel.id], }, }, }, }, }); expect(Selectors.isFavoriteChannel(state, channel.id)).toBe(true); }); }); describe('Selectors.Channels.getUnreadChannelIds', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); it('should return unread channel ids in current team', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team2.id); const channel3 = TestHelper.fakeChannelWithId(team1.id); const channel4 = TestHelper.fakeChannelWithId(''); const channel5 = TestHelper.fakeChannelWithId(team1.id); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, [channel5.id]: channel5, }; const channelsInTeam = { [team1.id]: [channel1.id, channel3.id], [team2.id]: [channel2.id], '': [channel4.id], }; const messageCounts = { [channel1.id]: {root: 10, total: 110}, [channel2.id]: {root: 20, total: 120}, [channel3.id]: {root: 30, total: 130}, [channel4.id]: {root: 40, total: 140}, [channel5.id]: {root: 50, total: 150}, }; const myMembers = { [channel1.id]: {msg_count_root: 9, msg_count: 109, mention_count_root: 0, mention_count: 0}, [channel2.id]: {msg_count_root: 19, msg_count: 119, mention_count_root: 1, mention_count: 1}, [channel3.id]: {msg_count_root: 30, msg_count: 130, mention_count_root: 1, mention_count: 1}, [channel4.id]: {msg_count_root: 40, msg_count: 140, mention_count_root: 0, mention_count: 0}, [channel5.id]: {msg_count_root: 40, msg_count: 140, mention_count_root: 0, mention_count: 0}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { preferences: { myPreferences: {}, }, general: { config: {}, }, users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, messageCounts, myMembers, }, }, }); expect(Selectors.getUnreadChannelIds(testState, channel5)).toEqual([ channel1.id, channel3.id, channel5.id, ]); }); it('should not return the id of a channel we are no member of', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team2.id); const channel3 = TestHelper.fakeChannelWithId(team1.id); const channel4 = TestHelper.fakeChannelWithId(''); const channel5 = TestHelper.fakeChannelWithId(team1.id); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, [channel4.id]: channel4, [channel5.id]: channel5, }; const channelsInTeam = { [team1.id]: [channel1.id, channel3.id], [team2.id]: [channel2.id], '': [channel4.id], }; const messageCounts = { [channel1.id]: {root: 10, total: 110}, [channel2.id]: {root: 20, total: 120}, [channel3.id]: {root: 30, total: 130}, [channel4.id]: {root: 40, total: 140}, [channel5.id]: {root: 50, total: 150}, }; const myMembers = { [channel1.id]: {msg_count_root: 9, msg_count: 109, mention_count_root: 0, mention_count: 0}, [channel2.id]: {msg_count_root: 19, msg_count: 119, mention_count_root: 1, mention_count: 1}, [channel3.id]: {msg_count_root: 30, msg_count: 130, mention_count_root: 1, mention_count: 1}, [channel4.id]: {msg_count_root: 40, msg_count: 140, mention_count_root: 0, mention_count: 0}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { preferences: { myPreferences: {}, }, general: { config: {}, }, users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, channels: { channels, channelsInTeam, messageCounts, myMembers, }, }, }); expect(Selectors.getUnreadChannelIds(testState, channel5)).toEqual([ channel1.id, channel3.id, ]); }); }); describe('Selectors.Channels.getRecentProfilesFromDMs', () => { it('should return profiles from DMs in descending order of last viewed at time', () => { const currentUser = TestHelper.fakeUserWithId(); const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const user4 = TestHelper.fakeUserWithId(); const profiles = { [currentUser.id]: currentUser, [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, [user4.id]: user4, }; const channel1 = TestHelper.fakeDmChannel(currentUser.id, user1.id); const channel2 = TestHelper.fakeDmChannel(currentUser.id, user2.id); const channel3 = TestHelper.fakeGmChannel(currentUser.username, user3.username, user4.username); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const myMembers = { [channel1.id]: {channel_id: channel1.id, last_viewed_at: 1664984782988}, [channel3.id]: {channel_id: channel3.id, last_viewed_at: 1664984782992}, [channel2.id]: {channel_id: channel2.id, last_viewed_at: 1664984782998}, }; const testState = deepFreezeAndThrowOnMutation({ entities: { preferences: { myPreferences: {}, }, general: { config: {}, }, users: { currentUserId: currentUser.id, profiles, }, teams: {}, channels: { channels, myMembers, }, }, }); expect(Selectors.getRecentProfilesFromDMs(testState).map((user) => user.username)).toEqual([ user2.username, ...[user3.username, user4.username].sort(), user1.username, ]); }); });
4,075
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/emojis.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import * as Selectors from './emojis'; import mergeObjects from '../../../test/merge_objects'; import TestHelper from '../../../test/test_helper'; describe('getCustomEmojis', () => { const emoji1 = {id: TestHelper.generateId(), name: 'a', creator_id: TestHelper.generateId()}; const emoji2 = {id: TestHelper.generateId(), name: 'b', creator_id: TestHelper.generateId()}; const baseState = deepFreezeAndThrowOnMutation({ entities: { emojis: { customEmoji: { emoji1, emoji2, }, }, general: { config: { EnableCustomEmoji: 'true', }, }, }, }); test('should return custom emojis', () => { expect(Selectors.getCustomEmojis(baseState)).toBe(baseState.entities.emojis.customEmoji); }); test('should return an empty object when custom emojis are disabled', () => { const state = mergeObjects(baseState, { entities: { general: { config: { EnableCustomEmoji: 'false', }, }, }, }); expect(Selectors.getCustomEmojis(state)).toEqual({}); }); test('MM-27679 should memoize properly', () => { let state = baseState; expect(Selectors.getCustomEmojis(state)).toBe(Selectors.getCustomEmojis(state)); state = mergeObjects(baseState, { entities: { general: { config: { EnableCustomEmoji: 'false', }, }, }, }); expect(Selectors.getCustomEmojis(state)).toBe(Selectors.getCustomEmojis(state)); }); }); describe('getCustomEmojiIdsSortedByName', () => { const emoji1 = {id: TestHelper.generateId(), name: 'a', creator_id: TestHelper.generateId()}; const emoji2 = {id: TestHelper.generateId(), name: 'b', creator_id: TestHelper.generateId()}; const emoji3 = {id: TestHelper.generateId(), name: '0', creator_id: TestHelper.generateId()}; const testState = deepFreezeAndThrowOnMutation({ entities: { emojis: { customEmoji: { [emoji1.id]: emoji1, [emoji2.id]: emoji2, [emoji3.id]: emoji3, }, }, general: { config: { EnableCustomEmoji: 'true', }, }, }, }); test('should get sorted emoji ids', () => { expect(Selectors.getCustomEmojiIdsSortedByName(testState)).toEqual([emoji3.id, emoji1.id, emoji2.id]); }); });
4,078
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/general.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GlobalState} from '@mattermost/types/store'; import {General} from 'mattermost-redux/constants'; import * as Selectors from 'mattermost-redux/selectors/entities/general'; describe('Selectors.General', () => { it('canUploadFilesOnMobile', () => { expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'false', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'true', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableMobileFileUpload: 'false', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'false', EnableMobileFileUpload: 'false', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'true', EnableMobileFileUpload: 'false', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableMobileFileUpload: 'true', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'false', EnableMobileFileUpload: 'true', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'true', EnableMobileFileUpload: 'true', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'false', }, license: { IsLicensed: 'false', Compliance: 'false', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'true', EnableMobileFileUpload: 'false', }, license: { IsLicensed: 'false', Compliance: 'false', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canUploadFilesOnMobile({ entities: { general: { config: { EnableFileAttachments: 'true', EnableMobileFileUpload: 'false', }, license: { IsLicensed: 'true', Compliance: 'false', }, }, }, } as unknown as GlobalState)).toEqual(true); }); it('canDownloadFilesOnMobile', () => { expect(Selectors.canDownloadFilesOnMobile({ entities: { general: { config: { }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canDownloadFilesOnMobile({ entities: { general: { config: { EnableMobileFileDownload: 'false', }, license: { IsLicensed: 'true', Compliance: 'true,', }, }, }, } as unknown as GlobalState)).toEqual(false); expect(Selectors.canDownloadFilesOnMobile({ entities: { general: { config: { EnableMobileFileDownload: 'true', }, license: { IsLicensed: 'true', Compliance: 'true', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canDownloadFilesOnMobile({ entities: { general: { config: { EnableMobileFileDownload: 'false', }, license: { IsLicensed: 'false', Compliance: 'false', }, }, }, } as unknown as GlobalState)).toEqual(true); expect(Selectors.canDownloadFilesOnMobile({ entities: { general: { config: { EnableMobileFileDownload: 'false', }, license: { IsLicensed: 'true', Compliance: 'false', }, }, }, } as unknown as GlobalState)).toEqual(true); }); describe('getAutolinkedUrlSchemes', () => { it('setting doesn\'t exist', () => { const state = { entities: { general: { config: { }, }, }, } as unknown as GlobalState; expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual(General.DEFAULT_AUTOLINKED_URL_SCHEMES); expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual(Selectors.getAutolinkedUrlSchemes(state)); }); it('no custom url schemes', () => { const state = { entities: { general: { config: { CustomUrlSchemes: '', }, }, }, } as unknown as GlobalState; expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual(General.DEFAULT_AUTOLINKED_URL_SCHEMES); expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual(Selectors.getAutolinkedUrlSchemes(state)); }); it('one custom url scheme', () => { const state = { entities: { general: { config: { CustomUrlSchemes: 'dns', }, }, }, } as unknown as GlobalState; expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual([...General.DEFAULT_AUTOLINKED_URL_SCHEMES, 'dns']); expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual(Selectors.getAutolinkedUrlSchemes(state)); }); it('multiple custom url schemes', () => { const state = { entities: { general: { config: { CustomUrlSchemes: 'dns,steam,shttp', }, }, }, } as unknown as GlobalState; expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual([...General.DEFAULT_AUTOLINKED_URL_SCHEMES, 'dns', 'steam', 'shttp']); expect(Selectors.getAutolinkedUrlSchemes(state)).toEqual(Selectors.getAutolinkedUrlSchemes(state)); }); }); describe('getManagedResourcePaths', () => { test('should return empty array when the setting doesn\'t exist', () => { const state = { entities: { general: { config: { }, }, }, } as unknown as GlobalState; expect(Selectors.getManagedResourcePaths(state)).toEqual([]); }); test('should return an array of trusted paths', () => { const state = { entities: { general: { config: { ManagedResourcePaths: 'trusted,jitsi , test', }, }, }, } as unknown as GlobalState; expect(Selectors.getManagedResourcePaths(state)).toEqual(['trusted', 'jitsi', 'test']); }); }); describe('getFeatureFlagValue', () => { test('should return undefined when feature flag does not exist', () => { const state = { entities: { general: { config: { }, }, }, } as unknown as GlobalState; expect(Selectors.getFeatureFlagValue(state, 'CoolFeature')).toBeUndefined(); }); test('should return the value of a valid feature flag', () => { const state = { entities: { general: { config: { FeatureFlagCoolFeature: 'true', }, }, }, } as unknown as GlobalState; expect(Selectors.getFeatureFlagValue(state, 'CoolFeature')).toEqual('true'); }); }); describe('firstAdminVisitMarketplaceStatus', () => { test('should return empty when status does not exist', () => { const state = { entities: { general: { firstAdminVisitMarketplaceStatus: { }, }, }, } as unknown as GlobalState; expect(Selectors.getFirstAdminVisitMarketplaceStatus(state)).toEqual({}); }); test('should return the value of the status', () => { const state = { entities: { general: { firstAdminVisitMarketplaceStatus: true, }, }, } as unknown as GlobalState; expect(Selectors.getFirstAdminVisitMarketplaceStatus(state)).toEqual(true); state.entities.general.firstAdminVisitMarketplaceStatus = false; expect(Selectors.getFirstAdminVisitMarketplaceStatus(state)).toEqual(false); }); }); });
4,080
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/groups.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {UserProfile} from '@mattermost/types/users'; import * as Selectors from 'mattermost-redux/selectors/entities/groups'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Groups', () => { const teamID = 'c6ubwm63apgftbjs71enbjjpsh'; const expectedAssociatedGroupID1 = 'xh585kyz3tn55q6ipfo57btwnc'; const expectedAssociatedGroupID2 = 'emdwu98u6jg9xfn9p5zu48bojo'; const teamAssociatedGroupIDs = [expectedAssociatedGroupID1, expectedAssociatedGroupID2]; const channelID = 'c6ubwm63apgftbjs71enbjjpzz'; const expectedAssociatedGroupID3 = 'xos794c6tfb57eog481acokozc'; const expectedAssociatedGroupID4 = 'tnd8zod9f3fdtqosxjmhwucbth'; const channelAssociatedGroupIDs = [expectedAssociatedGroupID3, expectedAssociatedGroupID4]; const expectedAssociatedGroupID5 = 'pak66a8raibpmn6r3w8r7mf35a'; const group1 = { id: expectedAssociatedGroupID1, name: '9uobsi3xb3y5tfjb3ze7umnh1o', display_name: 'abc', description: '', source: 'ldap', remote_id: 'abc', create_at: 1553808969975, update_at: 1553808969975, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: true, }; const group2 = { id: expectedAssociatedGroupID2, name: '7ybu9oy77jgedqp4pph8f4j5ge', display_name: 'xyz', description: '', source: 'ldap', remote_id: 'xyz', create_at: 1553808972099, update_at: 1553808972099, delete_at: 0, has_syncables: false, member_count: 2, allow_reference: false, }; const group3 = { id: expectedAssociatedGroupID3, name: '5mte953ncbfpunpr3zmtopiwbo', display_name: 'developers', description: '', source: 'ldap', remote_id: 'developers', create_at: 1553808970570, update_at: 1553808970570, delete_at: 0, has_syncables: false, member_count: 5, allow_reference: false, }; const group4 = { id: expectedAssociatedGroupID4, name: 'nobctj4brfgtpj3a1peiyq47tc', display_name: 'engineering', description: '', source: 'ldap', create_at: 1553808971099, remote_id: 'engineering', update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, allow_reference: true, }; const group5 = { id: expectedAssociatedGroupID5, name: 'group5', display_name: 'R&D', description: '', source: 'custom', create_at: 1553808971099, remote_id: null, update_at: 1553808971099, delete_at: 0, has_syncables: false, member_count: 8, allow_reference: true, }; const user1 = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles: Record<string, UserProfile> = {}; profiles[user1.id] = user1; profiles[user2.id] = user2; profiles[user3.id] = user3; const testState = deepFreezeAndThrowOnMutation({ entities: { groups: { syncables: {}, members: {}, groups: { [expectedAssociatedGroupID1]: group1, [expectedAssociatedGroupID3]: group3, [expectedAssociatedGroupID4]: group4, [expectedAssociatedGroupID2]: group2, [expectedAssociatedGroupID5]: group5, }, myGroups: [ group1.id, group4.id, group2.id, ], }, teams: { teams: { [teamID]: {group_constrained: true, id: teamID}, }, groupsAssociatedToTeam: { [teamID]: {ids: teamAssociatedGroupIDs}, }, }, channels: { channels: { [channelID]: {team_id: teamID, id: channelID, group_constrained: true}, }, groupsAssociatedToChannel: { [channelID]: {ids: channelAssociatedGroupIDs}, }, }, general: { config: {}, }, preferences: { myPreferences: {}, }, users: { currentUserId: user1.id, profiles, }, }, }); it('getAssociatedGroupsByName', () => { const groupsByName = Selectors.getAssociatedGroupsByName(testState, teamID, channelID); expect(groupsByName[group1.name]).toEqual(group1); expect(groupsByName[group4.name]).toEqual(group4); expect(groupsByName[group5.name]).toEqual(group5); expect(Object.keys(groupsByName).length).toEqual(3); }); it('getGroupsAssociatedToTeam', () => { const expected = [ group1, group2, ]; expect(Selectors.getGroupsAssociatedToTeam(testState, teamID)).toEqual(expected); }); it('getGroupsNotAssociatedToTeam', () => { const expected = [ group3, group4, ]; expect(Selectors.getGroupsNotAssociatedToTeam(testState, teamID)).toEqual(expected); }); it('getGroupsAssociatedToChannel', () => { const expected = [ group3, group4, ]; expect(Selectors.getGroupsAssociatedToChannel(testState, channelID)).toEqual(expected); }); it('getGroupsNotAssociatedToChannel', () => { const expected = [ group1, group2, ]; expect(Selectors.getGroupsNotAssociatedToChannel(testState, channelID, teamID)).toEqual(expected); let cloneState = JSON.parse(JSON.stringify(testState)); cloneState.entities.teams.teams[teamID].group_constrained = true; cloneState.entities.teams.groupsAssociatedToTeam[teamID].ids = [expectedAssociatedGroupID1]; cloneState = deepFreezeAndThrowOnMutation(cloneState); expect(Selectors.getGroupsNotAssociatedToChannel(cloneState, channelID, teamID)).toEqual([group1]); }); it('getGroupsAssociatedToTeamForReference', () => { const expected = [ group1, ]; expect(Selectors.getGroupsAssociatedToTeamForReference(testState, teamID)).toEqual(expected); }); it('getGroupsAssociatedToChannelForReference', () => { const expected = [ group4, ]; expect(Selectors.getGroupsAssociatedToChannelForReference(testState, channelID)).toEqual(expected); }); it('makeGetAllAssociatedGroupsForReference', () => { const expected = [ group1, group4, group5, ]; const getAllAssociatedGroupsForReference = Selectors.makeGetAllAssociatedGroupsForReference(); expect(getAllAssociatedGroupsForReference(testState, false)).toEqual(expected); }); it('getMyGroupMentionKeys', () => { const expected = [ { key: `@${group1.name}`, }, { key: `@${group4.name}`, }, ]; expect(Selectors.getMyGroupMentionKeys(testState, false)).toEqual(expected); }); it('getMyGroupMentionKeysForChannel', () => { const expected = [ { key: `@${group1.name}`, }, { key: `@${group4.name}`, }, ]; expect(Selectors.getMyGroupMentionKeysForChannel(testState, teamID, channelID)).toEqual(expected); }); it('getAssociatedGroupsForReference team constrained', () => { const expected = [ group5, group1, ]; expect(Selectors.getAssociatedGroupsForReference(testState, teamID, '')).toEqual(expected); }); it('getAssociatedGroupsForReference channel constrained', () => { const expected = [ group5, group4, ]; expect(Selectors.getAssociatedGroupsForReference(testState, '', channelID)).toEqual(expected); }); it('getAssociatedGroupsForReference team and channel constrained', () => { const expected = [ group4, group1, group5, ]; expect(Selectors.getAssociatedGroupsForReference(testState, teamID, channelID)).toEqual(expected); }); it('getAssociatedGroupsForReference no constraints', () => { const expected = [ group1, group4, group5, ]; expect(Selectors.getAssociatedGroupsForReference(testState, '', '')).toEqual(expected); }); });
4,083
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/i18n.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GlobalState} from '@mattermost/types/store'; import * as Selectors from 'mattermost-redux/selectors/entities/i18n'; import TestHelper from '../../../test/test_helper'; describe('Selectors.I18n', () => { describe('getCurrentUserLocale', () => { it('not logged in', () => { const state = { entities: { users: { currentUserId: '', profiles: {}, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserLocale(state, 'default')).toEqual('default'); }); it('current user not loaded', () => { const currentUserId = TestHelper.generateId(); const state = { entities: { users: { currentUserId, profiles: {}, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserLocale(state, 'default')).toEqual('default'); }); it('current user without locale set', () => { const currentUserId = TestHelper.generateId(); const state = { entities: { users: { currentUserId, profiles: { [currentUserId]: {locale: ''}, }, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserLocale(state, 'default')).toEqual('default'); }); it('current user with locale set', () => { const currentUserId = TestHelper.generateId(); const state = { entities: { users: { currentUserId, profiles: { [currentUserId]: {locale: 'fr'}, }, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserLocale(state, 'default')).toEqual('fr'); }); }); });
4,085
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/integrations.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import {getAllCommands, getAutocompleteCommandsList, getOutgoingHooksInCurrentTeam} from './integrations'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Integrations', () => { TestHelper.initBasic(); const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const hook1 = TestHelper.fakeOutgoingHookWithId(team1.id); const hook2 = TestHelper.fakeOutgoingHookWithId(team1.id); const hook3 = TestHelper.fakeOutgoingHookWithId(team2.id); const hooks = {[hook1.id]: hook1, [hook2.id]: hook2, [hook3.id]: hook3}; const command1 = {...TestHelper.testCommand(team1.id), id: TestHelper.generateId(), auto_complete: false}; const command2 = {...TestHelper.testCommand(team2.id), id: TestHelper.generateId()}; const command3 = TestHelper.testCommand(team1.id); const command4 = TestHelper.testCommand(team2.id); const commands = {[command1.id]: command1, [command2.id]: command2}; const systemCommands = {[command3.trigger]: command3, [command4.trigger]: command4}; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, integrations: { outgoingHooks: hooks, commands, systemCommands, }, }, }); it('should return outgoing hooks in current team', () => { const hooksInCurrentTeam1 = [hook1, hook2]; expect(getOutgoingHooksInCurrentTeam(testState)).toEqual(hooksInCurrentTeam1); }); it('should get all commands', () => { const commandsInState = {...commands, ...systemCommands}; expect(getAllCommands(testState)).toEqual(commandsInState); }); it('should get all autocomplete commands by teamId', () => { const autocompleteCommandsForTeam = [command3]; expect(getAutocompleteCommandsList(testState)).toEqual(autocompleteCommandsForTeam); }); TestHelper.tearDown(); });
4,088
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/posts.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Post} from '@mattermost/types/posts'; import type {Reaction} from '@mattermost/types/reactions'; import type {GlobalState} from '@mattermost/types/store'; import type {UserProfile} from '@mattermost/types/users'; import {Posts, Preferences} from 'mattermost-redux/constants'; import * as Selectors from 'mattermost-redux/selectors/entities/posts'; import type {PostWithFormatData} from 'mattermost-redux/selectors/entities/posts'; import {makeGetProfilesForReactions} from 'mattermost-redux/selectors/entities/users'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../../test/test_helper'; const p = (override: Partial<PostWithFormatData>) => Object.assign(TestHelper.getPostMock(override), override); describe('Selectors.Posts', () => { const user1 = TestHelper.fakeUserWithId(); const profiles: Record<string, UserProfile> = {}; profiles[user1.id] = user1; const posts = { a: p({id: 'a', channel_id: '1', create_at: 1, highlight: false, user_id: user1.id}), b: p({id: 'b', channel_id: '1', create_at: 2, highlight: false, user_id: user1.id}), c: p({id: 'c', root_id: 'a', channel_id: '1', create_at: 3, highlight: false, user_id: 'b'}), d: p({id: 'd', root_id: 'b', channel_id: '1', create_at: 4, highlight: false, user_id: 'b'}), e: p({id: 'e', root_id: 'a', channel_id: '1', create_at: 5, highlight: false, user_id: 'b'}), f: p({id: 'f', channel_id: '2', create_at: 6, highlight: false, user_id: 'b'}), }; const reaction1 = {user_id: user1.id, emoji_name: '+1'} as Reaction; const reactionA = {[reaction1.user_id + '-' + reaction1.emoji_name]: reaction1}; const reactions = { a: reactionA, }; const testState = deepFreezeAndThrowOnMutation({ entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'true', }, }, users: { currentUserId: user1.id, profiles, }, posts: { posts, postsInChannel: { 1: [ {order: ['e', 'd', 'c', 'b', 'a'], recent: true}, ], 2: [ {order: ['f'], recent: true}, ], }, postsInThread: { a: ['c', 'e'], b: ['d'], }, reactions, }, preferences: { myPreferences: {}, }, }, }); it('should return single post with no children', () => { const getPostsForThread = Selectors.makeGetPostsForThread(); expect(getPostsForThread(testState, 'f')).toEqual([posts.f]); }); it('should return post with children', () => { const getPostsForThread = Selectors.makeGetPostsForThread(); expect(getPostsForThread(testState, 'a')).toEqual([posts.e, posts.c, posts.a]); }); it('should return memoized result for identical rootId', () => { const getPostsForThread = Selectors.makeGetPostsForThread(); const result = getPostsForThread(testState, 'a'); expect(result).toEqual(getPostsForThread(testState, 'a')); }); it('should return memoized result for multiple selectors with different props', () => { const getPostsForThread1 = Selectors.makeGetPostsForThread(); const getPostsForThread2 = Selectors.makeGetPostsForThread(); const result1 = getPostsForThread1(testState, 'a'); const result2 = getPostsForThread2(testState, 'b'); expect(result1).toEqual(getPostsForThread1(testState, 'a')); expect(result2).toEqual(getPostsForThread2(testState, 'b')); }); it('should return reactions for post', () => { const getReactionsForPost = Selectors.makeGetReactionsForPost(); expect(getReactionsForPost(testState, posts.a.id)).toEqual(reactionA); }); it('should return profiles for reactions', () => { const getProfilesForReactions = makeGetProfilesForReactions(); expect(getProfilesForReactions(testState, [reaction1])).toEqual([user1]); }); it('get posts in channel', () => { const post1 = { ...posts.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, }; const post2 = { ...posts.b, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: true, replyCount: 1, isCommentMention: false, }; const post3 = { ...posts.c, isFirstReply: true, isLastReply: true, previousPostIsComment: false, commentedOnPost: posts.a, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, }; const post4 = { ...posts.d, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: posts.b, consecutivePostByUser: true, replyCount: 1, isCommentMention: false, }; const post5 = { ...posts.e, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: posts.a, consecutivePostByUser: true, replyCount: 2, isCommentMention: false, }; const getPostsInChannel = Selectors.makeGetPostsInChannel(); expect(getPostsInChannel(testState, '1', 30)).toEqual([post5, post4, post3, post2, post1]); }); it('get posts around post in channel', () => { const post1: PostWithFormatData = { ...posts.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post2: PostWithFormatData = { ...posts.b, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: true, replyCount: 1, isCommentMention: false, highlight: false, }; const post3: PostWithFormatData = { ...posts.c, isFirstReply: true, isLastReply: true, previousPostIsComment: false, commentedOnPost: posts.a, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: true, }; const post4: PostWithFormatData = { ...posts.d, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: posts.b, consecutivePostByUser: true, replyCount: 1, isCommentMention: false, highlight: false, }; const post5: PostWithFormatData = { ...posts.e, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: posts.a, consecutivePostByUser: true, replyCount: 2, isCommentMention: false, highlight: false, }; const getPostsAroundPost = Selectors.makeGetPostsAroundPost(); expect(getPostsAroundPost(testState, post3.id, '1')).toEqual([post5, post4, post3, post2, post1]); }); it('get posts in channel with notify comments as any', () => { const userAny = TestHelper.fakeUserWithId(); userAny.notify_props = {comments: 'any'} as UserProfile['notify_props']; const profilesAny: Record<string, UserProfile> = {}; profilesAny[userAny.id] = userAny; const postsAny = { a: p({id: 'a', channel_id: '1', create_at: 1, highlight: false, user_id: userAny.id}), b: p({id: 'b', channel_id: '1', create_at: 2, highlight: false, user_id: 'b'}), c: p({id: 'c', root_id: 'a', channel_id: '1', create_at: 3, highlight: false, user_id: 'b'}), d: p({id: 'd', root_id: 'b', channel_id: '1', create_at: 4, highlight: false, user_id: userAny.id}), e: p({id: 'e', root_id: 'a', channel_id: '1', create_at: 5, highlight: false, user_id: 'b'}), f: p({id: 'f', root_id: 'b', channel_id: '1', create_at: 6, highlight: false, user_id: 'b'}), g: p({id: 'g', channel_id: '2', create_at: 7, highlight: false, user_id: 'b'}), }; const testStateAny = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userAny.id, profiles: profilesAny, }, posts: { posts: postsAny, postsInChannel: { 1: [ {order: ['f', 'e', 'd', 'c', 'b', 'a'], recent: true}, ], 2: [ {order: ['g'], recent: true}, ], }, postsInThread: { a: ['c', 'e'], b: ['d', 'f'], }, }, preferences: { myPreferences: {}, }, }, }); const post1: PostWithFormatData = { ...postsAny.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post2: PostWithFormatData = { ...postsAny.b, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: true, highlight: false, }; const post3: PostWithFormatData = { ...postsAny.c, isFirstReply: true, isLastReply: true, previousPostIsComment: false, commentedOnPost: postsAny.a, consecutivePostByUser: true, replyCount: 2, isCommentMention: true, highlight: false, }; const post4: PostWithFormatData = { ...postsAny.d, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsAny.b, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post5: PostWithFormatData = { ...postsAny.e, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsAny.a, consecutivePostByUser: false, replyCount: 2, isCommentMention: true, highlight: false, }; const post6: PostWithFormatData = { ...postsAny.f, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsAny.b, consecutivePostByUser: true, replyCount: 2, isCommentMention: true, highlight: false, }; const getPostsInChannel = Selectors.makeGetPostsInChannel(); expect(getPostsInChannel(testStateAny, '1', 30)).toEqual([post6, post5, post4, post3, post2, post1]); }); it('get posts in channel with notify comments as root', () => { const userRoot = TestHelper.fakeUserWithId(); userRoot.notify_props = {comments: 'root'} as UserProfile['notify_props']; const profilesRoot: Record<string, UserProfile> = {}; profilesRoot[userRoot.id] = userRoot; const postsRoot = { a: p({id: 'a', channel_id: '1', create_at: 1, highlight: false, user_id: userRoot.id}), b: p({id: 'b', channel_id: '1', create_at: 2, highlight: false, user_id: 'b'}), c: p({id: 'c', root_id: 'a', channel_id: '1', create_at: 3, highlight: false, user_id: 'b'}), d: p({id: 'd', root_id: 'b', channel_id: '1', create_at: 4, highlight: false, user_id: userRoot.id}), e: p({id: 'e', root_id: 'a', channel_id: '1', create_at: 5, highlight: false, user_id: 'b'}), f: p({id: 'f', root_id: 'b', channel_id: '1', create_at: 6, highlight: false, user_id: 'b'}), g: p({id: 'g', channel_id: '2', create_at: 7, highlight: false, user_id: 'b'}), }; const testStateRoot = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userRoot.id, profiles: profilesRoot, }, posts: { posts: postsRoot, postsInChannel: { 1: [ {order: ['f', 'e', 'd', 'c', 'b', 'a'], recent: true}, ], 2: [ {order: ['g'], recent: true}, ], }, postsInThread: { a: ['c', 'e'], b: ['d', 'f'], }, }, preferences: { myPreferences: {}, }, }, }); const post1 = { ...postsRoot.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, }; const post2 = { ...postsRoot.b, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, }; const post3 = { ...postsRoot.c, isFirstReply: true, isLastReply: true, previousPostIsComment: false, commentedOnPost: postsRoot.a, consecutivePostByUser: true, replyCount: 2, isCommentMention: true, }; const post4 = { ...postsRoot.d, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsRoot.b, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, }; const post5 = { ...postsRoot.e, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsRoot.a, consecutivePostByUser: false, replyCount: 2, isCommentMention: true, }; const post6 = { ...postsRoot.f, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsRoot.b, consecutivePostByUser: true, replyCount: 2, isCommentMention: false, }; const getPostsInChannel = Selectors.makeGetPostsInChannel(); expect(getPostsInChannel(testStateRoot, '1', 30)).toEqual([post6, post5, post4, post3, post2, post1]); }); it('get posts in channel with notify comments as never', () => { const userNever = TestHelper.fakeUserWithId(); userNever.notify_props = {comments: 'never'} as UserProfile['notify_props']; const profilesNever: Record<string, UserProfile> = {}; profilesNever[userNever.id] = userNever; const postsNever = { a: p({id: 'a', channel_id: '1', create_at: 1, highlight: false, user_id: userNever.id}), b: p({id: 'b', channel_id: '1', create_at: 2, highlight: false, user_id: 'b'}), c: p({id: 'c', root_id: 'a', channel_id: '1', create_at: 3, highlight: false, user_id: 'b'}), d: p({id: 'd', root_id: 'b', channel_id: '1', create_at: 4, highlight: false, user_id: userNever.id}), e: p({id: 'e', root_id: 'a', channel_id: '1', create_at: 5, highlight: false, user_id: 'b'}), f: p({id: 'f', root_id: 'b', channel_id: '1', create_at: 6, highlight: false, user_id: 'b'}), g: p({id: 'g', channel_id: '2', create_at: 7, highlight: false, user_id: 'b'}), }; const testStateNever = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userNever.id, profiles: profilesNever, }, posts: { posts: postsNever, postsInChannel: { 1: [ {order: ['f', 'e', 'd', 'c', 'b', 'a'], recent: true}, ], 2: [ {order: ['g'], recent: true}, ], }, postsInThread: { a: ['c', 'e'], b: ['d', 'f'], }, }, preferences: { myPreferences: {}, }, }, }); const post1: PostWithFormatData = { ...postsNever.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post2: PostWithFormatData = { ...postsNever.b, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post3: PostWithFormatData = { ...postsNever.c, isFirstReply: true, isLastReply: true, previousPostIsComment: false, commentedOnPost: postsNever.a, consecutivePostByUser: true, replyCount: 2, isCommentMention: false, highlight: false, }; const post4: PostWithFormatData = { ...postsNever.d, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsNever.b, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post5: PostWithFormatData = { ...postsNever.e, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsNever.a, consecutivePostByUser: false, replyCount: 2, isCommentMention: false, highlight: false, }; const post6: PostWithFormatData = { ...postsNever.f, isFirstReply: true, isLastReply: true, previousPostIsComment: true, commentedOnPost: postsNever.b, consecutivePostByUser: true, replyCount: 2, isCommentMention: false, highlight: false, }; const getPostsInChannel = Selectors.makeGetPostsInChannel(); expect(getPostsInChannel(testStateNever, '1', 30)).toEqual([post6, post5, post4, post3, post2, post1]); }); it('gets posts around post in channel not adding ephemeral post to replyCount', () => { const userAny = TestHelper.fakeUserWithId(); userAny.notify_props = {comments: 'any'} as UserProfile['notify_props']; const profilesAny: Record<string, UserProfile> = {}; profilesAny[userAny.id] = userAny; const postsAny = { a: {id: 'a', channel_id: '1', create_at: 1, highlight: false, user_id: userAny.id}, b: {id: 'b', root_id: 'a', channel_id: '1', create_at: 2, highlight: false, user_id: 'b'}, c: {id: 'c', root_id: 'a', channel_id: '1', create_at: 3, highlight: false, user_id: 'b', type: Posts.POST_TYPES.EPHEMERAL}, d: {id: 'd', channel_id: '2', create_at: 4, highlight: false, user_id: 'b'}, }; const testStateAny = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userAny.id, profiles: profilesAny, }, posts: { posts: postsAny, postsInChannel: { 1: [ {order: ['c', 'b', 'a'], recent: true}, ], 2: [ {order: ['d'], recent: true}, ], }, postsInThread: { a: ['b', 'c'], }, }, preferences: { myPreferences: {}, }, }, }); const post1 = { ...postsAny.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 1, isCommentMention: false, highlight: true, }; const post2 = { ...postsAny.b, isFirstReply: true, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 1, isCommentMention: true, }; const post3 = { ...postsAny.c, isFirstReply: false, isLastReply: true, previousPostIsComment: true, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 1, isCommentMention: true, }; const getPostsAroundPost = Selectors.makeGetPostsAroundPost(); expect(getPostsAroundPost(testStateAny, post1.id, '1')).toEqual([post3, post2, post1]); }); it('gets posts in channel not adding ephemeral post to replyCount', () => { const userAny = TestHelper.fakeUserWithId(); userAny.notify_props = {comments: 'any'} as UserProfile['notify_props']; const profilesAny: Record<string, UserProfile> = {}; profilesAny[userAny.id] = userAny; const postsAny = { a: {id: 'a', channel_id: '1', create_at: 1, highlight: false, user_id: userAny.id}, b: {id: 'b', root_id: 'a', channel_id: '1', create_at: 2, highlight: false, user_id: 'b', type: Posts.POST_TYPES.EPHEMERAL}, c: {id: 'c', root_id: 'a', channel_id: '1', create_at: 3, highlight: false, user_id: 'b', state: Posts.POST_DELETED}, d: {id: 'd', channel_id: '2', create_at: 4, highlight: false, user_id: 'b'}, }; const testStateAny = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: userAny.id, profiles: profilesAny, }, posts: { posts: postsAny, postsInChannel: { 1: [ {order: ['c', 'b', 'a'], recent: true}, ], 2: [ {order: ['d'], recent: true}, ], }, postsInThread: { a: ['b', 'c'], }, }, preferences: { myPreferences: {}, }, }, }); const post1 = { ...postsAny.a, isFirstReply: false, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 0, isCommentMention: false, }; const post2 = { ...postsAny.b, isFirstReply: true, isLastReply: false, previousPostIsComment: false, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 0, isCommentMention: true, }; const post3 = { ...postsAny.c, isFirstReply: false, isLastReply: true, previousPostIsComment: true, commentedOnPost: undefined, consecutivePostByUser: false, replyCount: 0, isCommentMention: true, }; const getPostsInChannel = Selectors.makeGetPostsInChannel(); expect(getPostsInChannel(testStateAny, '1', 30)).toEqual([post3, post2, post1]); }); it('get current history item', () => { const testState1 = deepFreezeAndThrowOnMutation({ entities: { posts: { messagesHistory: { messages: ['test1', 'test2', 'test3'], index: { post: 1, comment: 2, }, }, }, }, }); const testState2 = deepFreezeAndThrowOnMutation({ entities: { posts: { messagesHistory: { messages: ['test1', 'test2', 'test3'], index: { post: 0, comment: 0, }, }, }, }, }); const testState3 = deepFreezeAndThrowOnMutation({ entities: { posts: { messagesHistory: { messages: [], index: { post: -1, comment: -1, }, }, }, }, }); const getHistoryMessagePost = Selectors.makeGetMessageInHistoryItem(Posts.MESSAGE_TYPES.POST as 'post'); const getHistoryMessageComment = Selectors.makeGetMessageInHistoryItem(Posts.MESSAGE_TYPES.COMMENT as 'comment'); expect(getHistoryMessagePost(testState1)).toEqual('test2'); expect(getHistoryMessageComment(testState1)).toEqual('test3'); expect(getHistoryMessagePost(testState2)).toEqual('test1'); expect(getHistoryMessageComment(testState2)).toEqual('test1'); expect(getHistoryMessagePost(testState3)).toEqual(''); expect(getHistoryMessageComment(testState3)).toEqual(''); }); describe('getPostIdsForThread', () => { const user1 = TestHelper.fakeUserWithId(); const profiles: Record<string, UserProfile> = {}; profiles[user1.id] = user1; it('single post', () => { const getPostIdsForThread = Selectors.makeGetPostIdsForThread(); const state = { entities: { general: { config: {}, }, users: { currentUserId: user1.id, profiles, }, preferences: { myPreferences: {}, }, posts: { posts: { 1001: {id: '1001', create_at: 1001}, 1002: {id: '1002', create_at: 1002, root_id: '1001'}, 1003: {id: '1003', create_at: 1003}, 1004: {id: '1004', create_at: 1004, root_id: '1001'}, 1005: {id: '1005', create_at: 1005}, }, postsInThread: { 1001: ['1002', '1004'], }, }, }, } as unknown as GlobalState; const expected = ['1005']; expect(getPostIdsForThread(state, '1005')).toEqual(expected); }); it('thread', () => { const getPostIdsForThread = Selectors.makeGetPostIdsForThread(); const state = { entities: { general: { config: {}, }, users: { currentUserId: user1.id, profiles, }, preferences: { myPreferences: {}, }, posts: { posts: { 1001: {id: '1001', create_at: 1001}, 1002: {id: '1002', create_at: 1002, root_id: '1001'}, 1003: {id: '1003', create_at: 1003}, 1004: {id: '1004', create_at: 1004, root_id: '1001'}, 1005: {id: '1005', create_at: 1005}, }, postsInThread: { 1001: ['1002', '1004'], }, }, }, } as unknown as GlobalState; const expected = ['1004', '1002', '1001']; expect(getPostIdsForThread(state, '1001')).toEqual(expected); }); it('memoization', () => { const getPostIdsForThread = Selectors.makeGetPostIdsForThread(); let state = { entities: { general: { config: {}, }, users: { currentUserId: user1.id, profiles, }, preferences: { myPreferences: {}, }, posts: { posts: { 1001: {id: '1001', create_at: 1001}, 1002: {id: '1002', create_at: 1002, root_id: '1001'}, 1003: {id: '1003', create_at: 1003}, 1004: {id: '1004', create_at: 1004, root_id: '1001'}, 1005: {id: '1005', create_at: 1005}, }, postsInThread: { 1001: ['1002', '1004'], }, }, }, } as unknown as GlobalState; // One post, no changes let previous = getPostIdsForThread(state, '1005'); let now = getPostIdsForThread(state, '1005'); expect(now).toEqual(['1005']); expect(now).toBe(previous); // One post, unrelated changes state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, 1006: p({id: '1006', create_at: 1006, root_id: '1003'}), }, postsInThread: { ...state.entities.posts.postsInThread, 1003: ['1006'], }, }, }, }; previous = now; now = getPostIdsForThread(state, '1005'); expect(now).toEqual(['1005']); expect(now).toBe(previous); // One post, changes to post state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, 1005: p({id: '1005', create_at: 1005, update_at: 1006}), }, postsInThread: state.entities.posts.postsInThread, }, }, }; previous = now; now = getPostIdsForThread(state, '1005'); expect(now).toEqual(['1005']); expect(now).toBe(previous); // Change of thread previous = now; now = getPostIdsForThread(state, '1001'); expect(now).toEqual(['1004', '1002', '1001']); expect(now).not.toBe(previous); previous = now; now = getPostIdsForThread(state, '1001'); expect(now).toBe(previous); // New post in thread state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, 1007: p({id: '1007', create_at: 1007, root_id: '1001'}), }, postsInThread: { ...state.entities.posts.postsInThread, 1001: [...state.entities.posts.postsInThread['1001'], '1007'], }, }, }, }; previous = now; now = getPostIdsForThread(state, '1001'); expect(now).toEqual(['1007', '1004', '1002', '1001']); expect(now).not.toBe(previous); previous = now; now = getPostIdsForThread(state, '1001'); expect(now).toEqual(['1007', '1004', '1002', '1001']); expect(now).toBe(previous); }); it('memoization with multiple selectors', () => { const getPostIdsForThread1 = Selectors.makeGetPostIdsForThread(); const getPostIdsForThread2 = Selectors.makeGetPostIdsForThread(); const state = { entities: { general: { config: {}, }, users: { currentUserId: user1.id, profiles, }, preferences: { myPreferences: {}, }, posts: { posts: { 1001: {id: '1001', create_at: 1001}, 1002: {id: '1002', create_at: 1002, root_id: '1001'}, 1003: {id: '1003', create_at: 1003}, 1004: {id: '1004', create_at: 1004, root_id: '1001'}, 1005: {id: '1005', create_at: 1005}, }, postsInThread: { 1001: ['1002', '1004'], }, }, }, } as unknown as GlobalState; let now1 = getPostIdsForThread1(state, '1001'); let now2 = getPostIdsForThread2(state, '1001'); expect(now1).not.toBe(now2); expect(now1).toEqual(now2); let previous1 = now1; now1 = getPostIdsForThread1(state, '1001'); expect(now1).toEqual(previous1); const previous2 = now2; now2 = getPostIdsForThread2(state, '1003'); expect(now2).not.toEqual(previous2); expect(now1).not.toEqual(now2); previous1 = now1; now1 = getPostIdsForThread1(state, '1001'); expect(now1).toEqual(previous1); }); }); describe('getPostIdsAroundPost', () => { it('no posts around', () => { const getPostIdsAroundPost = Selectors.makeGetPostIdsAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostIdsAroundPost(state, 'a', '1234')).toEqual(['a']); }); it('posts around', () => { const getPostIdsAroundPost = Selectors.makeGetPostIdsAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostIdsAroundPost(state, 'c', '1234')).toEqual(['a', 'b', 'c', 'd', 'e']); }); it('posts before limit', () => { const getPostIdsAroundPost = Selectors.makeGetPostIdsAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostIdsAroundPost(state, 'a', '1234', {postsBeforeCount: 2})).toEqual(['a', 'b', 'c']); }); it('posts after limit', () => { const getPostIdsAroundPost = Selectors.makeGetPostIdsAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostIdsAroundPost(state, 'e', '1234', {postsAfterCount: 3})).toEqual(['b', 'c', 'd', 'e']); }); it('posts before/after limit', () => { const getPostIdsAroundPost = Selectors.makeGetPostIdsAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostIdsAroundPost(state, 'c', '1234', {postsBeforeCount: 2, postsAfterCount: 1})).toEqual(['b', 'c', 'd', 'e']); }); it('memoization', () => { const getPostIdsAroundPost = Selectors.makeGetPostIdsAroundPost(); let state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e'], recent: true}, ], }, }, }, } as unknown as GlobalState; // No limit, no changes let previous = getPostIdsAroundPost(state, 'c', '1234'); let now = getPostIdsAroundPost(state, 'c', '1234'); expect(now).toEqual(['a', 'b', 'c', 'd', 'e']); expect(now).toBe(previous); // Changes to posts in another channel state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, abcd: [ {order: ['g', 'h', 'i', 'j', 'k', 'l'], recent: true}, ], }, }, }, }; previous = now; now = getPostIdsAroundPost(state, 'c', '1234'); expect(now).toEqual(['a', 'b', 'c', 'd', 'e']); expect(now).toBe(previous); // Changes to posts in this channel state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, ], }, }, }, }; previous = now; now = getPostIdsAroundPost(state, 'c', '1234'); expect(now).toEqual(['a', 'b', 'c', 'd', 'e', 'f']); expect(now).not.toBe(previous); previous = now; now = getPostIdsAroundPost(state, 'c', '1234'); expect(now).toEqual(['a', 'b', 'c', 'd', 'e', 'f']); expect(now).toBe(previous); // Change of channel previous = now; now = getPostIdsAroundPost(state, 'i', 'abcd'); expect(now).toEqual(['g', 'h', 'i', 'j', 'k', 'l']); expect(now).not.toBe(previous); previous = now; now = getPostIdsAroundPost(state, 'i', 'abcd'); expect(now).toEqual(['g', 'h', 'i', 'j', 'k', 'l']); expect(now).toBe(previous); // With limits previous = now; now = getPostIdsAroundPost(state, 'i', 'abcd', {postsBeforeCount: 2, postsAfterCount: 1}); expect(now).toEqual(['h', 'i', 'j', 'k']); expect(now).not.toBe(previous); previous = now; now = getPostIdsAroundPost(state, 'i', 'abcd', {postsBeforeCount: 2, postsAfterCount: 1}); // Note that the options object is a new object each time expect(now).toEqual(['h', 'i', 'j', 'k']); expect(now).toBe(previous); // Change of limits previous = now; now = getPostIdsAroundPost(state, 'i', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['g', 'h', 'i', 'j']); expect(now).not.toBe(previous); previous = now; now = getPostIdsAroundPost(state, 'i', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['g', 'h', 'i', 'j']); expect(now).toBe(previous); // Change of post previous = now; now = getPostIdsAroundPost(state, 'j', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['h', 'i', 'j', 'k']); expect(now).not.toBe(previous); previous = now; now = getPostIdsAroundPost(state, 'j', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['h', 'i', 'j', 'k']); expect(now).toBe(previous); // Change of posts past limit state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, abcd: [ {order: ['y', 'g', 'h', 'i', 'j', 'k', 'l', 'f', 'z'], recent: true}, ], }, }, }, }; previous = now; now = getPostIdsAroundPost(state, 'j', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['h', 'i', 'j', 'k']); expect(now).toBe(previous); // Change of post order state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, abcd: [ {order: ['y', 'g', 'i', 'h', 'j', 'l', 'k', 'z'], recent: true}, ], }, }, }, }; previous = now; now = getPostIdsAroundPost(state, 'j', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['i', 'h', 'j', 'l']); expect(now).not.toBe(previous); previous = now; now = getPostIdsAroundPost(state, 'j', 'abcd', {postsBeforeCount: 1, postsAfterCount: 2}); expect(now).toEqual(['i', 'h', 'j', 'l']); expect(now).toBe(previous); }); it('memoization with multiple selectors', () => { const getPostIdsAroundPost1 = Selectors.makeGetPostIdsAroundPost(); const getPostIdsAroundPost2 = Selectors.makeGetPostIdsAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, ], abcd: [ {order: ['g', 'h', 'i'], recent: true}, ], }, }, }, } as unknown as GlobalState; const previous1 = getPostIdsAroundPost1(state, 'c', '1234'); const previous2 = getPostIdsAroundPost2(state, 'h', 'abcd', {postsBeforeCount: 1, postsAfterCount: 0}); expect(previous1).not.toBe(previous2); const now1 = getPostIdsAroundPost1(state, 'c', '1234'); const now2 = getPostIdsAroundPost2(state, 'i', 'abcd', {postsBeforeCount: 1, postsAfterCount: 0}); expect(now1).toBe(previous1); expect(now2).not.toBe(previous2); expect(now1).not.toBe(now2); }); }); describe('makeGetPostsChunkAroundPost', () => { it('no posts around', () => { const getPostsChunkAroundPost = Selectors.makeGetPostsChunkAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostsChunkAroundPost(state, 'a', '1234')).toEqual({order: ['a'], recent: true}); }); it('posts around', () => { const getPostsChunkAroundPost = Selectors.makeGetPostsChunkAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostsChunkAroundPost(state, 'c', '1234')).toEqual({order: ['a', 'b', 'c', 'd', 'e'], recent: true}); }); it('no matching posts', () => { const getPostsChunkAroundPost = Selectors.makeGetPostsChunkAroundPost(); const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, ], }, }, }, } as unknown as GlobalState; expect(getPostsChunkAroundPost(state, 'noChunk', '1234')).toEqual(undefined); }); it('memoization', () => { const getPostsChunkAroundPost = Selectors.makeGetPostsChunkAroundPost(); let state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e'], recent: true}, ], }, }, }, } as unknown as GlobalState; // No limit, no changes let previous = getPostsChunkAroundPost(state, 'c', '1234'); // Changes to posts in another channel state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, abcd: [ {order: ['g', 'h', 'i', 'j', 'k', 'l'], recent: true}, ], }, }, }, }; let now = getPostsChunkAroundPost(state, 'c', '1234'); expect(now).toEqual({order: ['a', 'b', 'c', 'd', 'e'], recent: true}); expect(now).toBe(previous); // Changes to posts in this channel state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, ], }, }, }, }; previous = now; now = getPostsChunkAroundPost(state, 'c', '1234'); expect(now).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); expect(now).not.toBe(previous); previous = now; now = getPostsChunkAroundPost(state, 'c', '1234'); expect(now).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); expect(now).toBe(previous); // Change of channel previous = now; now = getPostsChunkAroundPost(state, 'i', 'abcd'); expect(now).toEqual({order: ['g', 'h', 'i', 'j', 'k', 'l'], recent: true}); expect(now).not.toBe(previous); previous = now; now = getPostsChunkAroundPost(state, 'i', 'abcd'); expect(now).toEqual({order: ['g', 'h', 'i', 'j', 'k', 'l'], recent: true}); expect(now).toBe(previous); // Change of post in the chunk previous = now; now = getPostsChunkAroundPost(state, 'j', 'abcd'); expect(now).toEqual({order: ['g', 'h', 'i', 'j', 'k', 'l'], recent: true}); expect(now).toBe(previous); // Change of post order state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, postsInChannel: { ...state.entities.posts.postsInChannel, abcd: [ {order: ['y', 'g', 'i', 'h', 'j', 'l', 'k', 'z'], recent: true}, ], }, }, }, }; previous = now; now = getPostsChunkAroundPost(state, 'j', 'abcd'); expect(now).toEqual({order: ['y', 'g', 'i', 'h', 'j', 'l', 'k', 'z'], recent: true}); expect(now).not.toBe(previous); previous = now; now = getPostsChunkAroundPost(state, 'j', 'abcd'); expect(now).toEqual({order: ['y', 'g', 'i', 'h', 'j', 'l', 'k', 'z'], recent: true}); expect(now).toBe(previous); }); }); describe('getRecentPostsChunkInChannel', () => { it('Should return as recent chunk exists', () => { const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, ], }, }, }, } as unknown as GlobalState; const recentPostsChunkInChannel = Selectors.getRecentPostsChunkInChannel(state, '1234'); expect(recentPostsChunkInChannel).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); }); it('Should return undefined as recent chunk does not exists', () => { const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: false}, ], }, }, }, } as unknown as GlobalState; const recentPostsChunkInChannel = Selectors.getRecentPostsChunkInChannel(state, '1234'); expect(recentPostsChunkInChannel).toEqual(undefined); }); }); describe('getOldestPostsChunkInChannel', () => { it('Should return as oldest chunk exists', () => { const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], oldest: true, recent: true}, ], }, }, }, } as unknown as GlobalState; const oldestPostsChunkInChannel = Selectors.getOldestPostsChunkInChannel(state, '1234'); expect(oldestPostsChunkInChannel).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true, oldest: true}); }); it('Should return undefined as recent chunk does not exists', () => { const state = { entities: { posts: { postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: false, oldest: false}, ], }, }, }, } as unknown as GlobalState; const oldestPostsChunkInChannel = Selectors.getOldestPostsChunkInChannel(state, '1234'); expect(oldestPostsChunkInChannel).toEqual(undefined); }); }); describe('getPostsChunkInChannelAroundTime', () => { it('getPostsChunkInChannelAroundTime', () => { const state = { entities: { posts: { posts: { e: {id: 'e', create_at: 1010}, j: {id: 'j', create_at: 1001}, a: {id: 'a', create_at: 1020}, f: {id: 'f', create_at: 1010}, }, postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, {order: ['e', 'f', 'g', 'h', 'i', 'j'], recent: false}, ], }, }, }, } as unknown as GlobalState; const postsChunkInChannelAroundTime1 = Selectors.getPostsChunkInChannelAroundTime(state, '1234', 1011); expect(postsChunkInChannelAroundTime1).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); const postsChunkInChannelAroundTime2 = Selectors.getPostsChunkInChannelAroundTime(state, '1234', 1002); expect(postsChunkInChannelAroundTime2).toEqual({order: ['e', 'f', 'g', 'h', 'i', 'j'], recent: false}); const postsChunkInChannelAroundTime3 = Selectors.getPostsChunkInChannelAroundTime(state, '1234', 1010); expect(postsChunkInChannelAroundTime3).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); const postsChunkInChannelAroundTime4 = Selectors.getPostsChunkInChannelAroundTime(state, '1234', 1020); expect(postsChunkInChannelAroundTime4).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); }); }); describe('getUnreadPostsChunk', () => { it('should return recent chunk even if the timstamp is greater than the last post', () => { const state = { entities: { posts: { posts: { e: {id: 'e', create_at: 1010}, j: {id: 'j', create_at: 1001}, a: {id: 'a', create_at: 1020}, f: {id: 'f', create_at: 1010}, }, postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, {order: ['e', 'f', 'g', 'h', 'i', 'j'], recent: false}, ], }, }, }, } as unknown as GlobalState; const unreadPostsChunk = Selectors.getUnreadPostsChunk(state, '1234', 1030); expect(unreadPostsChunk).toEqual({order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}); }); it('should return a not recent chunk based on the timestamp', () => { const state = { entities: { posts: { posts: { e: {id: 'e', create_at: 1010}, j: {id: 'j', create_at: 1001}, a: {id: 'a', create_at: 1020}, f: {id: 'f', create_at: 1010}, }, postsInChannel: { 1234: [ {order: ['a', 'b', 'c', 'd', 'e', 'f'], recent: true}, {order: ['e', 'f', 'g', 'h', 'i', 'j'], recent: false}, ], }, }, }, } as unknown as GlobalState; const unreadPostsChunk = Selectors.getUnreadPostsChunk(state, '1234', 1002); expect(unreadPostsChunk).toEqual({order: ['e', 'f', 'g', 'h', 'i', 'j'], recent: false}); }); it('should return recent chunk if it is an empty array', () => { const state = { entities: { posts: { posts: {}, postsInChannel: { 1234: [ {order: [], recent: true}, ], }, }, }, } as unknown as GlobalState; const unreadPostsChunk = Selectors.getUnreadPostsChunk(state, '1234', 1002); expect(unreadPostsChunk).toEqual({order: [], recent: true}); }); it('should return oldest chunk if timstamp greater than the oldest post', () => { const state = { entities: { posts: { posts: { a: {id: 'a', create_at: 1001}, b: {id: 'b', create_at: 1002}, c: {id: 'c', create_at: 1003}, }, postsInChannel: { 1234: [ {order: ['a', 'b', 'c'], recent: true, oldest: true}, ], }, }, }, } as unknown as GlobalState; const unreadPostsChunk = Selectors.getUnreadPostsChunk(state, '1234', 1000); expect(unreadPostsChunk).toEqual({order: ['a', 'b', 'c'], recent: true, oldest: true}); }); }); describe('getPostsForIds', () => { it('selector', () => { const getPostsForIds = Selectors.makeGetPostsForIds(); const testPosts: Record<string, Post> = { 1000: p({id: '1000'}), 1001: p({id: '1001'}), 1002: p({id: '1002'}), 1003: p({id: '1003'}), 1004: p({id: '1004'}), }; const state = { entities: { posts: { posts: testPosts, }, }, } as unknown as GlobalState; const postIds = ['1000', '1002', '1003']; const actual = getPostsForIds(state, postIds); expect(actual.length).toEqual(3); expect(actual[0]).toEqual(testPosts[postIds[0]]); expect(actual[1]).toEqual(testPosts[postIds[1]]); expect(actual[2]).toEqual(testPosts[postIds[2]]); }); it('memoization', () => { const getPostsForIds = Selectors.makeGetPostsForIds(); const testPosts: Record<string, Post> = { 1000: p({id: '1000'}), 1001: p({id: '1001'}), 1002: p({id: '1002'}), 1003: p({id: '1003'}), 1004: p({id: '1004'}), }; let state = { entities: { posts: { posts: { ...testPosts, }, }, }, } as unknown as GlobalState; let postIds = ['1000', '1002', '1003']; let now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1000'], testPosts['1002'], testPosts['1003']]); // No changes let previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1000'], testPosts['1002'], testPosts['1003']]); expect(now).toBe(previous); // New, identical ids postIds = ['1000', '1002', '1003']; previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1000'], testPosts['1002'], testPosts['1003']]); expect(now).toBe(previous); // New posts, no changes to ones in ids state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, }, }, }, }; previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1000'], testPosts['1002'], testPosts['1003']]); expect(now).toBe(previous); // New ids postIds = ['1001', '1002', '1004']; previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1001'], testPosts['1002'], testPosts['1004']]); expect(now).not.toBe(previous); previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1001'], testPosts['1002'], testPosts['1004']]); expect(now).toBe(previous); // New posts, changes to ones in ids const newPost = p({id: '1002', message: 'abcd'}); state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, [newPost.id]: newPost, }, }, }, }; previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1001'], newPost, testPosts['1004']]); expect(now).not.toBe(previous); previous = now; now = getPostsForIds(state, postIds); expect(now).toEqual([testPosts['1001'], newPost, testPosts['1004']]); expect(now).toBe(previous); }); }); describe('getMostRecentPostIdInChannel', () => { it('system messages visible', () => { const testPosts = { 1000: {id: '1000', type: 'system_join_channel'}, 1001: {id: '1001', type: 'system_join_channel'}, 1002: {id: '1002'}, 1003: {id: '1003'}, }; const state = { entities: { posts: { posts: testPosts, postsInChannel: { channelId: [ {order: ['1000', '1001', '1002', '1003'], recent: true}, ], }, }, preferences: { myPreferences: { [`${Preferences.CATEGORY_ADVANCED_SETTINGS}--${Preferences.ADVANCED_FILTER_JOIN_LEAVE}`]: {value: 'true'}, }, }, }, } as unknown as GlobalState; const postId = Selectors.getMostRecentPostIdInChannel(state, 'channelId'); expect(postId).toBe('1000'); }); it('system messages hidden', () => { const testPosts = { 1000: {id: '1000', type: 'system_join_channel'}, 1001: {id: '1001', type: 'system_join_channel'}, 1002: {id: '1002'}, 1003: {id: '1003'}, }; const state = { entities: { posts: { posts: testPosts, postsInChannel: { channelId: [ {order: ['1000', '1001', '1002', '1003'], recent: true}, ], }, }, preferences: { myPreferences: { [`${Preferences.CATEGORY_ADVANCED_SETTINGS}--${Preferences.ADVANCED_FILTER_JOIN_LEAVE}`]: {value: 'false'}, }, }, }, } as unknown as GlobalState; const postId = Selectors.getMostRecentPostIdInChannel(state, 'channelId'); expect(postId).toEqual('1002'); }); }); describe('getLatestReplyablePostId', () => { it('no posts', () => { const state = { entities: { channels: { currentChannelId: 'abcd', }, posts: { posts: {}, postsInChannel: [], }, preferences: { myPreferences: {}, }, users: { profiles: {}, }, }, } as unknown as GlobalState; const actual = Selectors.getLatestReplyablePostId(state); expect(actual).toEqual(''); }); it('return first post which dosent have POST_DELETED state', () => { const postsAny = { a: {id: 'a', channel_id: 'a', create_at: 1, highlight: false, user_id: 'a'}, b: {id: 'b', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', state: Posts.POST_DELETED}, c: {id: 'c', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: 'system_join_channel'}, d: {id: 'd', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: Posts.POST_TYPES.EPHEMERAL}, e: {id: 'e', channel_id: 'abcd', create_at: 4, highlight: false, user_id: 'b'}, }; const state = { entities: { channels: { currentChannelId: 'abcd', }, posts: { posts: postsAny, postsInChannel: { abcd: [ {order: ['b', 'c', 'd', 'e'], recent: true}, ], }, }, preferences: { myPreferences: {}, }, users: { profiles: {}, }, }, } as unknown as GlobalState; const actual = Selectors.getLatestReplyablePostId(state); expect(actual).toEqual(postsAny.e.id); }); }); describe('makeIsPostCommentMention', () => { const currentUser = { ...testState.entities.users.profiles[user1.id], notify_props: { comments: 'any', }, }; const modifiedState = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, profiles: { ...testState.entities.users.profiles, [user1.id]: currentUser, }, }, }, }; const isPostCommentMention = Selectors.makeIsPostCommentMention(); it('Should return true as root post is by the current user', () => { expect(isPostCommentMention(modifiedState, 'e')).toEqual(true); }); it('Should return false as post is not from currentUser', () => { expect(isPostCommentMention(modifiedState, 'b')).toEqual(false); }); it('Should return true as post is from webhook but user created rootPost', () => { const modifiedWbhookPostState = { ...modifiedState, entities: { ...modifiedState.entities, posts: { ...modifiedState.entities.posts, posts: { ...modifiedState.entities.posts.posts, e: { ...modifiedState.entities.posts.posts.e, props: { from_webhook: true, }, user_id: user1.id, }, }, }, }, }; expect(isPostCommentMention(modifiedWbhookPostState, 'e')).toEqual(true); }); it('Should return true as user commented in the thread', () => { const modifiedThreadState = { ...modifiedState, entities: { ...modifiedState.entities, posts: { ...modifiedState.entities.posts, posts: { ...modifiedState.entities.posts.posts, a: { ...modifiedState.entities.posts.posts.a, user_id: 'b', }, c: { ...modifiedState.entities.posts.posts.c, user_id: user1.id, }, }, }, }, }; expect(isPostCommentMention(modifiedThreadState, 'e')).toEqual(true); }); it('Should return false as user commented in the thread but notify_props is for root only', () => { const modifiedCurrentUserForNotifyProps = { ...testState.entities.users.profiles[user1.id], notify_props: { comments: 'root', }, }; const modifiedStateForRoot = { ...modifiedState, entities: { ...modifiedState.entities, posts: { ...modifiedState.entities.posts, posts: { ...modifiedState.entities.posts.posts, a: { ...modifiedState.entities.posts.posts.a, user_id: 'not current', }, c: { ...modifiedState.entities.posts.posts.c, user_id: user1.id, }, }, }, users: { ...modifiedState.entities.users, profiles: { ...modifiedState.entities.users.profiles, [user1.id]: modifiedCurrentUserForNotifyProps, }, }, }, }; expect(isPostCommentMention(modifiedStateForRoot, 'e')).toEqual(false); }); it('Should return false as user created root post', () => { const modifiedCurrentUserForNotifyProps = { ...testState.entities.users.profiles[user1.id], notify_props: { comments: 'root', }, }; const modifiedStateForRoot = { ...modifiedState, entities: { ...modifiedState.entities, users: { ...modifiedState.entities.users, profiles: { ...modifiedState.entities.users.profiles, [user1.id]: modifiedCurrentUserForNotifyProps, }, }, }, }; expect(isPostCommentMention(modifiedStateForRoot, 'e')).toEqual(true); }); }); }); describe('getPostIdsInCurrentChannel', () => { test('should return null when channel is not loaded', () => { const state = { entities: { channels: { currentChannelId: 'channel1', }, posts: { postsInChannel: {}, }, }, } as unknown as GlobalState; const postIds = Selectors.getPostIdsInCurrentChannel(state); expect(postIds).toBe(null); }); test('should return null when recent posts are not loaded', () => { const state = { entities: { channels: { currentChannelId: 'channel1', }, posts: { postsInChannel: { channel1: [ {order: ['post1', 'post2']}, ], }, }, }, } as unknown as GlobalState; const postIds = Selectors.getPostIdsInCurrentChannel(state); expect(postIds).toBe(null); }); test('should return post order from recent block', () => { const state = { entities: { channels: { currentChannelId: 'channel1', }, posts: { postsInChannel: { channel1: [ {order: ['post1', 'post2'], recent: true}, ], }, }, }, } as unknown as GlobalState; const postIds = Selectors.getPostIdsInCurrentChannel(state); expect(postIds).toBe(state.entities.posts.postsInChannel.channel1[0].order); }); }); describe('getPostsInCurrentChannel', () => { test('should return null when channel is not loaded', () => { const state = { entities: { channels: { currentChannelId: 'channel1', }, posts: { posts: {}, postsInChannel: {}, postsInThread: {}, }, preferences: { myPreferences: { [`${Preferences.CATEGORY_ADVANCED_SETTINGS}--${Preferences.ADVANCED_FILTER_JOIN_LEAVE}`]: {value: 'true'}, }, }, users: { profiles: {}, }, }, } as unknown as GlobalState; const postIds = Selectors.getPostsInCurrentChannel(state); expect(postIds).toEqual(null); }); test('should return null when recent posts are not loaded', () => { const post1 = {id: 'post1'}; const post2 = {id: 'post2'}; const state = { entities: { channels: { currentChannelId: 'channel1', }, posts: { posts: { post1, post2, }, postsInChannel: { channel1: [ {order: ['post1', 'post2']}, ], }, postsInThread: {}, }, preferences: { myPreferences: { [`${Preferences.CATEGORY_ADVANCED_SETTINGS}--${Preferences.ADVANCED_FILTER_JOIN_LEAVE}`]: {value: 'true'}, }, }, users: { profiles: {}, }, }, } as unknown as GlobalState; const postIds = Selectors.getPostsInCurrentChannel(state); expect(postIds).toEqual(null); }); test('should return post order from recent block', () => { const post1 = {id: 'post1'}; const post2 = {id: 'post2'}; const state = { entities: { channels: { currentChannelId: 'channel1', }, posts: { posts: { post1, post2, }, postsInChannel: { channel1: [ {order: ['post1', 'post2'], recent: true}, ], }, postsInThread: {}, }, preferences: { myPreferences: { [`${Preferences.CATEGORY_ADVANCED_SETTINGS}--${Preferences.ADVANCED_FILTER_JOIN_LEAVE}`]: {value: 'true'}, }, }, users: { profiles: {}, }, }, } as unknown as GlobalState; const postIds = Selectors.getPostsInCurrentChannel(state); expect(postIds).toMatchObject([post1, post2]); }); }); describe('getCurrentUsersLatestPost', () => { const user1 = TestHelper.fakeUserWithId(); const profiles: Record<string, UserProfile> = {}; profiles[user1.id] = user1; it('no posts', () => { const noPosts = {}; const state = { entities: { users: { currentUserId: user1.id, profiles, }, posts: { posts: noPosts, postsInChannel: [], }, preferences: { myPreferences: {}, }, channels: { currentChannelId: 'abcd', }, }, } as unknown as GlobalState; const actual = Selectors.getCurrentUsersLatestPost(state, ''); expect(actual).toEqual(null); }); it('return first post which user can edit', () => { const postsAny = { a: {id: 'a', channel_id: 'a', create_at: 1, highlight: false, user_id: 'a'}, b: {id: 'b', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', state: Posts.POST_DELETED}, c: {id: 'c', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: 'system_join_channel'}, d: {id: 'd', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: Posts.POST_TYPES.EPHEMERAL}, e: {id: 'e', channel_id: 'abcd', create_at: 4, highlight: false, user_id: 'c'}, f: {id: 'f', channel_id: 'abcd', create_at: 4, highlight: false, user_id: user1.id}, }; const state = { entities: { users: { currentUserId: user1.id, profiles, }, posts: { posts: postsAny, postsInChannel: { abcd: [ {order: ['b', 'c', 'd', 'e', 'f'], recent: true}, ], }, postsInThread: {}, }, preferences: { myPreferences: {}, }, channels: { currentChannelId: 'abcd', }, }, } as unknown as GlobalState; const actual = Selectors.getCurrentUsersLatestPost(state, ''); expect(actual).toMatchObject(postsAny.f); }); it('return first post which user can edit ignore pending and failed', () => { const postsAny = { a: {id: 'a', channel_id: 'a', create_at: 1, highlight: false, user_id: 'a'}, b: {id: 'b', channel_id: 'abcd', create_at: 4, highlight: false, user_id: user1.id, pending_post_id: 'b'}, c: {id: 'c', channel_id: 'abcd', create_at: 4, highlight: false, user_id: user1.id, failed: true}, d: {id: 'd', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: Posts.POST_TYPES.EPHEMERAL}, e: {id: 'e', channel_id: 'abcd', create_at: 4, highlight: false, user_id: 'c'}, f: {id: 'f', channel_id: 'abcd', create_at: 4, highlight: false, user_id: user1.id}, }; const state = { entities: { users: { currentUserId: user1.id, profiles, }, posts: { posts: postsAny, postsInChannel: { abcd: [ {order: ['b', 'c', 'd', 'e', 'f'], recent: true}, ], }, postsInThread: {}, }, preferences: { myPreferences: {}, }, channels: { currentChannelId: 'abcd', }, }, } as unknown as GlobalState; const actual = Selectors.getCurrentUsersLatestPost(state, ''); expect(actual).toMatchObject(postsAny.f); }); it('return first post which has rootId match', () => { const postsAny = { a: {id: 'a', channel_id: 'a', create_at: 1, highlight: false, user_id: 'a'}, b: {id: 'b', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', state: Posts.POST_DELETED}, c: {id: 'c', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: 'system_join_channel'}, d: {id: 'd', root_id: 'a', channel_id: 'abcd', create_at: 3, highlight: false, user_id: 'b', type: Posts.POST_TYPES.EPHEMERAL}, e: {id: 'e', channel_id: 'abcd', create_at: 4, highlight: false, user_id: 'c'}, f: {id: 'f', root_id: 'e', channel_id: 'abcd', create_at: 4, highlight: false, user_id: user1.id}, }; const state = { entities: { users: { currentUserId: user1.id, profiles, }, posts: { posts: postsAny, postsInChannel: { abcd: [ {order: ['b', 'c', 'd', 'e', 'f'], recent: true}, ], }, postsInThread: {}, }, preferences: { myPreferences: {}, }, channels: { currentChannelId: 'abcd', }, }, } as unknown as GlobalState; const actual = Selectors.getCurrentUsersLatestPost(state, 'e'); expect(actual).toMatchObject(postsAny.f); }); it('should not return posts outside of the recent block', () => { const postsAny = { a: {id: 'a', channel_id: 'a', create_at: 1, user_id: 'a'}, }; const state = { entities: { users: { currentUserId: user1.id, profiles, }, posts: { posts: postsAny, postsInChannel: { abcd: [ {order: ['a'], recent: false}, ], }, }, preferences: { myPreferences: {}, }, channels: { currentChannelId: 'abcd', }, }, } as unknown as GlobalState; const actual = Selectors.getCurrentUsersLatestPost(state, 'e'); expect(actual).toEqual(null); }); it('determine the sending posts', () => { const state = { entities: { users: { currentUserId: user1.id, profiles, }, posts: { posts: {}, postsInChannel: {}, pendingPostIds: ['1', '2', '3'], }, preferences: { myPreferences: {}, }, channels: { currentChannelId: 'abcd', }, }, } as unknown as GlobalState; expect(Selectors.isPostIdSending(state, '1')).toEqual(true); expect(Selectors.isPostIdSending(state, '2')).toEqual(true); expect(Selectors.isPostIdSending(state, '3')).toEqual(true); expect(Selectors.isPostIdSending(state, '4')).toEqual(false); expect(Selectors.isPostIdSending(state, '')).toEqual(false); }); }); describe('makeGetProfilesForThread', () => { it('should return profiles for threads in the right order and exclude current user', () => { const getProfilesForThread = Selectors.makeGetProfilesForThread(); const user1 = {id: 'user1', update_at: 1000}; const user2 = {id: 'user2', update_at: 1000}; const user3 = {id: 'user3', update_at: 1000}; const state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'true', }, }, posts: { posts: { 1001: {id: '1001', create_at: 1001, user_id: 'user1'}, 1002: {id: '1002', create_at: 1002, root_id: '1001', user_id: 'user2'}, 1003: {id: '1003', create_at: 1003}, 1004: {id: '1004', create_at: 1004, root_id: '1001', user_id: 'user3'}, 1005: {id: '1005', create_at: 1005}, }, postsInThread: { 1001: ['1002', '1004'], }, }, users: { profiles: { user1, user2, user3, }, currentUserId: 'user1', }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; expect(getProfilesForThread(state, '1001')).toEqual([user3, user2]); }); it('should return empty array if profiles data does not exist', () => { const getProfilesForThread = Selectors.makeGetProfilesForThread(); const user2 = {id: 'user2', update_at: 1000}; const state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'true', }, }, posts: { posts: { 1001: {id: '1001', create_at: 1001, user_id: 'user1'}, }, postsInThread: { 1001: [], }, }, users: { profiles: { user2, }, currentUserId: 'user2', }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; expect(getProfilesForThread(state, '1001')).toEqual([]); }); });
4,090
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/preferences.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {PreferencesType} from '@mattermost/types/preferences'; import type {GlobalState} from '@mattermost/types/store'; import {General, Preferences} from 'mattermost-redux/constants'; import * as Selectors from 'mattermost-redux/selectors/entities/preferences'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import * as ThemeUtils from 'mattermost-redux/utils/theme_utils'; import mergeObjects from '../../../test/merge_objects'; describe('Selectors.Preferences', () => { const category1 = 'testcategory1'; const category2 = 'testcategory2'; const directCategory = Preferences.CATEGORY_DIRECT_CHANNEL_SHOW; const groupCategory = Preferences.CATEGORY_GROUP_CHANNEL_SHOW; const name1 = 'testname1'; const value1 = 'true'; const pref1 = {category: category1, name: name1, value: value1, user_id: ''}; const name2 = 'testname2'; const value2 = '42'; const pref2 = {category: category2, name: name2, value: value2, user_id: ''}; const dm1 = 'teammate1'; const dmPref1 = {category: directCategory, name: dm1, value: 'true', user_id: ''}; const dm2 = 'teammate2'; const dmPref2 = {category: directCategory, name: dm2, value: 'false', user_id: ''}; const gp1 = 'group1'; const prefGp1 = {category: groupCategory, name: gp1, value: 'true', user_id: ''}; const gp2 = 'group2'; const prefGp2 = {category: groupCategory, name: gp2, value: 'false', user_id: ''}; const currentUserId = 'currentuserid'; const myPreferences: PreferencesType = {}; myPreferences[`${category1}--${name1}`] = pref1; myPreferences[`${category2}--${name2}`] = pref2; myPreferences[`${directCategory}--${dm1}`] = dmPref1; myPreferences[`${directCategory}--${dm2}`] = dmPref2; myPreferences[`${groupCategory}--${gp1}`] = prefGp1; myPreferences[`${groupCategory}--${gp2}`] = prefGp2; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId, }, preferences: { myPreferences, }, }, }); describe('get preference', () => { it('should return the requested value', () => { expect(Selectors.get(testState, category1, name1)).toEqual('true'); }); describe('should fallback to the default', () => { it('if name unknown', () => { expect(Selectors.get(testState, category1, 'unknown name')).toEqual(''); }); it('if category unknown', () => { expect(Selectors.get(testState, 'unknown category', name1)).toEqual(''); }); }); describe('should fallback to the overridden default', () => { it('if name unknown', () => { expect(Selectors.get(testState, category1, 'unknown name', 'fallback')).toEqual('fallback'); }); it('if category unknown', () => { expect(Selectors.get(testState, 'unknown category', name1, 'fallback')).toEqual('fallback'); }); }); }); describe('get bool preference', () => { it('should return the requested value', () => { expect(Selectors.getBool(testState, category1, name1)).toEqual(value1 === 'true'); }); describe('should fallback to the default', () => { it('if name unknown', () => { expect(Selectors.getBool(testState, category1, 'unknown name')).toEqual(false); }); it('if category unknown', () => { expect(Selectors.getBool(testState, 'unknown category', name1)).toEqual(false); }); }); describe('should fallback to the overridden default', () => { it('if name unknown', () => { expect(Selectors.getBool(testState, category1, 'unknown name', true)).toEqual(true); }); it('if category unknown', () => { expect(Selectors.getBool(testState, 'unknown category', name1, true)).toEqual(true); }); }); }); describe('get int preference', () => { it('should return the requested value', () => { expect(Selectors.getInt(testState, category2, name2)).toEqual(parseInt(value2, 10)); }); describe('should fallback to the default', () => { it('if name unknown', () => { expect(Selectors.getInt(testState, category2, 'unknown name')).toEqual(0); }); it('if category unknown', () => { expect(Selectors.getInt(testState, 'unknown category', name2)).toEqual(0); }); }); describe('should fallback to the overridden default', () => { it('if name unknown', () => { expect(Selectors.getInt(testState, category2, 'unknown name', 100)).toEqual(100); }); it('if category unknown', () => { expect(Selectors.getInt(testState, 'unknown category', name2, 100)).toEqual(100); }); }); }); it('get preferences by category', () => { const getCategory = Selectors.makeGetCategory(); expect(getCategory(testState, category1)).toEqual([pref1]); }); it('get direct channel show preferences', () => { expect(Selectors.getDirectShowPreferences(testState)).toEqual([dmPref1, dmPref2]); }); it('get group channel show preferences', () => { expect(Selectors.getGroupShowPreferences(testState)).toEqual([prefGp1, prefGp2]); }); it('get teammate name display setting', () => { expect( Selectors.getTeammateNameDisplaySetting({ entities: { general: { config: { TeammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_NICKNAME_FULLNAME, }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState)).toEqual( General.TEAMMATE_NAME_DISPLAY.SHOW_NICKNAME_FULLNAME, ); }); describe('get theme', () => { it('default theme', () => { const currentTeamId = '1234'; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { }, }, }, } as unknown as GlobalState)).toEqual(Preferences.THEMES.denim); }); it('custom theme', () => { const currentTeamId = '1234'; const theme = {sidebarBg: '#ff0000'}; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).sidebarBg).toEqual(theme.sidebarBg); }); it('team-specific theme', () => { const currentTeamId = '1234'; const otherTeamId = 'abcd'; const theme = {sidebarBg: '#ff0000'}; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify({}), }, [getPreferenceKey(Preferences.CATEGORY_THEME, currentTeamId)]: { category: Preferences.CATEGORY_THEME, name: currentTeamId, value: JSON.stringify(theme), }, [getPreferenceKey(Preferences.CATEGORY_THEME, otherTeamId)]: { category: Preferences.CATEGORY_THEME, name: otherTeamId, value: JSON.stringify({}), }, }, }, }, } as GlobalState).sidebarBg).toEqual(theme.sidebarBg); }); it('mentionBj backwards compatability theme', () => { const currentTeamId = '1234'; const theme: {mentionBj: string; mentionBg?: string} = {mentionBj: '#ff0000'}; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).mentionBg).toEqual(theme.mentionBj); theme.mentionBg = '#ff0001'; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).mentionBg).toEqual(theme.mentionBg); }); it('updates sideBarTeamBarBg variable when its not present', () => { const currentTeamId = '1234'; const theme = {sidebarHeaderBg: '#ff0000'}; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).sidebarTeamBarBg).toEqual(ThemeUtils.blendColors(theme.sidebarHeaderBg, '#000000', 0.2, true)); }); it('memoization', () => { const currentTeamId = '1234'; const otherTeamId = 'abcd'; let state = { entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify({}), }, [getPreferenceKey(Preferences.CATEGORY_THEME, currentTeamId)]: { category: Preferences.CATEGORY_THEME, name: currentTeamId, value: JSON.stringify({sidebarBg: '#ff0000'}), }, [getPreferenceKey(Preferences.CATEGORY_THEME, otherTeamId)]: { category: Preferences.CATEGORY_THEME, name: otherTeamId, value: JSON.stringify({}), }, }, }, }, } as GlobalState; const before = Selectors.getTheme(state); expect(before).toBe(Selectors.getTheme(state)); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, somethingUnrelated: { category: 'somethingUnrelated', name: '', value: JSON.stringify({}), user_id: '', }, }, }, }, }; expect(before).toBe(Selectors.getTheme(state)); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_THEME, currentTeamId)]: { category: Preferences.CATEGORY_THEME, name: currentTeamId, value: JSON.stringify({sidebarBg: '#0000ff'}), user_id: '', }, }, }, }, }; expect(before).not.toBe(Selectors.getTheme(state)); expect(before).not.toEqual(Selectors.getTheme(state)); }); it('custom theme with upper case colours', () => { const currentTeamId = '1234'; const theme = {sidebarBg: '#FF0000'}; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).sidebarBg).toEqual(theme.sidebarBg.toLowerCase()); }); it('custom theme with missing colours', () => { const currentTeamId = '1234'; const theme = {sidebarBg: '#ff0000'}; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).mentionHighlightLink).toEqual(Preferences.THEMES.denim.mentionHighlightLink); }); it('system theme with missing colours', () => { const currentTeamId = '1234'; const theme = { type: Preferences.THEMES.indigo.type, sidebarBg: '#ff0000', }; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).sidebarText).toEqual(Preferences.THEMES.indigo.sidebarText); }); it('non-default system theme', () => { const currentTeamId = '1234'; const theme = { type: Preferences.THEMES.onyx.type, }; expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState).codeTheme).toEqual(Preferences.THEMES.onyx.codeTheme); }); it('should return the server-configured theme by default', () => { expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'indigo', }, }, teams: { currentTeamId: null, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: null, }, }, }, } as unknown as GlobalState).codeTheme).toEqual(Preferences.THEMES.indigo.codeTheme); // Opposite case expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'onyx', }, }, teams: { currentTeamId: null, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: null, }, }, }, } as unknown as GlobalState).codeTheme).not.toEqual(Preferences.THEMES.indigo.codeTheme); }); it('returns the "default" theme if the server-configured value is not present', () => { expect(Selectors.getTheme({ entities: { general: { config: { DefaultTheme: 'fakedoesnotexist', }, }, teams: { currentTeamId: null, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: null, }, }, }, } as unknown as GlobalState).codeTheme).toEqual(Preferences.THEMES.denim.codeTheme); }); }); it('get theme from style', () => { const theme = {themeColor: '#ffffff'}; const currentTeamId = '1234'; const state = { entities: { general: { config: { DefaultTheme: 'default', }, }, teams: { currentTeamId, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_THEME, '')]: { category: Preferences.CATEGORY_THEME, name: '', value: JSON.stringify(theme), }, }, }, }, } as GlobalState; function testStyleFunction(myTheme: Selectors.Theme) { return { container: { backgroundColor: myTheme.themeColor, height: 100, }, }; } const expected = { container: { backgroundColor: theme.themeColor, height: 100, }, }; const getStyleFromTheme = Selectors.makeGetStyleFromTheme(); expect(getStyleFromTheme(state, testStyleFunction)).toEqual(expected); }); }); describe('shouldShowUnreadsCategory', () => { test('should return value from the preference if set', () => { const state = { entities: { general: { config: {}, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.SHOW_UNREAD_SECTION)]: {value: 'true'}, }, }, }, } as GlobalState; expect(Selectors.shouldShowUnreadsCategory(state)).toBe(true); }); test('should fall back properly from the new preference to the old one and then to the server default', () => { // With the new preference set let state = { entities: { general: { config: { ExperimentalGroupUnreadChannels: 'default_off', }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.SHOW_UNREAD_SECTION)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, '')]: {value: JSON.stringify({unreads_at_top: 'false'})}, }, }, }, } as GlobalState; expect(Selectors.shouldShowUnreadsCategory(state)).toBe(true); state = mergeObjects(state, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.SHOW_UNREAD_SECTION)]: {value: 'false'}, }, }, }, }); expect(Selectors.shouldShowUnreadsCategory(state)).toBe(false); // With only the old preference set state = { entities: { general: { config: { ExperimentalGroupUnreadChannels: 'default_off', }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, '')]: {value: JSON.stringify({unreads_at_top: 'true'})}, }, }, }, } as GlobalState; expect(Selectors.shouldShowUnreadsCategory(state)).toBe(true); state = mergeObjects(state, { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, '')]: {value: JSON.stringify({unreads_at_top: 'false'})}, }, }, }, }); expect(Selectors.shouldShowUnreadsCategory(state)).toBe(false); // Fall back from there to the server default state = { entities: { general: { config: { ExperimentalGroupUnreadChannels: 'default_on', }, }, preferences: { myPreferences: {}, }, }, } as GlobalState; expect(Selectors.shouldShowUnreadsCategory(state)).toBe(true); state = mergeObjects(state, { entities: { general: { config: { ExperimentalGroupUnreadChannels: 'default_off', }, }, }, }); expect(Selectors.shouldShowUnreadsCategory(state)).toBe(false); }); test('should not let admins fully disable the unread section', () => { // With the old sidebar, setting ExperimentalGroupUnreadChannels to disabled has an effect const state = { entities: { general: { config: { ExperimentalGroupUnreadChannels: 'disabled', }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.SHOW_UNREAD_SECTION)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, '')]: {value: JSON.stringify({unreads_at_top: 'true'})}, }, }, }, } as GlobalState; expect(Selectors.shouldShowUnreadsCategory(state)).toBe(true); }); });
4,093
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/roles.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel} from '@mattermost/types/channels'; import type {Group} from '@mattermost/types/groups'; import type {TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {General, Permissions} from 'mattermost-redux/constants'; import * as Selectors from 'mattermost-redux/selectors/entities/roles'; import {getMySystemPermissions, getMySystemRoles, getRoles} from 'mattermost-redux/selectors/entities/roles_helpers'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Roles', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const team3 = TestHelper.fakeTeamWithId(); const myTeamMembers: Record<string, TeamMembership> = {}; myTeamMembers[team1.id] = {roles: 'test_team1_role1 test_team1_role2'} as TeamMembership; myTeamMembers[team2.id] = {roles: 'test_team2_role1 test_team2_role2'} as TeamMembership; myTeamMembers[team3.id] = {} as TeamMembership; const channel1 = TestHelper.fakeChannelWithId(team1.id); channel1.display_name = 'Channel Name'; const channel2 = TestHelper.fakeChannelWithId(team1.id); channel2.display_name = 'DEF'; const channel3 = TestHelper.fakeChannelWithId(team2.id); const channel4 = TestHelper.fakeChannelWithId(''); channel4.display_name = 'Channel 4'; const channel5 = TestHelper.fakeChannelWithId(team1.id); channel5.type = General.PRIVATE_CHANNEL; channel5.display_name = 'Channel 5'; const channel6 = TestHelper.fakeChannelWithId(team1.id); const channel7 = TestHelper.fakeChannelWithId(''); channel7.display_name = ''; channel7.type = General.GM_CHANNEL; const channel8 = TestHelper.fakeChannelWithId(team1.id); channel8.display_name = 'ABC'; const channel9 = TestHelper.fakeChannelWithId(team1.id); const channel10 = TestHelper.fakeChannelWithId(team1.id); const channel11 = TestHelper.fakeChannelWithId(team1.id); channel11.type = General.PRIVATE_CHANNEL; const channel12 = TestHelper.fakeChannelWithId(team1.id); const channels: Record<string, Channel> = {}; channels[channel1.id] = channel1; channels[channel2.id] = channel2; channels[channel3.id] = channel3; channels[channel4.id] = channel4; channels[channel5.id] = channel5; channels[channel6.id] = channel6; channels[channel7.id] = channel7; channels[channel8.id] = channel8; channels[channel9.id] = channel9; channels[channel10.id] = channel10; channels[channel11.id] = channel11; channels[channel12.id] = channel12; const channelsInTeam: Record<string, Array<Channel['id']>> = {}; channelsInTeam[team1.id] = [channel1.id, channel2.id, channel5.id, channel6.id, channel8.id, channel10.id, channel11.id]; channelsInTeam[team2.id] = [channel3.id]; channelsInTeam[''] = [channel4.id, channel7.id, channel9.id]; const user = TestHelper.fakeUserWithId(); const profiles: Record<string, UserProfile> = {}; profiles[user.id] = user; profiles[user.id].roles = 'test_user_role test_user_role2'; const channelsRoles: Record<string, Set<string>> = {}; channelsRoles[channel1.id] = new Set(['test_channel_a_role1', 'test_channel_a_role2']); channelsRoles[channel2.id] = new Set(['test_channel_a_role1', 'test_channel_a_role2']); channelsRoles[channel3.id] = new Set(['test_channel_a_role1', 'test_channel_a_role2']); channelsRoles[channel4.id] = new Set(['test_channel_a_role1', 'test_channel_a_role2']); channelsRoles[channel5.id] = new Set(['test_channel_a_role1', 'test_channel_a_role2']); channelsRoles[channel7.id] = new Set(['test_channel_b_role1', 'test_channel_b_role2']); channelsRoles[channel8.id] = new Set(['test_channel_b_role1', 'test_channel_b_role2']); channelsRoles[channel9.id] = new Set(['test_channel_b_role1', 'test_channel_b_role2']); channelsRoles[channel10.id] = new Set(['test_channel_c_role1', 'test_channel_c_role2']); channelsRoles[channel11.id] = new Set(['test_channel_c_role1', 'test_channel_c_role2']); const roles = { test_team1_role1: {permissions: ['team1_role1']}, test_team2_role1: {permissions: ['team2_role1']}, test_team2_role2: {permissions: ['team2_role2']}, test_channel_a_role1: {permissions: ['channel_a_role1']}, test_channel_a_role2: {permissions: ['channel_a_role2']}, test_channel_b_role2: {permissions: ['channel_b_role2']}, test_channel_c_role1: {permissions: ['channel_c_role1']}, test_channel_c_role2: {permissions: ['channel_c_role2']}, test_user_role2: {permissions: ['user_role2', Permissions.EDIT_CUSTOM_GROUP, Permissions.CREATE_CUSTOM_GROUP, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS, Permissions.DELETE_CUSTOM_GROUP, Permissions.RESTORE_CUSTOM_GROUP]}, custom_group_user: {permissions: ['custom_group_user']}, }; const group1 = TestHelper.fakeGroup('group1', 'custom'); const group2 = TestHelper.fakeGroup('group2', 'custom'); const group3 = TestHelper.fakeGroup('group3', 'custom'); const group4 = TestHelper.fakeGroup('group4', 'custom'); const group5 = TestHelper.fakeGroup('group5'); const group6 = TestHelper.fakeGroup('group6', 'custom'); group6.delete_at = 10000; const groups: Record<string, Group> = {}; groups.group1 = group1; groups.group2 = group2; groups.group3 = group3; groups.group4 = group4; groups.group5 = group5; groups.group6 = group6; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, myMembers: myTeamMembers, }, channels: { currentChannelId: channel1.id, channels, roles: channelsRoles, }, groups: { groups, myGroups: ['group1'], }, roles: { roles, }, }, }); it('should return my roles by scope on getMySystemRoles/getMyTeamRoles/getMyChannelRoles/getMyGroupRoles', () => { const teamsRoles: Record<string, Set<string>> = {}; teamsRoles[team1.id] = new Set(['test_team1_role1', 'test_team1_role2']); teamsRoles[team2.id] = new Set(['test_team2_role1', 'test_team2_role2']); const groupRoles: Record<string, Set<string>> = {}; groupRoles[group1.id] = new Set(['custom_group_user']); const myRoles = { system: new Set(['test_user_role', 'test_user_role2']), team: teamsRoles, channel: channelsRoles, }; expect(getMySystemRoles(testState)).toEqual(myRoles.system); expect(Selectors.getMyTeamRoles(testState)).toEqual(myRoles.team); expect(Selectors.getMyChannelRoles(testState)).toEqual(myRoles.channel); expect(Selectors.getMyGroupRoles(testState)).toEqual(groupRoles); }); it('should return current loaded roles on getRoles', () => { const loadedRoles = { test_team1_role1: {permissions: ['team1_role1']}, test_team2_role1: {permissions: ['team2_role1']}, test_team2_role2: {permissions: ['team2_role2']}, test_channel_a_role1: {permissions: ['channel_a_role1']}, test_channel_a_role2: {permissions: ['channel_a_role2']}, test_channel_b_role2: {permissions: ['channel_b_role2']}, test_channel_c_role1: {permissions: ['channel_c_role1']}, test_channel_c_role2: {permissions: ['channel_c_role2']}, test_user_role2: {permissions: ['user_role2', Permissions.EDIT_CUSTOM_GROUP, Permissions.CREATE_CUSTOM_GROUP, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS, Permissions.DELETE_CUSTOM_GROUP, Permissions.RESTORE_CUSTOM_GROUP]}, custom_group_user: {permissions: ['custom_group_user']}, }; expect(getRoles(testState)).toEqual(loadedRoles); }); it('should return my system permission on getMySystemPermissions', () => { expect(getMySystemPermissions(testState)).toEqual(new Set([ 'user_role2', Permissions.EDIT_CUSTOM_GROUP, Permissions.CREATE_CUSTOM_GROUP, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS, Permissions.DELETE_CUSTOM_GROUP, Permissions.RESTORE_CUSTOM_GROUP, ])); }); it('should return if i have a system permission on haveISystemPermission', () => { expect(Selectors.haveISystemPermission(testState, {permission: 'user_role2'})).toEqual(true); expect(Selectors.haveISystemPermission(testState, {permission: 'invalid_permission'})).toEqual(false); }); it('should return if i have a team permission on haveITeamPermission', () => { expect(Selectors.haveITeamPermission(testState, team1.id, 'user_role2')).toEqual(true); expect(Selectors.haveITeamPermission(testState, team1.id, 'team1_role1')).toEqual(true); expect(Selectors.haveITeamPermission(testState, team1.id, 'team2_role2')).toEqual(false); expect(Selectors.haveITeamPermission(testState, team1.id, 'invalid_permission')).toEqual(false); }); it('should return if i have a team permission on haveICurrentTeamPermission', () => { expect(Selectors.haveICurrentTeamPermission(testState, 'user_role2')).toEqual(true); expect(Selectors.haveICurrentTeamPermission(testState, 'team1_role1')).toEqual(true); expect(Selectors.haveICurrentTeamPermission(testState, 'team2_role2')).toEqual(false); expect(Selectors.haveICurrentTeamPermission(testState, 'invalid_permission')).toEqual(false); }); it('should return if i have a channel permission on haveIChannelPermission', () => { expect(Selectors.haveIChannelPermission(testState, team1.id, channel1.id, 'user_role2')).toEqual(true); expect(Selectors.haveIChannelPermission(testState, team1.id, channel1.id, 'team1_role1')).toEqual(true); expect(Selectors.haveIChannelPermission(testState, team1.id, channel1.id, 'team2_role2')).toEqual(false); expect(Selectors.haveIChannelPermission(testState, team1.id, channel1.id, 'channel_a_role1')).toEqual(true); expect(Selectors.haveIChannelPermission(testState, team1.id, channel1.id, 'channel_b_role1')).toEqual(false); }); it('should return if i have a channel permission on haveICurrentChannelPermission', () => { expect(Selectors.haveICurrentChannelPermission(testState, 'user_role2')).toEqual(true); expect(Selectors.haveICurrentChannelPermission(testState, 'team1_role1')).toEqual(true); expect(Selectors.haveICurrentChannelPermission(testState, 'team2_role2')).toEqual(false); expect(Selectors.haveICurrentChannelPermission(testState, 'channel_a_role1')).toEqual(true); expect(Selectors.haveICurrentChannelPermission(testState, 'channel_b_role1')).toEqual(false); }); it('should return group memberships on getGroupMemberships', () => { expect(Selectors.getGroupMemberships(testState)).toEqual({[group1.id]: {user_id: user.id, roles: 'custom_group_user'}}); }); it('should return if i have a group permission on haveIGroupPermission', () => { expect(Selectors.haveIGroupPermission(testState, group1.id, Permissions.EDIT_CUSTOM_GROUP)).toEqual(true); expect(Selectors.haveIGroupPermission(testState, group1.id, Permissions.CREATE_CUSTOM_GROUP)).toEqual(true); expect(Selectors.haveIGroupPermission(testState, group1.id, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS)).toEqual(true); expect(Selectors.haveIGroupPermission(testState, group1.id, Permissions.DELETE_CUSTOM_GROUP)).toEqual(true); // You don't have to be a member to perform these actions expect(Selectors.haveIGroupPermission(testState, group2.id, Permissions.EDIT_CUSTOM_GROUP)).toEqual(true); expect(Selectors.haveIGroupPermission(testState, group2.id, Permissions.CREATE_CUSTOM_GROUP)).toEqual(true); expect(Selectors.haveIGroupPermission(testState, group2.id, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS)).toEqual(true); expect(Selectors.haveIGroupPermission(testState, group2.id, Permissions.DELETE_CUSTOM_GROUP)).toEqual(true); }); it('should return false if i dont have a group permission on haveIGroupPermission', () => { const roles = { test_team1_role1: {permissions: ['team1_role1']}, test_team2_role1: {permissions: ['team2_role1']}, test_team2_role2: {permissions: ['team2_role2']}, test_channel_a_role1: {permissions: ['channel_a_role1']}, test_channel_a_role2: {permissions: ['channel_a_role2']}, test_channel_b_role2: {permissions: ['channel_b_role2']}, test_channel_c_role1: {permissions: ['channel_c_role1']}, test_channel_c_role2: {permissions: ['channel_c_role2']}, test_user_role2: {permissions: ['user_role2', Permissions.CREATE_CUSTOM_GROUP, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS, Permissions.DELETE_CUSTOM_GROUP]}, custom_group_user: {permissions: ['custom_group_user']}, }; const newState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, myMembers: myTeamMembers, }, channels: { currentChannelId: channel1.id, channels, roles: channelsRoles, }, groups: { groups, myGroups: ['group1'], }, roles: { roles, }, }, }); expect(Selectors.haveIGroupPermission(newState, group2.id, Permissions.EDIT_CUSTOM_GROUP)).toEqual(false); expect(Selectors.haveIGroupPermission(newState, group2.id, Permissions.CREATE_CUSTOM_GROUP)).toEqual(true); expect(Selectors.haveIGroupPermission(newState, group2.id, Permissions.MANAGE_CUSTOM_GROUP_MEMBERS)).toEqual(true); expect(Selectors.haveIGroupPermission(newState, group2.id, Permissions.DELETE_CUSTOM_GROUP)).toEqual(true); expect(Selectors.haveIGroupPermission(newState, group2.id, Permissions.RESTORE_CUSTOM_GROUP)).toEqual(false); }); it('should return group set with permissions on getGroupListPermissions', () => { expect(Selectors.getGroupListPermissions(testState)).toEqual({ [group1.id]: {can_delete: true, can_manage_members: true, can_restore: false}, [group2.id]: {can_delete: true, can_manage_members: true, can_restore: false}, [group3.id]: {can_delete: true, can_manage_members: true, can_restore: false}, [group4.id]: {can_delete: true, can_manage_members: true, can_restore: false}, [group5.id]: {can_delete: false, can_manage_members: false, can_restore: false}, [group6.id]: {can_delete: false, can_manage_members: false, can_restore: true}, }); }); });
4,096
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/schemes.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel} from '@mattermost/types/channels'; import type {Scheme} from '@mattermost/types/schemes'; import type {Team} from '@mattermost/types/teams'; import {ScopeTypes} from 'mattermost-redux/constants/schemes'; import * as Selectors from 'mattermost-redux/selectors/entities/schemes'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Schemes', () => { const scheme1 = TestHelper.mockSchemeWithId(); scheme1.scope = ScopeTypes.CHANNEL as 'channel'; const scheme2 = TestHelper.mockSchemeWithId(); scheme2.scope = ScopeTypes.TEAM as 'team'; const schemes: Record<string, Scheme> = {}; schemes[scheme1.id] = scheme1; schemes[scheme2.id] = scheme2; const channel1 = TestHelper.fakeChannelWithId(''); channel1.scheme_id = scheme1.id; const channel2 = TestHelper.fakeChannelWithId(''); const channels: Record<string, Channel> = {}; channels[channel1.id] = channel1; channels[channel2.id] = channel2; const team1 = TestHelper.fakeTeamWithId(); team1.scheme_id = scheme2.id; const team2 = TestHelper.fakeTeamWithId(); const teams: Record<string, Team> = {}; teams[team1.id] = team1; teams[team2.id] = team2; const testState = deepFreezeAndThrowOnMutation({ entities: { schemes: {schemes}, channels: {channels}, teams: {teams}, }, }); it('getSchemes', () => { expect(Selectors.getSchemes(testState)).toEqual(schemes); }); it('getScheme', () => { expect(Selectors.getScheme(testState, scheme1.id)).toEqual(scheme1); }); it('makeGetSchemeChannels', () => { const getSchemeChannels = Selectors.makeGetSchemeChannels(); const results = getSchemeChannels(testState, {schemeId: scheme1.id}); expect(results.length).toEqual(1); expect(results[0].name).toEqual(channel1.name); }); it('makeGetSchemeChannels with team scope scheme', () => { const getSchemeChannels = Selectors.makeGetSchemeChannels(); const results = getSchemeChannels(testState, {schemeId: scheme2.id}); expect(results.length).toEqual(0); }); it('makeGetSchemeTeams', () => { const getSchemeTeams = Selectors.makeGetSchemeTeams(); const results = getSchemeTeams(testState, {schemeId: scheme2.id}); expect(results.length).toEqual(1); expect(results[0].name).toEqual(team1.name); }); it('getSchemeTeams with channel scope scheme', () => { const getSchemeTeams = Selectors.makeGetSchemeTeams(); const results = getSchemeTeams(testState, {schemeId: scheme1.id}); expect(results.length).toEqual(0); }); });
4,098
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/search.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GlobalState} from '@mattermost/types/store'; import * as Selectors from 'mattermost-redux/selectors/entities/search'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Search', () => { const team1 = TestHelper.fakeTeamWithId(); const team1CurrentSearch = {params: {page: 0, per_page: 20}, isEnd: true}; const testState = deepFreezeAndThrowOnMutation({ entities: { teams: { currentTeamId: team1.id, }, search: { current: {[team1.id]: team1CurrentSearch}, }, }, }); it('should return current search for current team', () => { expect(Selectors.getCurrentSearchForCurrentTeam(testState)).toEqual(team1CurrentSearch); }); it('groups', () => { const userId = '1234'; const notifyProps = { first_name: 'true', }; const state = { entities: { users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last', notify_props: notifyProps}, }, }, groups: { groups: { test1: { name: 'I-AM-THE-BEST!', display_name: 'I-AM-THE-BEST!', delete_at: 0, allow_reference: true, }, test2: { name: 'Do-you-love-me?', display_name: 'Do-you-love-me?', delete_at: 0, allow_reference: true, }, test3: { name: 'Maybe?-A-little-bit-I-guess....', display_name: 'Maybe?-A-little-bit-I-guess....', delete_at: 0, allow_reference: false, }, }, myGroups: [ 'test1', 'test2', 'test3', ], }, }, } as unknown as GlobalState; expect(Selectors.getAllUserMentionKeys(state)).toEqual([{key: 'First', caseSensitive: true}, {key: '@user'}, {key: '@Do-you-love-me?'}, {key: '@I-AM-THE-BEST!'}]); }); });
4,100
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/teams.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GlobalState} from '@mattermost/types/store'; import type {Team, TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {General} from 'mattermost-redux/constants'; import * as Selectors from 'mattermost-redux/selectors/entities/teams'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Teams', () => { TestHelper.initMockEntities(); const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const team3 = TestHelper.fakeTeamWithId(); const team4 = TestHelper.fakeTeamWithId(); const team5 = TestHelper.fakeTeamWithId(); const teams: Record<string, Team> = {}; teams[team1.id] = team1; teams[team2.id] = team2; teams[team3.id] = team3; teams[team4.id] = team4; teams[team5.id] = team5; team1.display_name = 'Marketeam'; team1.name = 'marketing_team'; team2.display_name = 'Core Team'; team3.allow_open_invite = true; team4.allow_open_invite = true; team3.display_name = 'Team AA'; team4.display_name = 'aa-team'; team5.delete_at = 10; team5.allow_open_invite = true; const user = TestHelper.fakeUserWithId(); const user2 = TestHelper.fakeUserWithId(); const user3 = TestHelper.fakeUserWithId(); const profiles: Record<string, UserProfile> = {}; profiles[user.id] = user; profiles[user2.id] = user2; profiles[user3.id] = user3; const myMembers: Record<string, TeamMembership> = {}; myMembers[team1.id] = {team_id: team1.id, user_id: user.id, roles: General.TEAM_USER_ROLE, mention_count: 1} as TeamMembership; myMembers[team2.id] = {team_id: team2.id, user_id: user.id, roles: General.TEAM_USER_ROLE, mention_count: 3} as TeamMembership; myMembers[team5.id] = {team_id: team5.id, user_id: user.id, roles: General.TEAM_USER_ROLE, mention_count: 0} as TeamMembership; const membersInTeam: Record<string, Record<string, TeamMembership>> = {}; membersInTeam[team1.id] = {} as Record<string, TeamMembership>; membersInTeam[team1.id][user2.id] = {team_id: team1.id, user_id: user2.id, roles: General.TEAM_USER_ROLE} as TeamMembership; membersInTeam[team1.id][user3.id] = {team_id: team1.id, user_id: user3.id, roles: General.TEAM_USER_ROLE} as TeamMembership; const testState = deepFreezeAndThrowOnMutation({ entities: { preferences: { myPreferences: {}, }, users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, teams, myMembers, membersInTeam, }, roles: { roles: TestHelper.basicRoles, }, general: { serverVersion: '5.8.0', }, }, }); it('getTeamsList', () => { expect(Selectors.getTeamsList(testState)).toEqual([team1, team2, team3, team4, team5]); }); it('getMyTeams', () => { expect(Selectors.getMyTeams(testState)).toEqual([team1, team2]); }); it('getMembersInCurrentTeam', () => { expect(Selectors.getMembersInCurrentTeam(testState)).toEqual(membersInTeam[team1.id]); }); it('getTeamMember', () => { expect(Selectors.getTeamMember(testState, team1.id, user2.id)).toEqual(membersInTeam[team1.id][user2.id]); }); it('getJoinableTeams', () => { const openTeams = [team3, team4]; const joinableTeams = Selectors.getJoinableTeams(testState); expect(joinableTeams[0]).toBe(openTeams[0]); expect(joinableTeams[1]).toBe(openTeams[1]); }); it('getSortedJoinableTeams', () => { const openTeams = [team4, team3]; const joinableTeams = Selectors.getSortedJoinableTeams(testState, 'en'); expect(joinableTeams[0]).toBe(openTeams[0]); expect(joinableTeams[1]).toBe(openTeams[1]); }); it('getListableTeams', () => { const openTeams = [team3, team4]; const listableTeams = Selectors.getListableTeams(testState); expect(listableTeams[0]).toBe(openTeams[0]); expect(listableTeams[1]).toBe(openTeams[1]); }); it('getListedJoinableTeams', () => { const openTeams = [team4, team3]; const joinableTeams = Selectors.getSortedListableTeams(testState, 'en'); expect(joinableTeams[0]).toBe(openTeams[0]); expect(joinableTeams[1]).toBe(openTeams[1]); }); it('getJoinableTeamsUsingPermissions', () => { const privateTeams = [team1, team2]; const openTeams = [team3, team4]; let modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { ...testState.entities.roles.roles.system_user, permissions: ['join_private_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; let joinableTeams = Selectors.getJoinableTeams(modifiedState); expect(joinableTeams[0]).toBe(privateTeams[0]); expect(joinableTeams[1]).toBe(privateTeams[1]); modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { permissions: ['join_public_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; joinableTeams = Selectors.getJoinableTeams(modifiedState); expect(joinableTeams[0]).toBe(openTeams[0]); expect(joinableTeams[1]).toBe(openTeams[1]); modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { permissions: ['join_public_teams', 'join_private_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; joinableTeams = Selectors.getJoinableTeams(modifiedState); expect(joinableTeams[0]).toBe(privateTeams[0]); expect(joinableTeams[1]).toBe(privateTeams[1]); expect(joinableTeams[2]).toBe(openTeams[0]); expect(joinableTeams[3]).toBe(openTeams[1]); }); it('getSortedJoinableTeamsUsingPermissions', () => { const privateTeams = [team2, team1]; const openTeams = [team4, team3]; const modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { ...testState.entities.roles.roles.system_user, permissions: ['join_public_teams', 'join_private_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; const joinableTeams = Selectors.getSortedJoinableTeams(modifiedState, 'en'); expect(joinableTeams[0]).toBe(openTeams[0]); expect(joinableTeams[1]).toBe(privateTeams[0]); expect(joinableTeams[2]).toBe(privateTeams[1]); expect(joinableTeams[3]).toBe(openTeams[1]); }); it('getListableTeamsUsingPermissions', () => { const privateTeams = [team1, team2]; const openTeams = [team3, team4]; let modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { ...testState.entities.roles.roles.system_user, permissions: ['list_private_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; let listableTeams = Selectors.getListableTeams(modifiedState); expect(listableTeams[0]).toBe(privateTeams[0]); expect(listableTeams[1]).toBe(privateTeams[1]); modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { permissions: ['list_public_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; listableTeams = Selectors.getListableTeams(modifiedState); expect(listableTeams[0]).toBe(openTeams[0]); expect(listableTeams[1]).toBe(openTeams[1]); modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { permissions: ['list_public_teams', 'list_private_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; listableTeams = Selectors.getListableTeams(modifiedState); expect(listableTeams[0]).toBe(privateTeams[0]); expect(listableTeams[1]).toBe(privateTeams[1]); expect(listableTeams[2]).toBe(openTeams[0]); expect(listableTeams[3]).toBe(openTeams[1]); }); it('getSortedListableTeamsUsingPermissions', () => { const privateTeams = [team2, team1]; const openTeams = [team4, team3]; const modifiedState = { entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: {}, }, roles: { roles: { system_user: { ...testState.entities.roles.roles.system_user, permissions: ['list_public_teams', 'list_private_teams'], }, }, }, general: { serverVersion: '5.10.0', }, }, } as GlobalState; const listableTeams = Selectors.getSortedListableTeams(modifiedState, 'en'); expect(listableTeams[0]).toBe(openTeams[0]); expect(listableTeams[1]).toBe(privateTeams[0]); expect(listableTeams[2]).toBe(privateTeams[1]); expect(listableTeams[3]).toBe(openTeams[1]); }); it('isCurrentUserCurrentTeamAdmin', () => { expect(Selectors.isCurrentUserCurrentTeamAdmin(testState)).toEqual(false); }); it('getMyTeamMember', () => { expect(Selectors.getMyTeamMember(testState, team1.id)).toEqual(myMembers[team1.id]); }); it('getTeam', () => { const modifiedState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, teams: { ...testState.entities.teams.teams, [team3.id]: { ...team3, allow_open_invite: false, }, }, }, }, }; const fromOriginalState = Selectors.getTeam(testState, team1.id); const fromModifiedState = Selectors.getTeam(modifiedState, team1.id); expect(fromOriginalState).toEqual(fromModifiedState); }); it('getJoinableTeamIds', () => { const modifiedState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, teams: { ...testState.entities.teams.teams, [team3.id]: { ...team3, display_name: 'Welcome', }, }, }, }, }; const fromOriginalState = Selectors.getJoinableTeamIds(testState); const fromModifiedState = Selectors.getJoinableTeamIds(modifiedState); expect(fromOriginalState).toEqual(fromModifiedState); }); it('getMySortedTeamIds', () => { const modifiedState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, teams: { ...testState.entities.teams.teams, [team3.id]: { ...team3, display_name: 'Welcome', }, }, }, }, }; const updateState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, teams: { ...testState.entities.teams.teams, [team2.id]: { ...team2, display_name: 'Yankz', }, }, }, }, }; const fromOriginalState = Selectors.getMySortedTeamIds(testState, 'en'); const fromModifiedState = Selectors.getMySortedTeamIds(modifiedState, 'en'); const fromUpdateState = Selectors.getMySortedTeamIds(updateState, 'en'); expect(fromOriginalState).toEqual(fromModifiedState); expect(fromModifiedState[0]).toEqual(team2.id); expect(fromModifiedState).not.toEqual(fromUpdateState); expect(fromUpdateState[0]).toEqual(team1.id); }); it('getMyTeamsCount', () => { const modifiedState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, teams: { ...testState.entities.teams.teams, [team3.id]: { ...team3, display_name: 'Welcome', }, }, }, }, }; const updateState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, myMembers: { ...testState.entities.teams.myMembers, [team3.id]: {team_id: team3.id, user_id: user.id, roles: General.TEAM_USER_ROLE}, }, }, }, }; const fromOriginalState = Selectors.getMyTeamsCount(testState); const fromModifiedState = Selectors.getMyTeamsCount(modifiedState); const fromUpdateState = Selectors.getMyTeamsCount(updateState); expect(fromOriginalState).toEqual(fromModifiedState); expect(fromModifiedState).toEqual(2); expect(fromModifiedState).not.toEqual(fromUpdateState); expect(fromUpdateState).toEqual(3); }); it('getChannelDrawerBadgeCount', () => { const mentions = Selectors.getChannelDrawerBadgeCount(testState); expect(mentions).toEqual(3); }); it('getTeamMentions', () => { const factory1 = Selectors.makeGetBadgeCountForTeamId(); const factory2 = Selectors.makeGetBadgeCountForTeamId(); const factory3 = Selectors.makeGetBadgeCountForTeamId(); const mentions1 = factory1(testState, team1.id); expect(mentions1).toEqual(1); const mentions2 = factory2(testState, team2.id); expect(mentions2).toEqual(3); // Not a member of the team const mentions3 = factory3(testState, team3.id); expect(mentions3).toEqual(0); }); it('getCurrentRelativeTeamUrl', () => { expect(Selectors.getCurrentRelativeTeamUrl(testState)).toEqual('/' + team1.name); expect(Selectors.getCurrentRelativeTeamUrl({entities: {teams: {teams: {}}}} as GlobalState)).toEqual('/'); }); it('getCurrentTeamUrl', () => { const siteURL = 'http://localhost:8065'; const general = { config: {SiteURL: siteURL}, credentials: {}, }; const withSiteURLState = { ...testState, entities: { ...testState.entities, general, }, }; withSiteURLState.entities.general = general; expect(Selectors.getCurrentTeamUrl(withSiteURLState)).toEqual(siteURL + '/' + team1.name); const credentialURL = 'http://localhost:8065'; const withCredentialURLState = { ...withSiteURLState, entities: { ...withSiteURLState.entities, general: { ...withSiteURLState.entities.general, credentials: {url: credentialURL}, }, }, }; expect(Selectors.getCurrentTeamUrl(withCredentialURLState)).toEqual(credentialURL + '/' + team1.name); }); it('getCurrentTeamUrl with falsy currentTeam', () => { const siteURL = 'http://localhost:8065'; const general = { config: {SiteURL: siteURL}, credentials: {}, }; const falsyCurrentTeamIds = ['', null, undefined]; falsyCurrentTeamIds.forEach((falsyCurrentTeamId) => { const withSiteURLState = { ...testState, entities: { ...testState.entities, teams: { ...testState.entities.teams, currentTeamId: falsyCurrentTeamId, }, general, }, }; withSiteURLState.entities.general = general; expect(Selectors.getCurrentTeamUrl(withSiteURLState)).toEqual(siteURL); const credentialURL = 'http://localhost:8065'; const withCredentialURLState = { ...withSiteURLState, entities: { ...withSiteURLState.entities, general: { ...withSiteURLState.entities.general, credentials: {url: credentialURL}, }, }, }; expect(Selectors.getCurrentTeamUrl(withCredentialURLState)).toEqual(credentialURL); }); }); });
4,102
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/threads.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import * as Selectors from './threads'; import TestHelper from '../../../test/test_helper'; describe('Selectors.Threads.getThreadOrderInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const post1 = TestHelper.fakePostWithId(''); const post2 = TestHelper.fakePostWithId(''); it('should return threads order in current team based on last reply time', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const testState = deepFreezeAndThrowOnMutation({ entities: { general: { config: { }, }, preferences: { myPreferences: { }, }, users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, threads: { threads: { a: {last_reply_at: 1, is_following: true, post: post1}, b: {last_reply_at: 2, is_following: true, post: post2}, }, threadsInTeam: { [team1.id]: ['a', 'b'], [team2.id]: ['c', 'd'], }, }, channels: { channelsInTeam: { [team1.id]: [post1.channel_id, post2.channel_id], }, channels: { [post1.channel_id]: { id: post1.channel_id, name: 'channel-1', display_name: 'channel 1', }, [post2.channel_id]: { id: post2.channel_id, name: 'channel-2', display_name: 'channel 2', }, }, myMembers: { [post1.channel_id]: [user.id], [post2.channel_id]: [user.id], }, }, }, }); expect(Selectors.getThreadOrderInCurrentTeam(testState)).toEqual(['b', 'a']); }); }); describe('Selectors.Threads.getUnreadThreadOrderInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const post1 = TestHelper.fakePostWithId(''); const post2 = TestHelper.fakePostWithId(''); it('should return unread threads order in current team based on last reply time', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const testState = deepFreezeAndThrowOnMutation({ entities: { general: { config: {}, }, preferences: { myPreferences: {}, }, users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, threads: { threads: { a: {last_reply_at: 1, is_following: true, unread_replies: 1, post: post1}, b: {last_reply_at: 2, is_following: true, unread_replies: 1, post: post2}, }, threadsInTeam: {}, unreadThreadsInTeam: { [team1.id]: ['a', 'b'], [team2.id]: ['c', 'd'], }, }, channels: { channelsInTeam: { [team1.id]: [post1.channel_id, post2.channel_id], }, channels: { [post1.channel_id]: { id: post1.channel_id, name: 'channel-1', display_name: 'channel 1', }, [post2.channel_id]: { id: post2.channel_id, name: 'channel-2', display_name: 'channel 2', }, }, myMembers: { [post1.channel_id]: [user.id], [post2.channel_id]: [user.id], }, }, }, }); expect(Selectors.getThreadOrderInCurrentTeam(testState)).toEqual([]); expect(Selectors.getUnreadThreadOrderInCurrentTeam(testState)).toEqual(['b', 'a']); }); }); describe('Selectors.Threads.getThreadsInCurrentTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); it('should return threads in current team', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, threads: { threads: { a: {}, b: {}, }, threadsInTeam: { [team1.id]: ['a', 'b'], [team2.id]: ['c', 'd'], }, }, }, }); expect(Selectors.getThreadsInCurrentTeam(testState)).toEqual(['a', 'b']); }); }); describe('Selectors.Threads.getThreadsInChannel', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(''); const channel2 = TestHelper.fakeChannelWithId(''); const channel3 = TestHelper.fakeChannelWithId(''); it('should return threads in channel', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, threads: { threads: { a: { post: { channel_id: channel1.id, }, }, b: { post: { channel_id: channel1.id, }, }, c: { post: { channel_id: channel2.id, }, }, d: { post: { channel_id: channel3.id, }, }, }, threadsInTeam: { [team1.id]: ['a', 'b', 'c'], [team2.id]: ['d'], }, }, }, }); expect(Selectors.getThreadsInChannel(testState, channel1.id)).toEqual(['a', 'b']); }); }); describe('Selectors.Threads.getNewestThreadInTeam', () => { const team1 = TestHelper.fakeTeamWithId(); const team2 = TestHelper.fakeTeamWithId(); it('should return newest thread in team', () => { const user = TestHelper.fakeUserWithId(); const threadB = {last_reply_at: 2, is_following: true}; const profiles = { [user.id]: user, }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user.id, profiles, }, teams: { currentTeamId: team1.id, }, threads: { threads: { a: {last_reply_at: 1, is_following: true}, b: threadB, }, threadsInTeam: { [team1.id]: ['a', 'b'], [team2.id]: ['c', 'd'], }, }, }, }); expect(Selectors.getNewestThreadInTeam(testState, team1.id)).toEqual(threadB); }); });
4,107
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/users.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel, ChannelMembership} from '@mattermost/types/channels'; import type {Group} from '@mattermost/types/groups'; import type {PreferencesType} from '@mattermost/types/preferences'; import type {GlobalState} from '@mattermost/types/store'; import type {Team, TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {General, Preferences} from 'mattermost-redux/constants'; import * as Selectors from 'mattermost-redux/selectors/entities/users'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import {sortByUsername} from 'mattermost-redux/utils/user_utils'; import TestHelper from '../../../test/test_helper'; const searchProfilesMatchingWithTerm = Selectors.makeSearchProfilesMatchingWithTerm(); const searchProfilesStartingWithTerm = Selectors.makeSearchProfilesStartingWithTerm(); describe('Selectors.Users', () => { const team1 = TestHelper.fakeTeamWithId(); const channel1 = TestHelper.fakeChannelWithId(team1.id); const channel2 = TestHelper.fakeChannelWithId(team1.id); const group1 = TestHelper.fakeGroupWithId(''); const group2 = TestHelper.fakeGroupWithId(''); const user1 = TestHelper.fakeUserWithId(''); user1.notify_props = {mention_keys: 'testkey1,testkey2'} as UserProfile['notify_props']; user1.roles = 'system_admin system_user'; const user2 = TestHelper.fakeUserWithId(); user2.delete_at = 1; const user3 = TestHelper.fakeUserWithId(); const user4 = TestHelper.fakeUserWithId(); const user5 = TestHelper.fakeUserWithId(); const user6 = TestHelper.fakeUserWithId(); user6.roles = 'system_admin system_user'; const user7 = TestHelper.fakeUserWithId(); user7.delete_at = 1; user7.roles = 'system_admin system_user'; const profiles: Record<string, UserProfile> = {}; profiles[user1.id] = user1; profiles[user2.id] = user2; profiles[user3.id] = user3; profiles[user4.id] = user4; profiles[user5.id] = user5; profiles[user6.id] = user6; profiles[user7.id] = user7; const profilesInTeam: Record<Team['id'], Set<UserProfile['id']>> = {}; profilesInTeam[team1.id] = new Set([user1.id, user2.id, user7.id]); const membersInTeam: Record<Team['id'], Record<UserProfile['id'], TeamMembership>> = {}; membersInTeam[team1.id] = {}; membersInTeam[team1.id][user1.id] = { ...TestHelper.fakeTeamMember(user1.id, team1.id), scheme_user: true, scheme_admin: true, }; membersInTeam[team1.id][user2.id] = { ...TestHelper.fakeTeamMember(user2.id, team1.id), scheme_user: true, scheme_admin: false, }; membersInTeam[team1.id][user7.id] = { ...TestHelper.fakeTeamMember(user7.id, team1.id), scheme_user: true, scheme_admin: false, }; const profilesNotInTeam: Record<Team['id'], Set<UserProfile['id']>> = {}; profilesNotInTeam[team1.id] = new Set([user3.id, user4.id]); const profilesWithoutTeam = new Set([user5.id, user6.id]); const profilesInChannel: Record<Channel['id'], Set<UserProfile['id']>> = {}; profilesInChannel[channel1.id] = new Set([user1.id]); profilesInChannel[channel2.id] = new Set([user1.id, user2.id]); const membersInChannel: Record<Channel['id'], Record<UserProfile['id'], ChannelMembership>> = {}; membersInChannel[channel1.id] = {}; membersInChannel[channel1.id][user1.id] = { ...TestHelper.fakeChannelMember(user1.id, channel1.id), scheme_user: true, scheme_admin: true, }; membersInChannel[channel2.id] = {}; membersInChannel[channel2.id][user1.id] = { ...TestHelper.fakeChannelMember(user1.id, channel2.id), scheme_user: true, scheme_admin: true, }; membersInChannel[channel2.id][user2.id] = { ...TestHelper.fakeChannelMember(user2.id, channel2.id), scheme_user: true, scheme_admin: false, }; const profilesNotInChannel: Record<Channel['id'], Set<UserProfile['id']>> = {}; profilesNotInChannel[channel1.id] = new Set([user2.id, user3.id]); profilesNotInChannel[channel2.id] = new Set([user4.id, user5.id]); const profilesInGroup: Record<Group['id'], Set<UserProfile['id']>> = {}; profilesInGroup[group1.id] = new Set([user1.id]); profilesInGroup[group2.id] = new Set([user2.id, user3.id]); const userSessions = [{ create_at: 1, expires_at: 2, props: {}, user_id: user1.id, roles: '', }]; const userAudits = [{ action: 'test_user_action', create_at: 1535007018934, extra_info: 'success', id: 'test_id', ip_address: '::1', session_id: '', user_id: 'test_user_id', }]; const myPreferences: PreferencesType = {}; myPreferences[`${Preferences.CATEGORY_DIRECT_CHANNEL_SHOW}--${user2.id}`] = {category: Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, name: user2.id, value: 'true', user_id: ''}; myPreferences[`${Preferences.CATEGORY_DIRECT_CHANNEL_SHOW}--${user3.id}`] = {category: Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, name: user3.id, value: 'false', user_id: ''}; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: user1.id, profiles, profilesInTeam, profilesNotInTeam, profilesWithoutTeam, profilesInChannel, profilesNotInChannel, profilesInGroup, mySessions: userSessions, myAudits: userAudits, }, teams: { currentTeamId: team1.id, membersInTeam, }, channels: { currentChannelId: channel1.id, membersInChannel, }, preferences: { myPreferences, }, }, }); it('getUserIdsInChannels', () => { expect(Selectors.getUserIdsInChannels(testState)).toEqual(profilesInChannel); }); it('getUserIdsNotInChannels', () => { expect(Selectors.getUserIdsNotInChannels(testState)).toEqual(profilesNotInChannel); }); it('getUserIdsInTeams', () => { expect(Selectors.getUserIdsInTeams(testState)).toEqual(profilesInTeam); }); it('getUserIdsNotInTeams', () => { expect(Selectors.getUserIdsNotInTeams(testState)).toEqual(profilesNotInTeam); }); it('getUserIdsWithoutTeam', () => { expect(Selectors.getUserIdsWithoutTeam(testState)).toEqual(profilesWithoutTeam); }); it('getUserSessions', () => { expect(Selectors.getUserSessions(testState)).toEqual(userSessions); }); it('getUserAudits', () => { expect(Selectors.getUserAudits(testState)).toEqual(userAudits); }); it('getUser', () => { expect(Selectors.getUser(testState, user1.id)).toEqual(user1); }); it('getUsers', () => { expect(Selectors.getUsers(testState)).toEqual(profiles); }); describe('getCurrentUserMentionKeys', () => { it('at mention', () => { const userId = '1234'; const notifyProps = {}; const state = { entities: { users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last', notify_props: notifyProps}, }, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserMentionKeys(state)).toEqual([{key: '@user'}]); }); it('channel', () => { const userId = '1234'; const notifyProps = { channel: 'true', }; const state = { entities: { users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last', notify_props: notifyProps}, }, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserMentionKeys(state)).toEqual([{key: '@channel'}, {key: '@all'}, {key: '@here'}, {key: '@user'}]); }); it('first name', () => { const userId = '1234'; const notifyProps = { first_name: 'true', }; const state = { entities: { users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last', notify_props: notifyProps}, }, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserMentionKeys(state)).toEqual([{key: 'First', caseSensitive: true}, {key: '@user'}]); }); it('custom keys', () => { const userId = '1234'; const notifyProps = { mention_keys: 'test,foo,@user,user', }; const state = { entities: { users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last', notify_props: notifyProps}, }, }, }, } as unknown as GlobalState; expect(Selectors.getCurrentUserMentionKeys(state)).toEqual([{key: 'test'}, {key: 'foo'}, {key: '@user'}, {key: 'user'}]); }); }); describe('getProfiles', () => { it('getProfiles without filter', () => { const users = [user1, user2, user3, user4, user5, user6, user7].sort(sortByUsername); expect(Selectors.getProfiles(testState)).toEqual(users); }); it('getProfiles with role filter', () => { const users = [user1, user6, user7].sort(sortByUsername); expect(Selectors.getProfiles(testState, {role: 'system_admin'})).toEqual(users); }); it('getProfiles with inactive', () => { const users = [user2, user7].sort(sortByUsername); expect(Selectors.getProfiles(testState, {inactive: true})).toEqual(users); }); it('getProfiles with active', () => { const users = [user1, user3, user4, user5, user6].sort(sortByUsername); expect(Selectors.getProfiles(testState, {active: true})).toEqual(users); }); it('getProfiles with multiple filters', () => { const users = [user7]; expect(Selectors.getProfiles(testState, {role: 'system_admin', inactive: true})).toEqual(users); }); }); it('getProfilesInCurrentTeam', () => { const users = [user1, user2, user7].sort(sortByUsername); expect(Selectors.getProfilesInCurrentTeam(testState)).toEqual(users); }); describe('getProfilesInTeam', () => { it('getProfilesInTeam without filter', () => { const users = [user1, user2, user7].sort(sortByUsername); expect(Selectors.getProfilesInTeam(testState, team1.id)).toEqual(users); expect(Selectors.getProfilesInTeam(testState, 'junk')).toEqual([]); }); it('getProfilesInTeam with role filter', () => { const users = [user1, user7].sort(sortByUsername); expect(Selectors.getProfilesInTeam(testState, team1.id, {role: 'system_admin'})).toEqual(users); expect(Selectors.getProfilesInTeam(testState, 'junk', {role: 'system_admin'})).toEqual([]); }); it('getProfilesInTeam with inactive filter', () => { const users = [user2, user7].sort(sortByUsername); expect(Selectors.getProfilesInTeam(testState, team1.id, {inactive: true})).toEqual(users); expect(Selectors.getProfilesInTeam(testState, 'junk', {inactive: true})).toEqual([]); }); it('getProfilesInTeam with active', () => { const users = [user1]; expect(Selectors.getProfilesInTeam(testState, team1.id, {active: true})).toEqual(users); expect(Selectors.getProfilesInTeam(testState, 'junk', {active: true})).toEqual([]); }); it('getProfilesInTeam with role filters', () => { expect(Selectors.getProfilesInTeam(testState, team1.id, {roles: ['system_admin']})).toEqual([user1, user7].sort(sortByUsername)); expect(Selectors.getProfilesInTeam(testState, team1.id, {team_roles: ['team_user']})).toEqual([user2]); }); it('getProfilesInTeam with multiple filters', () => { const users = [user7]; expect(Selectors.getProfilesInTeam(testState, team1.id, {role: 'system_admin', inactive: true})).toEqual(users); }); }); describe('getProfilesNotInTeam', () => { const users = [user3, user4].sort(sortByUsername); expect(Selectors.getProfilesNotInTeam(testState, team1.id)).toEqual(users); expect(Selectors.getProfilesNotInTeam(testState, team1.id, {role: 'system_user'})).toEqual(users); expect(Selectors.getProfilesNotInTeam(testState, team1.id, {role: 'system_guest'})).toEqual([]); }); it('getProfilesNotInCurrentTeam', () => { const users = [user3, user4].sort(sortByUsername); expect(Selectors.getProfilesNotInCurrentTeam(testState)).toEqual(users); }); describe('getProfilesWithoutTeam', () => { it('getProfilesWithoutTeam', () => { const users = [user5, user6].sort(sortByUsername); expect(Selectors.getProfilesWithoutTeam(testState, {} as any)).toEqual(users); }); it('getProfilesWithoutTeam with filter', () => { expect(Selectors.getProfilesWithoutTeam(testState, {role: 'system_admin'})).toEqual([user6]); }); }); it('getProfilesInGroup', () => { expect(Selectors.getProfilesInGroup(testState, group1.id)).toEqual([user1]); const users = [user2, user3].sort(sortByUsername); expect(Selectors.getProfilesInGroup(testState, group2.id)).toEqual(users); }); describe('searchProfilesStartingWithTerm', () => { it('searchProfiles without filter', () => { expect(searchProfilesStartingWithTerm(testState, user1.username)).toEqual([user1]); expect(searchProfilesStartingWithTerm(testState, user2.first_name + ' ' + user2.last_name)).toEqual([user2]); expect(searchProfilesStartingWithTerm(testState, user1.username, true)).toEqual([]); }); it('searchProfiles with filters', () => { expect(searchProfilesStartingWithTerm(testState, user1.username, false, {role: 'system_admin'})).toEqual([user1]); expect(searchProfilesStartingWithTerm(testState, user3.username, false, {role: 'system_admin'})).toEqual([]); expect(searchProfilesStartingWithTerm(testState, user1.username, false, {roles: ['system_user']})).toEqual([]); expect(searchProfilesStartingWithTerm(testState, user3.username, false, {roles: ['system_user']})).toEqual([user3]); expect(searchProfilesStartingWithTerm(testState, user3.username, false, {inactive: true})).toEqual([]); expect(searchProfilesStartingWithTerm(testState, user2.username, false, {inactive: true})).toEqual([user2]); expect(searchProfilesStartingWithTerm(testState, user2.username, false, {active: true})).toEqual([]); expect(searchProfilesStartingWithTerm(testState, user3.username, false, {active: true})).toEqual([user3]); }); }); describe('searchProfilesMatchingWithTerm', () => { it('searchProfiles without filter', () => { expect(searchProfilesMatchingWithTerm(testState, user1.username.slice(1, user1.username.length))).toEqual([user1]); expect(searchProfilesMatchingWithTerm(testState, ' ' + user2.last_name)).toEqual([user2]); }); it('searchProfiles with filters', () => { expect(searchProfilesMatchingWithTerm(testState, user1.username.slice(2, user1.username.length), false, {role: 'system_admin'})).toEqual([user1]); expect(searchProfilesMatchingWithTerm(testState, user3.username.slice(3, user3.username.length), false, {role: 'system_admin'})).toEqual([]); expect(searchProfilesMatchingWithTerm(testState, user1.username.slice(0, user1.username.length), false, {roles: ['system_user']})).toEqual([]); expect(searchProfilesMatchingWithTerm(testState, user3.username, false, {roles: ['system_user']})).toEqual([user3]); expect(searchProfilesMatchingWithTerm(testState, user3.username, false, {inactive: true})).toEqual([]); expect(searchProfilesMatchingWithTerm(testState, user2.username, false, {inactive: true})).toEqual([user2]); expect(searchProfilesMatchingWithTerm(testState, user2.username, false, {active: true})).toEqual([]); expect(searchProfilesMatchingWithTerm(testState, user3.username, false, {active: true})).toEqual([user3]); }); }); it('searchProfilesInChannel', () => { const doSearchProfilesInChannel = Selectors.makeSearchProfilesInChannel(); expect(doSearchProfilesInChannel(testState, channel1.id, user1.username)).toEqual([user1]); expect(doSearchProfilesInChannel(testState, channel1.id, user1.username, true)).toEqual([]); expect(doSearchProfilesInChannel(testState, channel2.id, user2.username)).toEqual([user2]); expect(doSearchProfilesInChannel(testState, channel2.id, user2.username, false, {active: true})).toEqual([]); }); it('searchProfilesInCurrentChannel', () => { expect(Selectors.searchProfilesInCurrentChannel(testState, user1.username)).toEqual([user1]); expect(Selectors.searchProfilesInCurrentChannel(testState, user1.username, true)).toEqual([]); }); it('searchProfilesNotInCurrentChannel', () => { expect(Selectors.searchProfilesNotInCurrentChannel(testState, user2.username)).toEqual([user2]); expect(Selectors.searchProfilesNotInCurrentChannel(testState, user2.username, true)).toEqual([user2]); }); it('searchProfilesInCurrentTeam', () => { expect(Selectors.searchProfilesInCurrentTeam(testState, user1.username)).toEqual([user1]); expect(Selectors.searchProfilesInCurrentTeam(testState, user1.username, true)).toEqual([]); }); describe('searchProfilesInTeam', () => { it('searchProfilesInTeam without filter', () => { expect(Selectors.searchProfilesInTeam(testState, team1.id, user1.username)).toEqual([user1]); expect(Selectors.searchProfilesInTeam(testState, team1.id, user1.username, true)).toEqual([]); }); it('searchProfilesInTeam with filter', () => { expect(Selectors.searchProfilesInTeam(testState, team1.id, user1.username, false, {role: 'system_admin'})).toEqual([user1]); expect(Selectors.searchProfilesInTeam(testState, team1.id, user1.username, false, {inactive: true})).toEqual([]); expect(Selectors.searchProfilesInTeam(testState, team1.id, user2.username, false, {active: true})).toEqual([]); expect(Selectors.searchProfilesInTeam(testState, team1.id, user1.username, false, {active: true})).toEqual([user1]); }); it('getProfiles with multiple filters', () => { const users = [user7]; expect(Selectors.searchProfilesInTeam(testState, team1.id, user7.username, false, {role: 'system_admin', inactive: true})).toEqual(users); }); }); it('searchProfilesNotInCurrentTeam', () => { expect(Selectors.searchProfilesNotInCurrentTeam(testState, user3.username)).toEqual([user3]); expect(Selectors.searchProfilesNotInCurrentTeam(testState, user3.username, true)).toEqual([user3]); }); describe('searchProfilesWithoutTeam', () => { it('searchProfilesWithoutTeam without filter', () => { expect(Selectors.searchProfilesWithoutTeam(testState, user5.username, false, {})).toEqual([user5]); expect(Selectors.searchProfilesWithoutTeam(testState, user5.username, true, {})).toEqual([user5]); }); it('searchProfilesWithoutTeam with filter', () => { expect(Selectors.searchProfilesWithoutTeam(testState, user6.username, false, {role: 'system_admin'})).toEqual([user6]); expect(Selectors.searchProfilesWithoutTeam(testState, user5.username, false, {inactive: true})).toEqual([]); }); }); it('searchProfilesInGroup', () => { expect(Selectors.searchProfilesInGroup(testState, group1.id, user5.username)).toEqual([]); expect(Selectors.searchProfilesInGroup(testState, group1.id, user1.username)).toEqual([user1]); expect(Selectors.searchProfilesInGroup(testState, group2.id, user2.username)).toEqual([user2]); expect(Selectors.searchProfilesInGroup(testState, group2.id, user3.username)).toEqual([user3]); }); it('isCurrentUserSystemAdmin', () => { expect(Selectors.isCurrentUserSystemAdmin(testState)).toEqual(true); }); it('getUserByUsername', () => { expect(Selectors.getUserByUsername(testState, user1.username)).toEqual(user1); }); it('getUsersInVisibleDMs', () => { expect(Selectors.getUsersInVisibleDMs(testState)).toEqual([user2]); }); it('getUserByEmail', () => { expect(Selectors.getUserByEmail(testState, user1.email)).toEqual(user1); expect(Selectors.getUserByEmail(testState, user2.email)).toEqual(user2); }); it('makeGetProfilesInChannel', () => { const getProfilesInChannel = Selectors.makeGetProfilesInChannel(); expect(getProfilesInChannel(testState, channel1.id)).toEqual([user1]); const users = [user1, user2].sort(sortByUsername); expect(getProfilesInChannel(testState, channel2.id)).toEqual(users); expect(getProfilesInChannel(testState, channel2.id, {active: true})).toEqual([user1]); expect(getProfilesInChannel(testState, channel2.id, {channel_roles: ['channel_admin']})).toEqual([]); expect(getProfilesInChannel(testState, channel2.id, {channel_roles: ['channel_user']})).toEqual([user2]); expect(getProfilesInChannel(testState, channel2.id, {channel_roles: ['channel_admin', 'channel_user']})).toEqual([user2]); expect(getProfilesInChannel(testState, channel2.id, {roles: ['system_admin'], channel_roles: ['channel_admin', 'channel_user']})).toEqual([user1, user2].sort(sortByUsername)); expect(getProfilesInChannel(testState, 'nonexistentid')).toEqual([]); expect(getProfilesInChannel(testState, 'nonexistentid')).toEqual([]); }); it('makeGetProfilesInChannel, unknown user id in channel', () => { const state = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, profilesInChannel: { ...testState.entities.users.profilesInChannel, [channel1.id]: new Set([...testState.entities.users.profilesInChannel[channel1.id], 'unknown']), }, }, }, }; const getProfilesInChannel = Selectors.makeGetProfilesInChannel(); expect(getProfilesInChannel(state, channel1.id)).toEqual([user1]); expect(getProfilesInChannel(state, channel1.id, {})).toEqual([user1]); }); it('makeGetProfilesNotInChannel', () => { const getProfilesNotInChannel = Selectors.makeGetProfilesNotInChannel(); expect(getProfilesNotInChannel(testState, channel1.id)).toEqual([user2, user3].sort(sortByUsername)); expect(getProfilesNotInChannel(testState, channel2.id)).toEqual([user4, user5].sort(sortByUsername)); expect(getProfilesNotInChannel(testState, 'nonexistentid')).toEqual([]); expect(getProfilesNotInChannel(testState, 'nonexistentid')).toEqual([]); }); it('makeGetProfilesByIdsAndUsernames', () => { const getProfilesByIdsAndUsernames = Selectors.makeGetProfilesByIdsAndUsernames(); const testCases = [ {input: {allUserIds: [], allUsernames: []}, output: []}, {input: {allUserIds: ['nonexistentid'], allUsernames: ['nonexistentid']}, output: []}, {input: {allUserIds: [user1.id], allUsernames: []}, output: [user1]}, {input: {allUserIds: [user1.id]}, output: [user1]}, {input: {allUserIds: [user1.id, 'nonexistentid']}, output: [user1]}, {input: {allUserIds: [user1.id, user2.id]}, output: [user1, user2]}, {input: {allUserIds: ['nonexistentid', user1.id, user2.id]}, output: [user1, user2]}, {input: {allUserIds: [], allUsernames: [user1.username]}, output: [user1]}, {input: {allUsernames: [user1.username]}, output: [user1]}, {input: {allUsernames: [user1.username, 'nonexistentid']}, output: [user1]}, {input: {allUsernames: [user1.username, user2.username]}, output: [user1, user2]}, {input: {allUsernames: [user1.username, 'nonexistentid', user2.username]}, output: [user1, user2]}, {input: {allUserIds: [user1.id], allUsernames: [user2.username]}, output: [user1, user2]}, {input: {allUserIds: [user1.id, user2.id], allUsernames: [user3.username, user4.username]}, output: [user1, user2, user3, user4]}, {input: {allUserIds: [user1.username, user2.username], allUsernames: [user3.id, user4.id]}, output: []}, ]; testCases.forEach((testCase) => { expect(getProfilesByIdsAndUsernames(testState, testCase.input as Parameters<typeof getProfilesByIdsAndUsernames>[1])).toEqual(testCase.output); }); }); describe('makeGetDisplayName and makeDisplayNameGetter', () => { const testUser1 = { ...user1, id: 'test_user_id', username: 'username', first_name: 'First', last_name: 'Last', }; const newProfiles = { ...profiles, [testUser1.id]: testUser1, }; it('Should show full name since preferences is being used and LockTeammateNameDisplay is false', () => { const newTestState = { entities: { users: {profiles: newProfiles}, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.NAME_NAME_FORMAT}`]: { value: General.TEAMMATE_NAME_DISPLAY.SHOW_FULLNAME, }, }, }, general: { config: { TeammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, LockTeammateNameDisplay: 'false', }, license: { LockTeammateNameDisplay: 'true', }, }, }, } as unknown as GlobalState; expect(Selectors.makeGetDisplayName()(newTestState, testUser1.id)).toEqual('First Last'); expect(Selectors.makeDisplayNameGetter()(newTestState, false)(testUser1)).toEqual('First Last'); }); it('Should show show username since LockTeammateNameDisplay is true', () => { const newTestState = { entities: { users: {profiles: newProfiles}, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.NAME_NAME_FORMAT}`]: { value: General.TEAMMATE_NAME_DISPLAY.SHOW_FULLNAME, }, }, }, general: { config: { TeammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, LockTeammateNameDisplay: 'true', }, license: { LockTeammateNameDisplay: 'true', }, }, }, } as unknown as GlobalState; expect(Selectors.makeGetDisplayName()(newTestState, testUser1.id)).toEqual('username'); expect(Selectors.makeDisplayNameGetter()(newTestState, false)(testUser1)).toEqual('username'); }); it('Should show full name since license is false', () => { const newTestState = { entities: { users: {profiles: newProfiles}, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.NAME_NAME_FORMAT}`]: { value: General.TEAMMATE_NAME_DISPLAY.SHOW_FULLNAME, }, }, }, general: { config: { TeammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, LockTeammateNameDisplay: 'true', }, license: { LockTeammateNameDisplay: 'false', }, }, }, } as unknown as GlobalState; expect(Selectors.makeGetDisplayName()(newTestState, testUser1.id)).toEqual('First Last'); expect(Selectors.makeDisplayNameGetter()(newTestState, false)(testUser1)).toEqual('First Last'); }); it('Should show full name since license is not available', () => { const newTestState = { entities: { users: {profiles: newProfiles}, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.NAME_NAME_FORMAT}`]: { value: General.TEAMMATE_NAME_DISPLAY.SHOW_FULLNAME, }, }, }, general: { config: { TeammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, LockTeammateNameDisplay: 'true', }, }, }, } as GlobalState; expect(Selectors.makeGetDisplayName()(newTestState, testUser1.id)).toEqual('First Last'); expect(Selectors.makeDisplayNameGetter()(newTestState, false)(testUser1)).toEqual('First Last'); }); it('Should show Full name since license is not available and lock teammate name display is false', () => { const newTestState = { entities: { users: {profiles: newProfiles}, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.NAME_NAME_FORMAT}`]: { value: General.TEAMMATE_NAME_DISPLAY.SHOW_FULLNAME, }, }, }, general: { config: { TeammateNameDisplay: General.TEAMMATE_NAME_DISPLAY.SHOW_USERNAME, LockTeammateNameDisplay: 'false', }, }, }, } as GlobalState; expect(Selectors.makeGetDisplayName()(newTestState, testUser1.id)).toEqual('First Last'); expect(Selectors.makeDisplayNameGetter()(newTestState, false)(testUser1)).toEqual('First Last'); }); it('Should show username since no settings are available (falls back to default)', () => { const newTestState = { entities: { users: {profiles: newProfiles}, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.NAME_NAME_FORMAT}`]: { }, }, }, general: { config: { }, }, }, } as GlobalState; expect(Selectors.makeGetDisplayName()(newTestState, testUser1.id)).toEqual('username'); expect(Selectors.makeDisplayNameGetter()(newTestState, false)(testUser1)).toEqual('username'); }); }); it('shouldShowTermsOfService', () => { const userId = 1234; // Test latest terms not accepted expect(Selectors.shouldShowTermsOfService({ entities: { general: { config: { CustomTermsOfServiceId: '1', EnableCustomTermsOfService: 'true', }, license: { IsLicensed: 'true', }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last'}, }, }, }, } as unknown as GlobalState)).toEqual(true); // Test Feature disabled expect(Selectors.shouldShowTermsOfService({ entities: { general: { config: { CustomTermsOfServiceId: '1', EnableCustomTermsOfService: 'false', }, license: { IsLicensed: 'true', }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last'}, }, }, }, } as unknown as GlobalState)).toEqual(false); // Test unlicensed expect(Selectors.shouldShowTermsOfService({ entities: { general: { config: { CustomTermsOfServiceId: '1', EnableCustomTermsOfService: 'true', }, license: { IsLicensed: 'false', }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last'}, }, }, }, } as unknown as GlobalState)).toEqual(false); // Test terms already accepted expect(Selectors.shouldShowTermsOfService({ entities: { general: { config: { CustomTermsOfServiceId: '1', EnableCustomTermsOfService: 'true', }, license: { IsLicensed: 'true', }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: 'user', first_name: 'First', last_name: 'Last', terms_of_service_id: '1', terms_of_service_create_at: new Date().getTime()}, }, }, }, } as unknown as GlobalState)).toEqual(false); // Test not logged in expect(Selectors.shouldShowTermsOfService({ entities: { general: { config: { CustomTermsOfServiceId: '1', EnableCustomTermsOfService: 'true', }, license: { IsLicensed: 'true', }, }, users: { currentUserId: userId, profiles: {}, }, }, } as unknown as GlobalState)).toEqual(false); }); describe('currentUserHasAnAdminRole', () => { it('returns the expected result', () => { expect(Selectors.currentUserHasAnAdminRole(testState)).toEqual(true); const state = { ...testState, entities: { ...testState.entities, users: { ...testState.entities.users, currentUserId: user2.id, }, }, }; expect(Selectors.currentUserHasAnAdminRole(state)).toEqual(false); }); }); describe('filterProfiles', () => { it('no filter, return all users', () => { expect(Object.keys(Selectors.filterProfiles(profiles)).length).toEqual(7); }); it('filter role', () => { const filter = { role: 'system_admin', }; expect(Object.keys(Selectors.filterProfiles(profiles, filter)).length).toEqual(3); }); it('filter roles', () => { const filter = { roles: ['system_admin'], team_roles: ['team_admin'], }; const membership = TestHelper.fakeTeamMember(user3.id, team1.id); membership.scheme_admin = true; const memberships = {[user3.id]: membership}; expect(Object.keys(Selectors.filterProfiles(profiles, filter, memberships)).length).toEqual(4); }); it('exclude_roles', () => { const filter = { exclude_roles: ['system_admin'], }; expect(Object.keys(Selectors.filterProfiles(profiles, filter)).length).toEqual(4); }); it('exclude bots', () => { const filter = { exclude_bots: true, }; const botUser = { ...user1, id: 'test_bot_id', username: 'botusername', first_name: '', last_name: '', is_bot: true, }; const newProfiles = { ...profiles, [botUser.id]: botUser, }; expect(Object.keys(Selectors.filterProfiles(newProfiles, filter)).length).toEqual(7); }); it('filter inactive', () => { const filter = { inactive: true, }; expect(Object.keys(Selectors.filterProfiles(profiles, filter)).length).toEqual(2); }); it('filter active', () => { const filter = { active: true, }; expect(Object.keys(Selectors.filterProfiles(profiles, filter)).length).toEqual(5); }); }); });
4,109
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/selectors/entities/utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {General} from 'mattermost-redux/constants'; import deepFreezeAndThrowOnMutation from 'mattermost-redux/utils/deep_freeze'; import {makeAddLastViewAtToProfiles} from './utils'; import TestHelper from '../../../test/test_helper'; describe('utils.makeAddLastViewAtToProfiles', () => { it('Should return profiles with last_viewed_at from membership if channel and membership exists', () => { const currentUser = TestHelper.fakeUserWithStatus(General.ONLINE); const user1 = TestHelper.fakeUserWithStatus(General.OUT_OF_OFFICE); const user2 = TestHelper.fakeUserWithStatus(General.OFFLINE); const user3 = TestHelper.fakeUserWithStatus(General.DND); const user4 = TestHelper.fakeUserWithStatus(General.AWAY); const profiles = { [user1.id]: user1, [user2.id]: user2, [user3.id]: user3, [user4.id]: user4, }; const statuses = { [user1.id]: user1.status, [user2.id]: user2.status, [user3.id]: user3.status, [user4.id]: user4.status, }; const channel1 = TestHelper.fakeDmChannel(currentUser.id, user1.id); const channel2 = TestHelper.fakeDmChannel(currentUser.id, user2.id); const channel3 = TestHelper.fakeDmChannel(currentUser.id, user3.id); const channels = { [channel1.id]: channel1, [channel2.id]: channel2, [channel3.id]: channel3, }; const membership1 = {...TestHelper.fakeChannelMember(currentUser.id, channel1.id), last_viewed_at: 1}; const membership2 = {...TestHelper.fakeChannelMember(currentUser.id, channel2.id), last_viewed_at: 2}; const membership3 = {...TestHelper.fakeChannelMember(currentUser.id, channel3.id), last_viewed_at: 3}; const myMembers = { [membership1.channel_id]: membership1, [membership2.channel_id]: membership2, [membership3.channel_id]: membership3, }; const channelsInTeam = { '': [channel1.id, channel2.id, channel3.id], }; const testState = deepFreezeAndThrowOnMutation({ entities: { users: { currentUserId: currentUser.id, profiles, statuses, }, teams: { currentTeamId: 'currentTeam', }, channels: { channels, channelsInTeam, myMembers, }, general: { config: {}, }, preferences: { myPreferences: {}, }, }, }); const addLastViewAtToProfiles = makeAddLastViewAtToProfiles(); expect(addLastViewAtToProfiles(testState, [user1, user2, user3, user4])).toEqual([{...user1, last_viewed_at: 1}, {...user2, last_viewed_at: 2}, {...user3, last_viewed_at: 3}, {...user4, last_viewed_at: 0}]); }); });
4,115
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/store/reducer_registry.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import reducerRegistry from 'mattermost-redux/store/reducer_registry'; import configureStore from '../../test/test_store'; describe('ReducerRegistry', () => { let store = configureStore(); function testReducer() { return 'teststate'; } beforeEach(() => { store = configureStore(); }); it('register reducer', () => { reducerRegistry.register('testReducer', testReducer); expect(store.getState().testReducer).toBe('teststate'); }); it('get reducers', () => { reducerRegistry.register('testReducer', testReducer); const reducers = reducerRegistry.getReducers(); expect(reducers.testReducer).toBeTruthy(); }); });
4,118
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/apps.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {AppBinding, AppCall, AppField, AppForm, AppSelectOption} from '@mattermost/types/apps'; import {AppBindingLocations, AppFieldTypes} from 'mattermost-redux/constants/apps'; import {cleanForm, cleanBinding, validateBindings} from './apps'; describe('Apps Utils', () => { const basicCall: AppCall = { path: 'url', }; const basicSubmitForm: AppForm = { submit: basicCall, }; const basicFetchForm: AppForm = { source: basicCall, }; describe('fillAndTrimBindingsInformation', () => { test('Apps IDs propagate down, and locations get formed', () => { const inBinding: AppBinding = { app_id: 'id', location: 'loc1', bindings: [ { location: 'loc2', bindings: [ { location: 'loc3', submit: basicCall, }, { location: 'loc4', form: basicSubmitForm, }, ], }, { location: 'loc5', form: basicFetchForm, }, ], } as AppBinding; const outBinding: AppBinding = { app_id: 'id', location: 'loc1', bindings: [ { location: 'loc1/loc2', app_id: 'id', label: 'loc2', bindings: [ { location: 'loc1/loc2/loc3', app_id: 'id', label: 'loc3', submit: basicCall, }, { location: 'loc1/loc2/loc4', app_id: 'id', label: 'loc4', form: basicSubmitForm, }, ], }, { location: 'loc1/loc5', app_id: 'id', label: 'loc5', form: basicFetchForm, }, ], } as AppBinding; cleanBinding(inBinding, ''); expect(inBinding).toEqual(outBinding); }); test('Trim branches without call.', () => { const inBinding: AppBinding = { location: 'loc1', app_id: 'id', bindings: [ { location: 'loc2', bindings: [ { location: 'loc3', }, { location: 'loc4', form: basicSubmitForm, }, { location: 'loc5', form: basicFetchForm, }, ], }, { location: 'loc6', }, { location: 'loc7', submit: basicCall, }, { location: 'loc8', form: {}, }, ], } as AppBinding; const outBinding: AppBinding = { app_id: 'id', location: 'loc1', bindings: [ { location: 'loc1/loc2', app_id: 'id', label: 'loc2', bindings: [ { location: 'loc1/loc2/loc4', app_id: 'id', form: basicSubmitForm, label: 'loc4', }, { location: 'loc1/loc2/loc5', app_id: 'id', form: basicFetchForm, label: 'loc5', }, ], }, { location: 'loc1/loc7', app_id: 'id', submit: basicCall, label: 'loc7', }, ], } as AppBinding; cleanBinding(inBinding, ''); expect(inBinding).toEqual(outBinding); }); test('Trim branches with calls, bindings and forms.', () => { const inBinding: AppBinding = { location: 'loc1', app_id: 'id', bindings: [ { location: 'loc2', bindings: [ { location: 'loc3', submit: basicCall, form: basicSubmitForm, }, { location: 'loc4', form: basicSubmitForm, }, { location: 'loc5', form: basicFetchForm, }, ], }, { location: 'loc6', submit: basicCall, bindings: [ { location: 'loc9', submit: basicCall, }, ], }, { location: 'loc7', submit: basicCall, }, { location: 'loc8', form: basicFetchForm, bindings: [ { location: 'loc10', submit: basicCall, }, ], }, ], } as AppBinding; const outBinding: AppBinding = { app_id: 'id', location: 'loc1', bindings: [ { location: 'loc1/loc2', app_id: 'id', label: 'loc2', bindings: [ { location: 'loc1/loc2/loc4', app_id: 'id', form: basicSubmitForm, label: 'loc4', }, { location: 'loc1/loc2/loc5', app_id: 'id', form: basicFetchForm, label: 'loc5', }, ], }, { location: 'loc1/loc7', app_id: 'id', submit: basicCall, label: 'loc7', }, ], } as AppBinding; cleanBinding(inBinding, ''); expect(inBinding).toEqual(outBinding); }); test('Trim branches with whitespace labels.', () => { const inBinding: AppBinding = { location: 'loc1', app_id: 'id', bindings: [ { location: 'loc2', label: ' ', bindings: [ { location: 'loc4', form: basicSubmitForm, }, { location: 'loc5', form: basicFetchForm, }, ], }, ], } as AppBinding; const outBinding: AppBinding = { app_id: 'id', location: 'loc1', bindings: [] as AppBinding[], } as AppBinding; cleanBinding(inBinding, ''); expect(inBinding).toEqual(outBinding); }); }); describe('cleanForm', () => { test('no field filter on names', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, }, { name: 'opt2', type: AppFieldTypes.TEXT, }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, }, { name: 'opt2', type: AppFieldTypes.TEXT, }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('no field filter on labels', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'opt1', }, { name: 'opt2', type: AppFieldTypes.TEXT, label: 'opt2', }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'opt1', }, { name: 'opt2', type: AppFieldTypes.TEXT, label: 'opt2', }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('no field filter with no name', () => { const inForm: AppForm = { fields: [ { type: AppFieldTypes.TEXT, label: 'opt1', } as AppField, { name: 'opt2', type: AppFieldTypes.TEXT, label: 'opt2', }, ], }; const outForm: AppForm = { fields: [ { name: 'opt2', type: AppFieldTypes.TEXT, label: 'opt2', }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter with same label inferred from name', () => { const inForm: AppForm = { fields: [ { name: 'same', type: AppFieldTypes.TEXT, }, { name: 'same', type: AppFieldTypes.BOOL, }, ], }; const outForm: AppForm = { fields: [ { name: 'same', type: AppFieldTypes.TEXT, }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter with same labels', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'same', }, { name: 'opt2', type: AppFieldTypes.TEXT, label: 'same', }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'same', }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter with multiword name', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'opt1', }, { name: 'opt 2', type: AppFieldTypes.TEXT, label: 'opt2', }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'opt1', }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter with multiword label', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'opt1', }, { name: 'opt2', type: AppFieldTypes.TEXT, label: 'opt 2', }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'opt1', }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter more than one field', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'same', }, { name: 'opt2', type: AppFieldTypes.BOOL, label: 'same', }, { name: 'opt2', type: AppFieldTypes.USER, label: 'same', }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.TEXT, label: 'same', }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter static with no options', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, }, ], }; const outForm: AppForm = { fields: [], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter static options with no value', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ {value: 'opt1'} as AppSelectOption, {} as AppSelectOption, ], }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ {value: 'opt1'} as AppSelectOption, ], }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter static options with same label inferred from value', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { value: 'same', icon_data: 'opt1', } as AppSelectOption, { value: 'same', icon_data: 'opt2', } as AppSelectOption, ], }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { value: 'same', icon_data: 'opt1', } as AppSelectOption, ], }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter static options with same label', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { value: 'opt1', label: 'same', }, { value: 'opt2', label: 'same', }, ], }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { value: 'opt1', label: 'same', }, ], }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter static options with same value', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { label: 'opt1', value: 'same', }, { label: 'opt2', value: 'same', }, ], }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { label: 'opt1', value: 'same', }, ], }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('invalid static options don\'t consume namespace', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { label: 'same1', value: 'same1', }, { label: 'same1', value: 'same2', }, { label: 'same2', value: 'same1', }, { label: 'same2', value: 'same2', }, ], }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ { label: 'same1', value: 'same1', }, { label: 'same2', value: 'same2', }, ], }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter static with no valid options', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.STATIC_SELECT, options: [ {} as AppSelectOption, ], }, ], }; const outForm: AppForm = { fields: [], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('invalid static field does not consume namespace', () => { const inForm: AppForm = { fields: [ { name: 'field1', type: AppFieldTypes.STATIC_SELECT, options: [ {} as AppSelectOption, ], }, { name: 'field1', type: AppFieldTypes.TEXT, }, ], }; const outForm: AppForm = { fields: [ { name: 'field1', type: AppFieldTypes.TEXT, }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('field filter dynamic with no valid lookup call', () => { const inForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.DYNAMIC_SELECT, lookup: basicCall, }, { name: 'opt2', type: AppFieldTypes.DYNAMIC_SELECT, }, ], }; const outForm: AppForm = { fields: [ { name: 'opt1', type: AppFieldTypes.DYNAMIC_SELECT, lookup: basicCall, }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); test('invalid dynamic field does not consume namespace', () => { const inForm: AppForm = { fields: [ { name: 'field1', type: AppFieldTypes.DYNAMIC_SELECT, }, { name: 'field1', type: AppFieldTypes.TEXT, }, ], }; const outForm: AppForm = { fields: [ { name: 'field1', type: AppFieldTypes.TEXT, }, ], }; cleanForm(inForm); expect(inForm).toEqual(outForm); }); }); describe('cleanCommands', () => { test('happy path', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'loc11', label: 'loc11', submit: basicCall, }, { app_id: 'app', location: 'loc12', label: 'loc12', form: basicSubmitForm, }, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: basicFetchForm, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/loc11', label: 'loc11', submit: basicCall, }, { app_id: 'app', location: '/command/loc1/loc12', label: 'loc12', form: basicSubmitForm, }, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: basicFetchForm, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); test('no label nor location', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'loc11', label: 'loc11', form: { submit: { path: '/path', }, }, }, { app_id: 'app', form: { submit: { path: '/path', }, }, } as AppBinding, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/loc11', label: 'loc11', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); test('no multiword infered from location', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'loc11', label: 'loc11', form: { submit: { path: '/path', }, }, }, { app_id: 'app', location: 'loc1 2', form: { submit: { path: '/path', }, }, } as AppBinding, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/loc11', label: 'loc11', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); test('no multiword on label', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'loc11', label: 'loc11', form: { submit: { path: '/path', }, }, }, { app_id: 'app', location: 'loc12', label: 'loc1 2', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/loc11', label: 'loc11', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); test('filter repeated label', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'same', description: 'loc11', form: { submit: { path: '/path', }, }, } as AppBinding, { app_id: 'app', location: 'same', description: 'loc12', form: { submit: { path: '/path', }, }, } as AppBinding, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/same', label: 'same', description: 'loc11', form: { submit: { path: '/path', }, }, } as AppBinding, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); test('filter with same label', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'loc11', label: 'same', form: { submit: { path: '/path', }, }, }, { app_id: 'app', location: 'loc12', label: 'same', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/loc11', label: 'same', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); test('non-leaf command removed when it has no subcommands', () => { const inBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: 'loc1', label: 'loc1', bindings: [ { app_id: 'app', location: 'loc11', label: 'loc 1 1', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: 'loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; cleanBinding(inBinding, AppBindingLocations.COMMAND); expect(inBinding).toEqual(outBinding); }); }); describe('validateBindings', () => { test('return validated binding when bindings are NOT empty', () => { const outBinding: AppBinding = { location: '/command', bindings: [ { app_id: 'app', location: '/command/loc1', label: 'loc1', bindings: [ { app_id: 'app', location: '/command/loc1/loc11', label: 'same', form: { submit: { path: '/path', }, }, }, ], }, { app_id: 'app', location: '/command/loc2', label: 'loc2', form: { submit: { path: '/path', }, }, }, ], } as AppBinding; const bindings = validateBindings([outBinding]); expect([outBinding]).toEqual(bindings); }); test('return empty array when bindings are empty', () => { const inBinding: AppBinding = { location: '/command', bindings: [] as AppBinding[], } as AppBinding; const bindings = validateBindings([inBinding]); expect([]).toEqual(bindings); }); test('return empty array when bindings is NULL', () => { const inBinding: AppBinding = { location: '/command', bindings: null, } as unknown as AppBinding; const bindings = validateBindings([inBinding]); expect([]).toEqual(bindings); }); }); });
4,120
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/array_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {insertWithoutDuplicates, insertMultipleWithoutDuplicates, removeItem} from './array_utils'; describe('insertWithoutDuplicates', () => { test('should add the item at the given location', () => { expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'z', 0)).toEqual(['z', 'a', 'b', 'c', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'z', 1)).toEqual(['a', 'z', 'b', 'c', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'z', 2)).toEqual(['a', 'b', 'z', 'c', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'z', 3)).toEqual(['a', 'b', 'c', 'z', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'z', 4)).toEqual(['a', 'b', 'c', 'd', 'z']); }); test('should move an item if it already exists', () => { expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'a', 0)).toEqual(['a', 'b', 'c', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'a', 1)).toEqual(['b', 'a', 'c', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'a', 2)).toEqual(['b', 'c', 'a', 'd']); expect(insertWithoutDuplicates(['a', 'b', 'c', 'd'], 'a', 3)).toEqual(['b', 'c', 'd', 'a']); }); test('should return the original array if nothing changed', () => { const input = ['a', 'b', 'c', 'd']; expect(insertWithoutDuplicates(input, 'a', 0)).toBe(input); }); }); describe('insertMultipleWithoutDuplicates', () => { test('should add the item at the given location', () => { expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x'], 0)).toEqual(['z', 'y', 'x', 'a', 'b', 'c', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x'], 1)).toEqual(['a', 'z', 'y', 'x', 'b', 'c', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x'], 2)).toEqual(['a', 'b', 'z', 'y', 'x', 'c', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x'], 3)).toEqual(['a', 'b', 'c', 'z', 'y', 'x', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x'], 4)).toEqual(['a', 'b', 'c', 'd', 'z', 'y', 'x']); }); test('should move an item if it already exists', () => { expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['a', 'c'], 0)).toEqual(['a', 'c', 'b', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['a', 'c'], 1)).toEqual(['b', 'a', 'c', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['a', 'c'], 2)).toEqual(['b', 'd', 'a', 'c']); }); test('should properly place new and existing items', () => { expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x', 'a', 'c'], 0)).toEqual(['z', 'y', 'x', 'a', 'c', 'b', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x', 'a', 'c'], 1)).toEqual(['b', 'z', 'y', 'x', 'a', 'c', 'd']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['z', 'y', 'x', 'a', 'c'], 2)).toEqual(['b', 'd', 'z', 'y', 'x', 'a', 'c']); }); test('should return the original array if nothing changed', () => { const input = ['a', 'b', 'c', 'd']; expect(insertMultipleWithoutDuplicates(input, ['a', 'b', 'c'], 0)).toStrictEqual(input); }); test('should just return the array if either the input or items to insert is blank', () => { expect(insertMultipleWithoutDuplicates([], ['a', 'b', 'c'], 0)).toStrictEqual(['a', 'b', 'c']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c'], [], 0)).toStrictEqual(['a', 'b', 'c']); }); test('should handle invalid index inputs', () => { expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['e', 'f'], 10)).toStrictEqual(['a', 'b', 'c', 'd', 'e', 'f']); expect(insertMultipleWithoutDuplicates(['a', 'b', 'c', 'd'], ['e', 'f'], -2)).toStrictEqual(['a', 'b', 'e', 'f', 'c', 'd']); }); }); describe('removeItem', () => { test('should remove the given item', () => { expect(removeItem(['a', 'b', 'c', 'd'], 'a')).toEqual(['b', 'c', 'd']); expect(removeItem(['a', 'b', 'c', 'd'], 'b')).toEqual(['a', 'c', 'd']); expect(removeItem(['a', 'b', 'c', 'd'], 'c')).toEqual(['a', 'b', 'd']); expect(removeItem(['a', 'b', 'c', 'd'], 'd')).toEqual(['a', 'b', 'c']); }); test('should return the original array if nothing changed', () => { const input = ['a', 'b', 'c', 'd']; expect(removeItem(input, 'e')).toBe(input); }); });
4,122
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/channel_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ChannelNotifyProps} from '@mattermost/types/channels'; import type {Post} from '@mattermost/types/posts'; import { areChannelMentionsIgnored, filterChannelsMatchingTerm, sortChannelsByRecency, sortChannelsByDisplayName, sortChannelsByTypeListAndDisplayName, } from 'mattermost-redux/utils/channel_utils'; import TestHelper from '../../test/test_helper'; import {General, Users} from '../constants'; describe('ChannelUtils', () => { it('areChannelMentionsIgnored', () => { const currentUserNotifyProps1 = TestHelper.fakeUserNotifyProps({channel: 'true'}); const channelMemberNotifyProps1 = TestHelper.fakeChannelNotifyProps({ignore_channel_mentions: Users.IGNORE_CHANNEL_MENTIONS_DEFAULT as 'default'}); expect(areChannelMentionsIgnored(channelMemberNotifyProps1, currentUserNotifyProps1)).toBe(false); const currentUserNotifyProps2 = TestHelper.fakeUserNotifyProps({channel: 'true'}); const channelMemberNotifyProps2 = TestHelper.fakeChannelNotifyProps({ignore_channel_mentions: Users.IGNORE_CHANNEL_MENTIONS_OFF as 'off'}); expect(areChannelMentionsIgnored(channelMemberNotifyProps2, currentUserNotifyProps2)).toBe(false); const currentUserNotifyProps3 = TestHelper.fakeUserNotifyProps({channel: 'true'}); const channelMemberNotifyProps3 = TestHelper.fakeChannelNotifyProps({ignore_channel_mentions: Users.IGNORE_CHANNEL_MENTIONS_ON as 'on'}); expect(areChannelMentionsIgnored(channelMemberNotifyProps3, currentUserNotifyProps3)).toBe(true); const currentUserNotifyProps4 = TestHelper.fakeUserNotifyProps({channel: 'false'}); const channelMemberNotifyProps4 = TestHelper.fakeChannelNotifyProps({ignore_channel_mentions: Users.IGNORE_CHANNEL_MENTIONS_DEFAULT as 'default'}); expect(areChannelMentionsIgnored(channelMemberNotifyProps4, currentUserNotifyProps4)).toBe(true); const currentUserNotifyProps5 = TestHelper.fakeUserNotifyProps({channel: 'false'}); const channelMemberNotifyProps5 = TestHelper.fakeChannelNotifyProps({ignore_channel_mentions: Users.IGNORE_CHANNEL_MENTIONS_OFF as 'off'}); expect(areChannelMentionsIgnored(channelMemberNotifyProps5, currentUserNotifyProps5)).toBe(false); const currentUserNotifyProps6 = TestHelper.fakeUserNotifyProps({channel: 'false'}); const channelMemberNotifyProps6 = TestHelper.fakeChannelNotifyProps({ignore_channel_mentions: Users.IGNORE_CHANNEL_MENTIONS_ON as 'on'}); expect(areChannelMentionsIgnored(channelMemberNotifyProps6, currentUserNotifyProps6)).toBe(true); const currentUserNotifyProps7 = TestHelper.fakeUserNotifyProps({channel: 'true'}); const channelMemberNotifyProps7 = null as unknown as ChannelNotifyProps; expect(areChannelMentionsIgnored(channelMemberNotifyProps7, currentUserNotifyProps7)).toBe(false); const currentUserNotifyProps8 = TestHelper.fakeUserNotifyProps({channel: false as unknown as 'false'}); const channelMemberNotifyProps8 = null as unknown as ChannelNotifyProps; expect(areChannelMentionsIgnored(channelMemberNotifyProps8, currentUserNotifyProps8)).toBe(false); }); it('filterChannelsMatchingTerm', () => { const channel1 = TestHelper.fakeChannel(''); channel1.display_name = 'channel1'; channel1.name = 'blargh1'; const channel2 = TestHelper.fakeChannel(''); channel2.display_name = 'channel2'; channel2.name = 'blargh2'; const channels = [channel1, channel2]; expect(filterChannelsMatchingTerm(channels, 'chan')).toEqual(channels); expect(filterChannelsMatchingTerm(channels, 'CHAN')).toEqual(channels); expect(filterChannelsMatchingTerm(channels, 'blargh')).toEqual(channels); expect(filterChannelsMatchingTerm(channels, 'channel1')).toEqual([channel1]); expect(filterChannelsMatchingTerm(channels, 'junk')).toEqual([]); expect(filterChannelsMatchingTerm(channels, 'annel')).toEqual([]); }); it('sortChannelsByRecency', () => { const channelA = TestHelper.fakeChannel(''); channelA.id = 'channel_a'; channelA.last_post_at = 1; const channelB = TestHelper.fakeChannel(''); channelB.last_post_at = 2; channelB.id = 'channel_b'; // sorting depends on channel's last_post_at when both channels don't have last post expect(sortChannelsByRecency({}, channelA, channelB)).toBe(1); // sorting depends on create_at of channel's last post if it's greater than the channel's last_post_at const lastPosts: Record<string, Post> = { channel_a: TestHelper.fakePostOverride({id: 'post_id_1', create_at: 5, update_at: 5}), channel_b: TestHelper.fakePostOverride({id: 'post_id_2', create_at: 7, update_at: 7}), }; // should return 2, comparison of create_at (7 - 5) expect(sortChannelsByRecency(lastPosts, channelA, channelB)).toBe(2); // sorting remains the same even if channel's last post is updated (e.g. edited, updated reaction, etc) lastPosts.channel_a.update_at = 10; // should return 2, comparison of create_at (7 - 5) expect(sortChannelsByRecency(lastPosts, channelA, channelB)).toBe(2); // sorting depends on create_at of channel's last post if it's greater than the channel's last_post_at lastPosts.channel_a.create_at = 10; // should return 2, comparison of create_at (7 - 10) expect(sortChannelsByRecency(lastPosts, channelA, channelB)).toBe(-3); }); it('sortChannelsByDisplayName', () => { const channelA = TestHelper.fakeChannelOverride({ name: 'channelA', team_id: 'teamId', display_name: 'Unit Test channelA', type: 'O', delete_at: 0, }); const channelB = TestHelper.fakeChannelOverride({ name: 'channelB', team_id: 'teamId', display_name: 'Unit Test channelB', type: 'O', delete_at: 0, }); expect(sortChannelsByDisplayName('en', channelA, channelB)).toBe(-1); expect(sortChannelsByDisplayName('en', channelB, channelA)).toBe(1); // When a channel does not have a display name set Reflect.deleteProperty(channelB, 'display_name'); expect(sortChannelsByDisplayName('en', channelA, channelB)).toBe(-1); expect(sortChannelsByDisplayName('en', channelB, channelA)).toBe(1); }); it('sortChannelsByTypeListAndDisplayName', () => { const channelOpen1 = TestHelper.fakeChannelOverride({ name: 'channelA', team_id: 'teamId', display_name: 'Unit Test channelA', type: General.OPEN_CHANNEL, delete_at: 0, }); const channelOpen2 = TestHelper.fakeChannelOverride({ name: 'channelB', team_id: 'teamId', display_name: 'Unit Test channelB', type: General.OPEN_CHANNEL, delete_at: 0, }); const channelPrivate = TestHelper.fakeChannelOverride({ name: 'channelC', team_id: 'teamId', display_name: 'Unit Test channelC', type: General.PRIVATE_CHANNEL, delete_at: 0, }); const channelDM = TestHelper.fakeChannelOverride({ name: 'channelD', team_id: 'teamId', display_name: 'Unit Test channelD', type: General.DM_CHANNEL, delete_at: 0, }); const channelGM = TestHelper.fakeChannelOverride({ name: 'channelE', team_id: 'teamId', display_name: 'Unit Test channelE', type: General.GM_CHANNEL, delete_at: 0, }); let sortfn = sortChannelsByTypeListAndDisplayName.bind(null, 'en', [General.OPEN_CHANNEL, General.PRIVATE_CHANNEL, General.DM_CHANNEL, General.GM_CHANNEL]); const actual = [channelOpen1, channelPrivate, channelDM, channelGM, channelOpen2].sort(sortfn); const expected = [channelOpen1, channelOpen2, channelPrivate, channelDM, channelGM]; expect(actual).toEqual(expected); // Skipped Open Channel type should sort last but open channels should still sort in alphabetical order sortfn = sortChannelsByTypeListAndDisplayName.bind(null, 'en', [General.DM_CHANNEL, General.GM_CHANNEL, General.PRIVATE_CHANNEL]); const actualOutput = JSON.stringify([channelOpen1, channelPrivate, channelDM, channelGM, channelOpen2].sort(sortfn)); const expectedOutput = JSON.stringify([channelDM, channelGM, channelPrivate, channelOpen1, channelOpen2]); expect(actualOutput).toEqual(expectedOutput); }); });
4,126
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/emoji_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as EmojiUtils from 'mattermost-redux/utils/emoji_utils'; import TestHelper from '../../test/test_helper'; describe('EmojiUtils', () => { describe('parseEmojiNamesFromText', () => { test('should return empty array for text without emojis', () => { const actual = EmojiUtils.parseEmojiNamesFromText( 'This has no emojis', ); const expected: string[] = []; expect(actual).toEqual(expected); }); test('should return anything that looks like an emoji', () => { const actual = EmojiUtils.parseEmojiNamesFromText( ':this: :is_all: :emo-jis: :123:', ); const expected = ['this', 'is_all', 'emo-jis', '123']; expect(actual).toEqual(expected); }); test('should correctly handle text surrounding emojis', () => { const actual = EmojiUtils.parseEmojiNamesFromText( ':this:/:is_all: (:emo-jis:) surrounding:123:text:456:asdf', ); const expected = ['this', 'is_all', 'emo-jis', '123', '456']; expect(actual).toEqual(expected); }); test('should not return duplicates', () => { const actual = EmojiUtils.parseEmojiNamesFromText( ':emoji: :emoji: :emoji: :emoji:', ); const expected = ['emoji']; expect(actual).toEqual(expected); }); }); describe('isSystemEmoji', () => { test('correctly identifies system emojis with category', () => { const sampleEmoji = TestHelper.getSystemEmojiMock({ unified: 'z1z1z1', name: 'sampleEmoji', category: 'activities', short_names: ['sampleEmoji'], short_name: 'sampleEmoji', batch: 2, image: 'sampleEmoji.png', }); expect(EmojiUtils.isSystemEmoji(sampleEmoji)).toBe(true); }); test('correctly identifies system emojis without category', () => { const sampleEmoji = TestHelper.getSystemEmojiMock({ unified: 'z1z1z1', name: 'sampleEmoji', short_names: ['sampleEmoji'], short_name: 'sampleEmoji', batch: 2, image: 'sampleEmoji.png', }); expect(EmojiUtils.isSystemEmoji(sampleEmoji)).toBe(true); }); test('correctly identifies custom emojis with category and without id', () => { const sampleEmoji = TestHelper.getCustomEmojiMock({ category: 'custom', }); expect(EmojiUtils.isSystemEmoji(sampleEmoji)).toBe(false); }); test('correctly identifies custom emojis without category and with id', () => { const sampleEmoji = TestHelper.getCustomEmojiMock({ id: 'sampleEmoji', }); expect(EmojiUtils.isSystemEmoji(sampleEmoji)).toBe(false); }); test('correctly identifies custom emojis with category and with id', () => { const sampleEmoji = TestHelper.getCustomEmojiMock({ id: 'sampleEmoji', category: 'custom', }); expect(EmojiUtils.isSystemEmoji(sampleEmoji)).toBe(false); }); }); describe('getEmojiImageUrl', () => { test('returns correct url for system emojis', () => { expect(EmojiUtils.getEmojiImageUrl(TestHelper.getSystemEmojiMock({unified: 'system_emoji'}))).toBe('/static/emoji/system_emoji.png'); expect(EmojiUtils.getEmojiImageUrl(TestHelper.getSystemEmojiMock({short_names: ['system_emoji_short_names']}))).toBe('/static/emoji/system_emoji_short_names.png'); }); test('return correct url for mattermost emoji', () => { expect(EmojiUtils.getEmojiImageUrl(TestHelper.getCustomEmojiMock({id: 'mattermost', category: 'custom'}))).toBe('/static/emoji/mattermost.png'); expect(EmojiUtils.getEmojiImageUrl(TestHelper.getCustomEmojiMock({id: 'mattermost'}))).toBe('/static/emoji/mattermost.png'); }); test('return correct url for custom emojis', () => { expect(EmojiUtils.getEmojiImageUrl(TestHelper.getCustomEmojiMock({id: 'custom_emoji', category: 'custom'}))).toBe('/api/v4/emoji/custom_emoji/image'); expect(EmojiUtils.getEmojiImageUrl(TestHelper.getCustomEmojiMock({id: 'custom_emoji'}))).toBe('/api/v4/emoji/custom_emoji/image'); }); }); });
4,129
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/file_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {Client4} from 'mattermost-redux/client'; import * as FileUtils from 'mattermost-redux/utils/file_utils'; import TestHelper from '../../test/test_helper'; describe('FileUtils', () => { const serverUrl = Client4.getUrl(); beforeEach(() => { Client4.setUrl('localhost'); }); afterEach(() => { Client4.setUrl(serverUrl); }); it('getFileUrl', () => { expect(FileUtils.getFileUrl('id1')).toEqual('localhost/api/v4/files/id1'); expect(FileUtils.getFileUrl('id2')).toEqual('localhost/api/v4/files/id2'); }); it('getFileDownloadUrl', () => { expect(FileUtils.getFileDownloadUrl('id1')).toEqual('localhost/api/v4/files/id1?download=1'); expect(FileUtils.getFileDownloadUrl('id2')).toEqual('localhost/api/v4/files/id2?download=1'); }); it('getFileThumbnailUrl', () => { expect(FileUtils.getFileThumbnailUrl('id1')).toEqual('localhost/api/v4/files/id1/thumbnail'); expect(FileUtils.getFileThumbnailUrl('id2')).toEqual('localhost/api/v4/files/id2/thumbnail'); }); it('getFilePreviewUrl', () => { expect(FileUtils.getFilePreviewUrl('id1')).toEqual('localhost/api/v4/files/id1/preview'); expect(FileUtils.getFilePreviewUrl('id2')).toEqual('localhost/api/v4/files/id2/preview'); }); it('getFileMiniPreviewUrl', () => { expect(FileUtils.getFileMiniPreviewUrl(TestHelper.getFileInfoMock({}))).toEqual(undefined); expect(FileUtils.getFileMiniPreviewUrl(TestHelper.getFileInfoMock({mime_type: 'mime_type', mini_preview: 'mini_preview'}))).toEqual('data:mime_type;base64,mini_preview'); }); it('sortFileInfos', () => { const testCases = [ { inputFileInfos: [ TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), ], outputFileInfos: [ TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), ], }, { inputFileInfos: [ TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), ], outputFileInfos: [ TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), ], }, { inputFileInfos: [ TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), TestHelper.getFileInfoMock({name: 'ccc', create_at: 300}), ], outputFileInfos: [ TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), TestHelper.getFileInfoMock({name: 'ccc', create_at: 300}), ], }, { inputFileInfos: [ TestHelper.getFileInfoMock({name: 'ccc', create_at: 300}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), ], outputFileInfos: [ TestHelper.getFileInfoMock({name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({name: 'bbb', create_at: 200}), TestHelper.getFileInfoMock({name: 'ccc', create_at: 300}), ], }, { inputFileInfos: [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'aaa', create_at: 200}), ], outputFileInfos: [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'aaa', create_at: 200}), ], }, { inputFileInfos: [ TestHelper.getFileInfoMock({id: '2', name: 'aaa', create_at: 200}), TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), ], outputFileInfos: [ TestHelper.getFileInfoMock({id: '1', name: 'aaa', create_at: 100}), TestHelper.getFileInfoMock({id: '2', name: 'aaa', create_at: 200}), ], }, ]; testCases.forEach((testCase) => { expect(FileUtils.sortFileInfos(testCase.inputFileInfos)).toEqual(testCase.outputFileInfos); }); }); });
4,131
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/group_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { filterGroupsMatchingTerm, } from './group_utils'; describe('group utils', () => { describe('filterGroupsMatchingTerm', () => { const groupA = { id: 'groupid1', name: 'board-group', description: 'group1 description', display_name: 'board-group', source: 'ldap', remote_id: 'group1', create_at: 1, update_at: 2, delete_at: 0, has_syncables: true, member_count: 3, scheme_admin: false, allow_reference: true, }; const groupB = { id: 'groupid2', name: 'developers-group', description: 'group2 description', display_name: 'developers-group', source: 'ldap', remote_id: 'group2', create_at: 1, update_at: 2, delete_at: 0, has_syncables: true, member_count: 3, scheme_admin: false, allow_reference: true, }; const groupC = { id: 'groupid3', name: 'software-engineers', description: 'group3 description', display_name: 'software engineers', source: 'ldap', remote_id: 'group3', create_at: 1, update_at: 2, delete_at: 0, has_syncables: true, member_count: 3, scheme_admin: false, allow_reference: true, }; const groups = [groupA, groupB, groupC]; it('should match all for empty filter', () => { expect(filterGroupsMatchingTerm(groups, '')).toEqual([groupA, groupB, groupC]); }); it('should filter out results which do not match', () => { expect(filterGroupsMatchingTerm(groups, 'testBad')).toEqual([]); }); it('should match by name', () => { expect(filterGroupsMatchingTerm(groups, 'software-engineers')).toEqual([groupC]); }); it('should match by split part of the name', () => { expect(filterGroupsMatchingTerm(groups, 'group')).toEqual([groupA, groupB]); expect(filterGroupsMatchingTerm(groups, 'board')).toEqual([groupA]); }); it('should match by display_name fully', () => { expect(filterGroupsMatchingTerm(groups, 'software engineers')).toEqual([groupC]); }); it('should match by display_name case-insensitive', () => { expect(filterGroupsMatchingTerm(groups, 'software ENGINEERS')).toEqual([groupC]); }); it('should ignore leading @ for name', () => { expect(filterGroupsMatchingTerm(groups, '@developers')).toEqual([groupB]); }); it('should ignore leading @ for display_name', () => { expect(filterGroupsMatchingTerm(groups, '@software')).toEqual([groupC]); }); }); });
4,133
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/helpers.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {isMinimumServerVersion, isEmail} from 'mattermost-redux/utils/helpers'; describe('Helpers', () => { it('isMinimumServerVersion', () => { expect(isMinimumServerVersion('1.0.0', 1, 0, 0)).toBeTruthy(); expect(isMinimumServerVersion('1.1.1', 1, 1, 1)).toBeTruthy(); expect(!isMinimumServerVersion('1.0.0', 2, 0, 0)).toBeTruthy(); expect(isMinimumServerVersion('4.6', 2, 0, 0)).toBeTruthy(); expect(!isMinimumServerVersion('4.6', 4, 7, 0)).toBeTruthy(); expect(isMinimumServerVersion('4.6.1', 2, 0, 0)).toBeTruthy(); expect(isMinimumServerVersion('4.7.1', 4, 6, 2)).toBeTruthy(); expect(!isMinimumServerVersion('4.6.1', 4, 6, 2)).toBeTruthy(); expect(!isMinimumServerVersion('3.6.1', 4, 6, 2)).toBeTruthy(); expect(isMinimumServerVersion('4.6.1', 3, 7, 2)).toBeTruthy(); expect(isMinimumServerVersion('5', 4, 6, 2)).toBeTruthy(); expect(isMinimumServerVersion('5', 5)).toBeTruthy(); expect(isMinimumServerVersion('5.1', 5)).toBeTruthy(); expect(isMinimumServerVersion('5.1', 5, 1)).toBeTruthy(); expect(!isMinimumServerVersion('5.1', 5, 2)).toBeTruthy(); expect(isMinimumServerVersion('5.1.0', 5)).toBeTruthy(); expect(isMinimumServerVersion('5.1.1', 5, 1, 1)).toBeTruthy(); expect(!isMinimumServerVersion('5.1.1', 5, 1, 2)).toBeTruthy(); expect(isMinimumServerVersion('4.6.2.sakjdgaksfg', 4, 6, 2)).toBeTruthy(); expect(!isMinimumServerVersion('')).toBeTruthy(); }); }); describe('Utils.isEmail', () => { it('', () => { for (const data of [ { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: 'admin@mailserver1', valid: true, }, { email: '#!$%&\'*+-/=?^_`{}|[email protected]', valid: true, }, { email: '[email protected]', valid: true, }, { email: 'Abc.example.com', valid: false, }, { email: 'A@b@[email protected]', valid: false, }, { email: '<testing> [email protected]', valid: false, }, { email: 'test <[email protected]>', valid: false, }, { email: '[email protected], [email protected]', valid: false, }, { email: '[email protected],[email protected]', valid: false, }, ]) { expect(isEmail(data.email)).toBe(data.valid); } }); });
4,135
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/i18n_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {setLocalizeFunction, localizeMessage} from 'mattermost-redux/utils/i18n_utils'; describe('i18n utils', () => { afterEach(() => { setLocalizeFunction(null as any); }); it('should return default message', () => { expect(localizeMessage('someting.string', 'defaultString')).toBe('defaultString'); }); it('should return previously set Localized function return value', () => { function mockFunc() { return 'test'; } setLocalizeFunction(mockFunc); expect(localizeMessage('someting.string', 'defaultString')).toBe('test'); }); });
4,137
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/integration_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {checkDialogElementForError, checkIfErrorsMatchElements} from 'mattermost-redux/utils/integration_utils'; import TestHelper from '../../test/test_helper'; describe('integration utils', () => { describe('checkDialogElementForError', () => { it('should return null error on optional text element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', optional: true}), undefined)).toBe(null); }); it('should return null error on optional textarea element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'textarea', optional: true}), undefined)).toBe(null); }); it('should return error on required element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', optional: false}), undefined)!.id).toBe('interactive_dialog.error.required'); }); it('should return error on too short text element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', min_length: 5}), '123')!.id).toBe('interactive_dialog.error.too_short'); }); it('should return null on 0', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'number'}), 0)).toBe(null); }); it('should return null on good number element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'number'}), '123')).toBe(null); }); it('should return error on bad number element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'number'}), 'totallyanumber')!.id).toBe('interactive_dialog.error.bad_number'); }); it('should return null on good email element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'email'}), '[email protected]')).toBe(null); }); it('should return error on bad email element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'email'}), 'totallyanemail')!.id).toBe('interactive_dialog.error.bad_email'); }); it('should return null on good url element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'url'}), 'http://mattermost.com')).toBe(null); expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'url'}), 'https://mattermost.com')).toBe(null); }); it('should return error on bad url element', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'text', subtype: 'url'}), 'totallyawebsite')!.id).toBe('interactive_dialog.error.bad_url'); }); it('should return null when value is in the options', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'radio', options: [{text: '', value: 'Sales'}]}), 'Sales')).toBe(null); }); it('should return error when value is not in the options', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'radio', options: [{text: '', value: 'Sales'}]}), 'Sale')!.id).toBe('interactive_dialog.error.invalid_option'); }); it('should return error when value is falsey and not on the list of options', () => { expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'radio', options: [{text: '', value: false}]}), 'Sale')!.id).toBe('interactive_dialog.error.invalid_option'); expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'radio', options: [{text: '', value: undefined}]}), 'Sale')!.id).toBe('interactive_dialog.error.invalid_option'); expect(checkDialogElementForError(TestHelper.getDialogElementMock({type: 'radio', options: [{text: '', value: null}]}), 'Sale')!.id).toBe('interactive_dialog.error.invalid_option'); }); }); describe('checkIfErrorsMatchElements', () => { it('should pass as returned error matches an element', () => { expect(checkIfErrorsMatchElements({name1: 'some error'} as any, [TestHelper.getDialogElementMock({name: 'name1'})])).toBeTruthy(); expect(checkIfErrorsMatchElements({name1: 'some error'} as any, [TestHelper.getDialogElementMock({name: 'name1'}), TestHelper.getDialogElementMock({name: 'name2'})])).toBeTruthy(); }); it('should fail as returned errors do not match an element', () => { expect(!checkIfErrorsMatchElements({name17: 'some error'} as any, [TestHelper.getDialogElementMock({name: 'name1'}), TestHelper.getDialogElementMock({name: 'name2'})])).toBeTruthy(); }); }); });
4,141
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/notify_props.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {getEmailInterval} from 'mattermost-redux/utils/notify_props'; import {Preferences} from '../constants'; describe('user utils', () => { const testCases = [ {enableEmail: false, enableBatching: true, intervalPreference: Preferences.INTERVAL_IMMEDIATE, out: Preferences.INTERVAL_NEVER}, {enableEmail: true, enableBatching: true, intervalPreference: undefined as any, out: Preferences.INTERVAL_FIFTEEN_MINUTES}, {enableEmail: true, enableBatching: true, intervalPreference: Preferences.INTERVAL_IMMEDIATE, out: Preferences.INTERVAL_IMMEDIATE}, {enableEmail: true, enableBatching: true, intervalPreference: Preferences.INTERVAL_NEVER, out: Preferences.INTERVAL_IMMEDIATE}, {enableEmail: true, enableBatching: true, intervalPreference: Preferences.INTERVAL_FIFTEEN_MINUTES, out: Preferences.INTERVAL_FIFTEEN_MINUTES}, {enableEmail: true, enableBatching: true, intervalPreference: Preferences.INTERVAL_HOUR, out: Preferences.INTERVAL_HOUR}, {enableEmail: true, enableBatching: false, intervalPreference: undefined as any, out: Preferences.INTERVAL_IMMEDIATE}, {enableEmail: true, enableBatching: false, intervalPreference: Preferences.INTERVAL_IMMEDIATE, out: Preferences.INTERVAL_IMMEDIATE}, {enableEmail: true, enableBatching: false, intervalPreference: Preferences.INTERVAL_NEVER, out: Preferences.INTERVAL_IMMEDIATE}, {enableEmail: true, enableBatching: false, intervalPreference: Preferences.INTERVAL_FIFTEEN_MINUTES, out: Preferences.INTERVAL_IMMEDIATE}, {enableEmail: true, enableBatching: false, intervalPreference: Preferences.INTERVAL_HOUR, out: Preferences.INTERVAL_IMMEDIATE}, ]; testCases.forEach((testCase) => { it(`getEmailInterval should return correct interval: getEmailInterval(${testCase.enableEmail}, ${testCase.enableBatching}, ${testCase.intervalPreference}) should return ${testCase.out}`, () => { expect(getEmailInterval(testCase.enableEmail, testCase.enableBatching, testCase.intervalPreference)).toEqual(testCase.out); }); }); });
4,143
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/post_list.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ActivityEntry, Post} from '@mattermost/types/posts'; import type {GlobalState} from '@mattermost/types/store'; import deepFreeze from 'mattermost-redux/utils/deep_freeze'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import { COMBINED_USER_ACTIVITY, combineUserActivitySystemPost, DATE_LINE, getDateForDateLine, getFirstPostId, getLastPostId, getLastPostIndex, getPostIdsForCombinedUserActivityPost, isCombinedUserActivityPost, isDateLine, makeCombineUserActivityPosts, makeFilterPostsAndAddSeparators, makeGenerateCombinedPost, extractUserActivityData, START_OF_NEW_MESSAGES, shouldShowJoinLeaveMessages, } from './post_list'; import TestHelper from '../../test/test_helper'; import {Posts, Preferences} from '../constants'; describe('makeFilterPostsAndAddSeparators', () => { it('filter join/leave posts', () => { const filterPostsAndAddSeparators = makeFilterPostsAndAddSeparators(); const time = Date.now(); const today = new Date(time); let state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'true', }, }, posts: { posts: { 1001: {id: '1001', create_at: time, type: ''}, 1002: {id: '1002', create_at: time + 1, type: Posts.POST_TYPES.JOIN_CHANNEL}, }, }, preferences: { myPreferences: {}, }, users: { currentUserId: '1234', profiles: { 1234: {id: '1234', username: 'user'}, }, }, }, } as unknown as GlobalState; const lastViewedAt = Number.POSITIVE_INFINITY; const postIds = ['1002', '1001']; const indicateNewMessages = true; // Defaults to show post let now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages}); expect(now).toEqual([ '1002', '1001', 'date-' + today.getTime(), ]); // Show join/leave posts state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_FILTER_JOIN_LEAVE)]: { category: Preferences.CATEGORY_ADVANCED_SETTINGS, name: Preferences.ADVANCED_FILTER_JOIN_LEAVE, value: 'true', }, } as GlobalState['entities']['preferences']['myPreferences'], }, }, }; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages}); expect(now).toEqual([ '1002', '1001', 'date-' + today.getTime(), ]); // Hide join/leave posts state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_FILTER_JOIN_LEAVE)]: { category: Preferences.CATEGORY_ADVANCED_SETTINGS, name: Preferences.ADVANCED_FILTER_JOIN_LEAVE, value: 'false', }, } as GlobalState['entities']['preferences']['myPreferences'], }, }, }; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages}); expect(now).toEqual([ '1001', 'date-' + today.getTime(), ]); // always show join/leave posts for the current user state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, 1002: {id: '1002', create_at: time + 1, type: Posts.POST_TYPES.JOIN_CHANNEL, props: {username: 'user'}}, }, }, }, } as unknown as GlobalState; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages}); expect(now).toEqual([ '1002', '1001', 'date-' + today.getTime(), ]); }); it('new messages indicator', () => { const filterPostsAndAddSeparators = makeFilterPostsAndAddSeparators(); const time = Date.now(); const today = new Date(time); const state = { entities: { general: { config: {}, }, posts: { posts: { 1000: {id: '1000', create_at: time + 1000, type: ''}, 1005: {id: '1005', create_at: time + 1005, type: ''}, 1010: {id: '1010', create_at: time + 1010, type: ''}, }, }, preferences: { myPreferences: {}, }, users: { currentUserId: '1234', profiles: { 1234: {id: '1234', username: 'user'}, }, }, }, } as unknown as GlobalState; const postIds = ['1010', '1005', '1000']; // Remember that we list the posts backwards // Do not show new messages indicator before all posts let now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt: 0, indicateNewMessages: true}); expect(now).toEqual([ '1010', '1005', '1000', 'date-' + (today.getTime() + 1000), ]); now = filterPostsAndAddSeparators(state, {postIds, indicateNewMessages: true, lastViewedAt: 0}); expect(now).toEqual([ '1010', '1005', '1000', 'date-' + (today.getTime() + 1000), ]); now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt: time + 999, indicateNewMessages: false}); expect(now).toEqual([ '1010', '1005', '1000', 'date-' + (today.getTime() + 1000), ]); // Show new messages indicator before all posts now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt: time + 999, indicateNewMessages: true}); expect(now).toEqual([ '1010', '1005', '1000', START_OF_NEW_MESSAGES, 'date-' + (today.getTime() + 1000), ]); // Show indicator between posts now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt: time + 1003, indicateNewMessages: true}); expect(now).toEqual([ '1010', '1005', START_OF_NEW_MESSAGES, '1000', 'date-' + (today.getTime() + 1000), ]); now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt: time + 1006, indicateNewMessages: true}); expect(now).toEqual([ '1010', START_OF_NEW_MESSAGES, '1005', '1000', 'date-' + (today.getTime() + 1000), ]); // Don't show indicator when all posts are read now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt: time + 1020}); expect(now).toEqual([ '1010', '1005', '1000', 'date-' + (today.getTime() + 1000), ]); }); it('memoization', () => { const filterPostsAndAddSeparators = makeFilterPostsAndAddSeparators(); const time = Date.now(); const today = new Date(time); const tomorrow = new Date((24 * 60 * 60 * 1000) + today.getTime()); // Posts 7 hours apart so they should appear on multiple days const initialPosts = { 1001: {id: '1001', create_at: time, type: ''}, 1002: {id: '1002', create_at: time + 5, type: ''}, 1003: {id: '1003', create_at: time + 10, type: ''}, 1004: {id: '1004', create_at: tomorrow, type: ''}, 1005: {id: '1005', create_at: tomorrow as any + 5, type: ''}, 1006: {id: '1006', create_at: tomorrow as any + 10, type: Posts.POST_TYPES.JOIN_CHANNEL}, }; let state = { entities: { general: { config: {}, }, posts: { posts: initialPosts, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_FILTER_JOIN_LEAVE)]: { category: Preferences.CATEGORY_ADVANCED_SETTINGS, name: Preferences.ADVANCED_FILTER_JOIN_LEAVE, value: 'true', }, }, }, users: { currentUserId: '1234', profiles: { 1234: {id: '1234', username: 'user'}, }, }, }, } as unknown as GlobalState; let postIds = [ '1006', '1004', '1003', '1001', ]; let lastViewedAt = initialPosts['1001'].create_at + 1; let now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual([ '1006', '1004', 'date-' + tomorrow.getTime(), '1003', START_OF_NEW_MESSAGES, '1001', 'date-' + today.getTime(), ]); // No changes let prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1006', '1004', 'date-' + tomorrow.getTime(), '1003', START_OF_NEW_MESSAGES, '1001', 'date-' + today.getTime(), ]); // lastViewedAt changed slightly lastViewedAt = initialPosts['1001'].create_at + 2; prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1006', '1004', 'date-' + tomorrow.getTime(), '1003', START_OF_NEW_MESSAGES, '1001', 'date-' + today.getTime(), ]); // lastViewedAt changed a lot lastViewedAt = initialPosts['1003'].create_at + 1; prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).not.toEqual(prev); expect(now).toEqual([ '1006', '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1006', '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); // postIds changed, but still shallowly equal postIds = [...postIds]; prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1006', '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); // Post changed, not in postIds state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, 1007: {id: '1007', create_at: 7 * 60 * 60 * 7 * 1000}, }, }, }, } as unknown as GlobalState; prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1006', '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); // Post changed, in postIds state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, 1006: {...state.entities.posts.posts['1006'], message: 'abcd'}, }, }, }, }; prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1006', '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); // Filter changed state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_FILTER_JOIN_LEAVE)]: { category: Preferences.CATEGORY_ADVANCED_SETTINGS, name: Preferences.ADVANCED_FILTER_JOIN_LEAVE, value: 'false', }, } as unknown as GlobalState['entities']['preferences']['myPreferences'], }, }, }; prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).not.toEqual(prev); expect(now).toEqual([ '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); prev = now; now = filterPostsAndAddSeparators(state, {postIds, lastViewedAt, indicateNewMessages: true}); expect(now).toEqual(prev); expect(now).toEqual([ '1004', START_OF_NEW_MESSAGES, 'date-' + tomorrow.getTime(), '1003', '1001', 'date-' + today.getTime(), ]); }); }); describe('makeCombineUserActivityPosts', () => { test('should do nothing if no post IDs are provided', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds: string[] = []; const state = { entities: { posts: { posts: {}, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).toBe(postIds); expect(result).toEqual([]); }); test('should do nothing if there are no user activity posts', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds = deepFreeze([ 'post1', START_OF_NEW_MESSAGES, 'post2', DATE_LINE + '1001', 'post3', DATE_LINE + '1000', ]); const state = { entities: { posts: { posts: { post1: {id: 'post1'}, post2: {id: 'post2'}, post3: {id: 'post3'}, }, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).toBe(postIds); }); test('should combine adjacent user activity posts', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds = deepFreeze([ 'post1', 'post2', 'post3', ]); const state = { entities: { posts: { posts: { post1: {id: 'post1', type: Posts.POST_TYPES.JOIN_CHANNEL}, post2: {id: 'post2', type: Posts.POST_TYPES.LEAVE_CHANNEL}, post3: {id: 'post3', type: Posts.POST_TYPES.ADD_TO_CHANNEL}, }, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).not.toBe(postIds); expect(result).toEqual([ COMBINED_USER_ACTIVITY + 'post1_post2_post3', ]); }); test('should "combine" a single activity post', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds = deepFreeze([ 'post1', 'post2', 'post3', ]); const state = { entities: { posts: { posts: { post1: {id: 'post1'}, post2: {id: 'post2', type: Posts.POST_TYPES.LEAVE_CHANNEL}, post3: {id: 'post3'}, }, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).not.toBe(postIds); expect(result).toEqual([ 'post1', COMBINED_USER_ACTIVITY + 'post2', 'post3', ]); }); test('should not combine with regular messages', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds = deepFreeze([ 'post1', 'post2', 'post3', 'post4', 'post5', ]); const state = { entities: { posts: { posts: { post1: {id: 'post1', type: Posts.POST_TYPES.JOIN_CHANNEL}, post2: {id: 'post2', type: Posts.POST_TYPES.JOIN_CHANNEL}, post3: {id: 'post3'}, post4: {id: 'post4', type: Posts.POST_TYPES.ADD_TO_CHANNEL}, post5: {id: 'post5', type: Posts.POST_TYPES.ADD_TO_CHANNEL}, }, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).not.toBe(postIds); expect(result).toEqual([ COMBINED_USER_ACTIVITY + 'post1_post2', 'post3', COMBINED_USER_ACTIVITY + 'post4_post5', ]); }); test('should not combine with other system messages', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds = deepFreeze([ 'post1', 'post2', 'post3', ]); const state = { entities: { posts: { posts: { post1: {id: 'post1', type: Posts.POST_TYPES.JOIN_CHANNEL}, post2: {id: 'post2', type: Posts.POST_TYPES.PURPOSE_CHANGE}, post3: {id: 'post3', type: Posts.POST_TYPES.ADD_TO_CHANNEL}, }, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).not.toBe(postIds); expect(result).toEqual([ COMBINED_USER_ACTIVITY + 'post1', 'post2', COMBINED_USER_ACTIVITY + 'post3', ]); }); test('should not combine across non-post items', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds = deepFreeze([ 'post1', START_OF_NEW_MESSAGES, 'post2', 'post3', DATE_LINE + '1001', 'post4', ]); const state = { entities: { posts: { posts: { post1: {id: 'post1', type: Posts.POST_TYPES.JOIN_CHANNEL}, post2: {id: 'post2', type: Posts.POST_TYPES.LEAVE_CHANNEL}, post3: {id: 'post3', type: Posts.POST_TYPES.ADD_TO_CHANNEL}, post4: {id: 'post4', type: Posts.POST_TYPES.JOIN_CHANNEL}, }, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).not.toBe(postIds); expect(result).toEqual([ COMBINED_USER_ACTIVITY + 'post1', START_OF_NEW_MESSAGES, COMBINED_USER_ACTIVITY + 'post2_post3', DATE_LINE + '1001', COMBINED_USER_ACTIVITY + 'post4', ]); }); test('should not combine more than 100 posts', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); const postIds: string[] = []; const posts: Record<string, Post> = {}; for (let i = 0; i < 110; i++) { const postId = `post${i}`; postIds.push(postId); posts[postId] = TestHelper.getPostMock({id: postId, type: Posts.POST_TYPES.JOIN_CHANNEL}); } const state = { entities: { posts: { posts, }, }, } as unknown as GlobalState; const result = combineUserActivityPosts(state, postIds); expect(result).toHaveLength(2); }); describe('memoization', () => { const initialPostIds = ['post1', 'post2']; const initialState = { entities: { posts: { posts: { post1: {id: 'post1', type: Posts.POST_TYPES.JOIN_CHANNEL}, post2: {id: 'post2', type: Posts.POST_TYPES.JOIN_CHANNEL}, }, }, }, } as unknown as GlobalState; test('should not recalculate when nothing has changed', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); expect(combineUserActivityPosts.recomputations()).toBe(0); combineUserActivityPosts(initialState, initialPostIds); expect(combineUserActivityPosts.recomputations()).toBe(1); combineUserActivityPosts(initialState, initialPostIds); expect(combineUserActivityPosts.recomputations()).toBe(1); }); test('should recalculate when the post IDs change', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); let postIds = initialPostIds; combineUserActivityPosts(initialState, postIds); expect(combineUserActivityPosts.recomputations()).toBe(1); postIds = ['post1']; combineUserActivityPosts(initialState, postIds); expect(combineUserActivityPosts.recomputations()).toBe(2); }); test('should not recalculate when an unrelated state change occurs', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); let state = initialState; combineUserActivityPosts(state, initialPostIds); expect(combineUserActivityPosts.recomputations()).toBe(1); state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, selectedPostId: 'post2', }, }, }; combineUserActivityPosts(state, initialPostIds); expect(combineUserActivityPosts.recomputations()).toBe(1); }); test('should not recalculate if an unrelated post changes', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); let state = initialState; const initialResult = combineUserActivityPosts(state, initialPostIds); expect(combineUserActivityPosts.recomputations()).toBe(1); // An unrelated post changed state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, post3: TestHelper.getPostMock({id: 'post3'}), }, }, }, }; const result = combineUserActivityPosts(state, initialPostIds); // The selector didn't recalculate so the result didn't change expect(combineUserActivityPosts.recomputations()).toBe(1); expect(result).toBe(initialResult); }); test('should return the same result when a post changes in a way that doesn\'t affect the result', () => { const combineUserActivityPosts = makeCombineUserActivityPosts(); let state = initialState; const initialResult = combineUserActivityPosts(state, initialPostIds); expect(combineUserActivityPosts.recomputations()).toBe(1); // One of the posts was updated, but post type didn't change state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, post2: {...state.entities.posts.posts.post2, update_at: 1234}, }, }, }, }; let result = combineUserActivityPosts(state, initialPostIds); // The selector recalculated but is still returning the same array expect(combineUserActivityPosts.recomputations()).toBe(2); expect(result).toBe(initialResult); // One of the posts changed type state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, post2: {...state.entities.posts.posts.post2, type: ''}, }, }, }, }; result = combineUserActivityPosts(state, initialPostIds); // The selector recalculated, and the result changed expect(combineUserActivityPosts.recomputations()).toBe(3); expect(result).not.toBe(initialResult); }); }); }); describe('isDateLine', () => { test('should correctly identify date line items', () => { expect(isDateLine('')).toBe(false); expect(isDateLine('date')).toBe(false); expect(isDateLine('date-')).toBe(true); expect(isDateLine('date-0')).toBe(true); expect(isDateLine('date-1531152392')).toBe(true); expect(isDateLine('date-1531152392-index')).toBe(true); }); }); describe('getDateForDateLine', () => { test('should get date correctly without suffix', () => { expect(getDateForDateLine('date-1234')).toBe(1234); }); test('should get date correctly with suffix', () => { expect(getDateForDateLine('date-1234-suffix')).toBe(1234); }); }); describe('isCombinedUserActivityPost', () => { test('should correctly identify combined user activity posts', () => { expect(isCombinedUserActivityPost('post1')).toBe(false); expect(isCombinedUserActivityPost('date-1234')).toBe(false); expect(isCombinedUserActivityPost('user-activity-post1')).toBe(true); expect(isCombinedUserActivityPost('user-activity-post1_post2')).toBe(true); expect(isCombinedUserActivityPost('user-activity-post1_post2_post4')).toBe(true); }); }); describe('getPostIdsForCombinedUserActivityPost', () => { test('should get IDs correctly', () => { expect(getPostIdsForCombinedUserActivityPost('user-activity-post1_post2_post3')).toEqual(['post1', 'post2', 'post3']); }); }); describe('getFirstPostId', () => { test('should return the first item if it is a post', () => { expect(getFirstPostId(['post1', 'post2', 'post3'])).toBe('post1'); }); test('should return the first ID from a combined post', () => { expect(getFirstPostId(['user-activity-post2_post3', 'post4', 'user-activity-post5_post6'])).toBe('post2'); }); test('should skip date separators', () => { expect(getFirstPostId(['date-1234', 'user-activity-post1_post2', 'post3', 'post4', 'date-1000'])).toBe('post1'); }); test('should skip the new message line', () => { expect(getFirstPostId([START_OF_NEW_MESSAGES, 'post2', 'post3', 'post4'])).toBe('post2'); }); }); describe('getLastPostId', () => { test('should return the last item if it is a post', () => { expect(getLastPostId(['post1', 'post2', 'post3'])).toBe('post3'); }); test('should return the last ID from a combined post', () => { expect(getLastPostId(['user-activity-post2_post3', 'post4', 'user-activity-post5_post6'])).toBe('post6'); }); test('should skip date separators', () => { expect(getLastPostId(['date-1234', 'user-activity-post1_post2', 'post3', 'post4', 'date-1000'])).toBe('post4'); }); test('should skip the new message line', () => { expect(getLastPostId(['post2', 'post3', 'post4', START_OF_NEW_MESSAGES])).toBe('post4'); }); }); describe('getLastPostIndex', () => { test('should return index of last post for list of all regular posts', () => { expect(getLastPostIndex(['post1', 'post2', 'post3'])).toBe(2); }); test('should return index of last combined post', () => { expect(getLastPostIndex(['user-activity-post2_post3', 'post4', 'user-activity-post5_post6'])).toBe(2); }); test('should skip date separators and return index of last post', () => { expect(getLastPostIndex(['date-1234', 'user-activity-post1_post2', 'post3', 'post4', 'date-1000'])).toBe(3); }); test('should skip the new message line and return index of last post', () => { expect(getLastPostIndex(['post2', 'post3', 'post4', START_OF_NEW_MESSAGES])).toBe(2); }); }); describe('makeGenerateCombinedPost', () => { test('should output a combined post', () => { const generateCombinedPost = makeGenerateCombinedPost(); const state = { entities: { posts: { posts: { post1: { id: 'post1', channel_id: 'channel1', create_at: 1002, delete_at: 0, message: 'joe added to the channel by bill.', props: { addedUsername: 'joe', addedUserId: 'user2', username: 'bill', userId: 'user1', }, type: Posts.POST_TYPES.ADD_TO_CHANNEL, user_id: 'user1', metadata: {}, }, post2: { id: 'post2', channel_id: 'channel1', create_at: 1001, delete_at: 0, message: 'alice added to the channel by bill.', props: { addedUsername: 'alice', addedUserId: 'user3', username: 'bill', userId: 'user1', }, type: Posts.POST_TYPES.ADD_TO_CHANNEL, user_id: 'user1', metadata: {}, }, post3: { id: 'post3', channel_id: 'channel1', create_at: 1000, delete_at: 0, message: 'bill joined the channel.', props: { username: 'bill', userId: 'user1', }, type: Posts.POST_TYPES.JOIN_CHANNEL, user_id: 'user1', metadata: {}, }, }, }, }, } as unknown as GlobalState; const combinedId = 'user-activity-post1_post2_post3'; const result = generateCombinedPost(state, combinedId); expect(result).toMatchObject({ id: combinedId, root_id: '', channel_id: 'channel1', create_at: 1000, delete_at: 0, message: 'joe added to the channel by bill.\nalice added to the channel by bill.\nbill joined the channel.', props: { messages: [ 'joe added to the channel by bill.', 'alice added to the channel by bill.', 'bill joined the channel.', ], user_activity: { allUserIds: ['user1', 'user3', 'user2'], allUsernames: [ 'alice', 'joe', ], messageData: [ { postType: Posts.POST_TYPES.JOIN_CHANNEL, userIds: ['user1'], }, { postType: Posts.POST_TYPES.ADD_TO_CHANNEL, userIds: ['user3', 'user2'], actorId: 'user1', }, ], }, }, system_post_ids: ['post3', 'post2', 'post1'], type: Posts.POST_TYPES.COMBINED_USER_ACTIVITY, user_activity_posts: [ state.entities.posts.posts.post3, state.entities.posts.posts.post2, state.entities.posts.posts.post1, ], user_id: '', metadata: {}, }); }); describe('memoization', () => { const initialState = { entities: { posts: { posts: { post1: {id: 'post1'}, post2: {id: 'post2'}, }, }, }, } as unknown as GlobalState; const initialCombinedId = 'user-activity-post1_post2'; test('should not recalculate when called twice with the same ID', () => { const generateCombinedPost = makeGenerateCombinedPost(); expect((generateCombinedPost as any).recomputations()).toBe(0); generateCombinedPost(initialState, initialCombinedId); expect((generateCombinedPost as any).recomputations()).toBe(1); generateCombinedPost(initialState, initialCombinedId); expect((generateCombinedPost as any).recomputations()).toBe(1); }); test('should recalculate when called twice with different IDs', () => { const generateCombinedPost = makeGenerateCombinedPost(); expect((generateCombinedPost as any).recomputations()).toBe(0); let combinedId = initialCombinedId; generateCombinedPost(initialState, combinedId); expect((generateCombinedPost as any).recomputations()).toBe(1); combinedId = 'user-activity-post2'; generateCombinedPost(initialState, combinedId); expect((generateCombinedPost as any).recomputations()).toBe(2); }); test('should not recalculate when a different post changes', () => { const generateCombinedPost = makeGenerateCombinedPost(); expect((generateCombinedPost as any).recomputations()).toBe(0); let state = initialState; generateCombinedPost(state, initialCombinedId); expect((generateCombinedPost as any).recomputations()).toBe(1); state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, post3: TestHelper.getPostMock({id: 'post3'}), }, }, }, }; generateCombinedPost(state, initialCombinedId); expect((generateCombinedPost as any).recomputations()).toBe(2); }); test('should recalculate when one of the included posts change', () => { const generateCombinedPost = makeGenerateCombinedPost(); expect((generateCombinedPost as any).recomputations()).toBe(0); let state = initialState; generateCombinedPost(state, initialCombinedId); expect((generateCombinedPost as any).recomputations()).toBe(1); state = { ...state, entities: { ...state.entities, posts: { ...state.entities.posts, posts: { ...state.entities.posts.posts, post2: TestHelper.getPostMock({id: 'post2', update_at: 1234}), }, }, }, }; generateCombinedPost(state, initialCombinedId); expect((generateCombinedPost as any).recomputations()).toBe(2); }); }); }); const PostTypes = Posts.POST_TYPES; describe('extractUserActivityData', () => { const postAddToChannel: ActivityEntry = { postType: PostTypes.ADD_TO_CHANNEL, actorId: ['user_id_1'], userIds: ['added_user_id_1'], usernames: ['added_username_1'], }; const postAddToTeam: ActivityEntry = { postType: PostTypes.ADD_TO_TEAM, actorId: ['user_id_1'], userIds: ['added_user_id_1', 'added_user_id_2'], usernames: ['added_username_1', 'added_username_2'], }; const postLeaveChannel: ActivityEntry = { postType: PostTypes.LEAVE_CHANNEL, actorId: ['user_id_1'], userIds: [], usernames: [], }; const postJoinChannel: ActivityEntry = { postType: PostTypes.JOIN_CHANNEL, actorId: ['user_id_1'], userIds: [], usernames: [], }; const postRemoveFromChannel: ActivityEntry = { postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: ['user_id_1'], userIds: ['removed_user_id_1'], usernames: ['removed_username_1'], }; const postLeaveTeam: ActivityEntry = { postType: PostTypes.LEAVE_TEAM, actorId: ['user_id_1'], userIds: [], usernames: [], }; const postJoinTeam: ActivityEntry = { postType: PostTypes.JOIN_TEAM, actorId: ['user_id_1'], userIds: [], usernames: [], }; const postRemoveFromTeam: ActivityEntry = { postType: PostTypes.REMOVE_FROM_TEAM, actorId: ['user_id_1'], userIds: [], usernames: [], }; it('should return empty activity when empty ', () => { expect(extractUserActivityData([])).toEqual({allUserIds: [], allUsernames: [], messageData: []}); }); it('should match return for JOIN_CHANNEL', () => { const userActivities = [postJoinChannel]; const expectedOutput = { allUserIds: ['user_id_1'], allUsernames: [], messageData: [{postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postJoinChannel2: ActivityEntry = { postType: PostTypes.JOIN_CHANNEL, actorId: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], userIds: [], usernames: [], }; const expectedOutput2 = { allUserIds: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], allUsernames: [], messageData: [{postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5']}], }; expect(extractUserActivityData([postJoinChannel2])).toEqual(expectedOutput2); }); it('should return expected data for ADD_TO_CHANNEL', () => { const userActivities = [postAddToChannel]; const expectedOutput = { allUserIds: ['added_user_id_1', 'user_id_1'], allUsernames: ['added_username_1'], messageData: [{postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_1', userIds: ['added_user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postAddToChannel2: ActivityEntry = { postType: PostTypes.ADD_TO_CHANNEL, actorId: ['user_id_2'], userIds: ['added_user_id_2', 'added_user_id_3', 'added_user_id_4'], usernames: ['added_username_2', 'added_username_3', 'added_username_4'], }; const userActivities2 = [postAddToChannel, postAddToChannel2]; const expectedOutput2 = { allUserIds: ['added_user_id_1', 'user_id_1', 'added_user_id_2', 'added_user_id_3', 'added_user_id_4', 'user_id_2'], allUsernames: ['added_username_1', 'added_username_2', 'added_username_3', 'added_username_4'], messageData: [ {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_1', userIds: ['added_user_id_1']}, {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_2', userIds: ['added_user_id_2', 'added_user_id_3', 'added_user_id_4']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for ADD_TO_TEAM', () => { const userActivities = [postAddToTeam]; const expectedOutput = { allUserIds: ['added_user_id_1', 'added_user_id_2', 'user_id_1'], allUsernames: ['added_username_1', 'added_username_2'], messageData: [{postType: PostTypes.ADD_TO_TEAM, actorId: 'user_id_1', userIds: ['added_user_id_1', 'added_user_id_2']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postAddToTeam2: ActivityEntry = { postType: PostTypes.ADD_TO_TEAM, actorId: ['user_id_2'], userIds: ['added_user_id_3', 'added_user_id_4'], usernames: ['added_username_3', 'added_username_4'], }; const userActivities2 = [postAddToTeam, postAddToTeam2]; const expectedOutput2 = { allUserIds: ['added_user_id_1', 'added_user_id_2', 'user_id_1', 'added_user_id_3', 'added_user_id_4', 'user_id_2'], allUsernames: ['added_username_1', 'added_username_2', 'added_username_3', 'added_username_4'], messageData: [ {postType: PostTypes.ADD_TO_TEAM, actorId: 'user_id_1', userIds: ['added_user_id_1', 'added_user_id_2']}, {postType: PostTypes.ADD_TO_TEAM, actorId: 'user_id_2', userIds: ['added_user_id_3', 'added_user_id_4']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for JOIN_TEAM', () => { const userActivities = [postJoinTeam]; const expectedOutput = { allUserIds: ['user_id_1'], allUsernames: [], messageData: [{postType: PostTypes.JOIN_TEAM, userIds: ['user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postJoinTeam2: ActivityEntry = { postType: PostTypes.JOIN_TEAM, actorId: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], userIds: [], usernames: [], }; const userActivities2 = [postJoinTeam, postJoinTeam2]; const expectedOutput2 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.JOIN_TEAM, userIds: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for LEAVE_CHANNEL', () => { const userActivities = [postLeaveChannel]; const expectedOutput = { allUserIds: ['user_id_1'], allUsernames: [], messageData: [{postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postLeaveChannel2: ActivityEntry = { postType: PostTypes.LEAVE_CHANNEL, actorId: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], userIds: [], usernames: [], }; const userActivities2 = [postLeaveChannel, postLeaveChannel2]; const expectedOutput2 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], allUsernames: [], messageData: [ {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for LEAVE_TEAM', () => { const userActivities = [postLeaveTeam]; const expectedOutput = { allUserIds: ['user_id_1'], allUsernames: [], messageData: [{postType: PostTypes.LEAVE_TEAM, userIds: ['user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postLeaveTeam2: ActivityEntry = { postType: PostTypes.LEAVE_TEAM, actorId: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], userIds: [], usernames: [], }; const userActivities2 = [postLeaveTeam, postLeaveTeam2]; const expectedOutput2 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], allUsernames: [], messageData: [ {postType: PostTypes.LEAVE_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_TEAM, userIds: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for REMOVE_FROM_CHANNEL', () => { const userActivities = [postRemoveFromChannel]; const expectedOutput = { allUserIds: ['removed_user_id_1', 'user_id_1'], allUsernames: ['removed_username_1'], messageData: [{postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: 'user_id_1', userIds: ['removed_user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postRemoveFromChannel2: ActivityEntry = { postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: ['user_id_2'], userIds: ['removed_user_id_2', 'removed_user_id_3', 'removed_user_id_4', 'removed_user_id_5'], usernames: ['removed_username_2', 'removed_username_3', 'removed_username_4', 'removed_username_5'], }; const userActivities2 = [postRemoveFromChannel, postRemoveFromChannel2]; const expectedOutput2 = { allUserIds: ['removed_user_id_1', 'user_id_1', 'removed_user_id_2', 'removed_user_id_3', 'removed_user_id_4', 'removed_user_id_5', 'user_id_2'], allUsernames: ['removed_username_1', 'removed_username_2', 'removed_username_3', 'removed_username_4', 'removed_username_5'], messageData: [ {postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: 'user_id_1', userIds: ['removed_user_id_1']}, {postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: 'user_id_2', userIds: ['removed_user_id_2', 'removed_user_id_3', 'removed_user_id_4', 'removed_user_id_5']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for REMOVE_FROM_TEAM', () => { const userActivities = [postRemoveFromTeam]; const expectedOutput = { allUserIds: ['user_id_1'], allUsernames: [], messageData: [{postType: PostTypes.REMOVE_FROM_TEAM, userIds: ['user_id_1']}], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); const postRemoveFromTeam2: ActivityEntry = { postType: PostTypes.REMOVE_FROM_TEAM, actorId: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], userIds: [], usernames: [], }; const userActivities2 = [postRemoveFromTeam, postRemoveFromTeam2]; const expectedOutput2 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3', 'user_id_4', 'user_id_5'], allUsernames: [], messageData: [ {postType: PostTypes.REMOVE_FROM_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.REMOVE_FROM_TEAM, userIds: ['user_id_2', 'user_id_3', 'user_id_4', 'user_id_5']}, ], }; expect(extractUserActivityData(userActivities2)).toEqual(expectedOutput2); }); it('should return expected data for multiple post types', () => { const userActivities = [postAddToChannel, postAddToTeam, postJoinChannel, postJoinTeam, postLeaveChannel, postLeaveTeam, postRemoveFromChannel, postRemoveFromTeam]; const expectedOutput = { allUserIds: ['added_user_id_1', 'user_id_1', 'added_user_id_2', 'removed_user_id_1'], allUsernames: ['added_username_1', 'added_username_2', 'removed_username_1'], messageData: [ {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_1', userIds: ['added_user_id_1']}, {postType: PostTypes.ADD_TO_TEAM, actorId: 'user_id_1', userIds: ['added_user_id_1', 'added_user_id_2']}, {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.JOIN_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: 'user_id_1', userIds: ['removed_user_id_1']}, {postType: PostTypes.REMOVE_FROM_TEAM, userIds: ['user_id_1']}, ], }; expect(extractUserActivityData(userActivities)).toEqual(expectedOutput); }); }); describe('combineUserActivityData', () => { it('combineUserActivitySystemPost returns null when systemPosts is an empty array', () => { expect(combineUserActivitySystemPost([])).toBeNull(); }); it('correctly combine different post types and actorIds by order', () => { const postAddToChannel1 = TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, user_id: 'user_id_1', props: {addedUserId: 'added_user_id_1', addedUsername: 'added_username_1'}}); const postAddToTeam1 = TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM, user_id: 'user_id_1', props: {addedUserId: 'added_user_id_1'}}); const postJoinChannel1 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_1'}); const postJoinTeam1 = TestHelper.getPostMock({type: PostTypes.JOIN_TEAM, user_id: 'user_id_1'}); const postLeaveChannel1 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_1'}); const postLeaveTeam1 = TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM, user_id: 'user_id_1'}); const postRemoveFromChannel1 = TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL, user_id: 'user_id_1', props: {removedUserId: 'removed_user_id_1', removedUsername: 'removed_username_1'}}); const postRemoveFromTeam1 = TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM, user_id: 'user_id_1'}); const posts = [postAddToChannel1, postAddToTeam1, postJoinChannel1, postJoinTeam1, postLeaveChannel1, postLeaveTeam1, postRemoveFromChannel1, postRemoveFromTeam1].reverse(); const expectedOutput = { allUserIds: ['added_user_id_1', 'user_id_1', 'removed_user_id_1'], allUsernames: ['added_username_1', 'removed_username_1'], messageData: [ {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_1', userIds: ['added_user_id_1']}, {postType: PostTypes.ADD_TO_TEAM, actorId: 'user_id_1', userIds: ['added_user_id_1']}, {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.JOIN_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_TEAM, userIds: ['user_id_1']}, {postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: 'user_id_1', userIds: ['removed_user_id_1']}, {postType: PostTypes.REMOVE_FROM_TEAM, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); }); it('correctly combine same post types', () => { const postAddToChannel1 = TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, user_id: 'user_id_1', props: {addedUserId: 'added_user_id_1', addedUsername: 'added_username_1'}}); const postAddToChannel2 = TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, user_id: 'user_id_2', props: {addedUserId: 'added_user_id_2', addedUsername: 'added_username_2'}}); const postAddToChannel3 = TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, user_id: 'user_id_3', props: {addedUserId: 'added_user_id_3', addedUsername: 'added_username_3'}}); const posts = [postAddToChannel1, postAddToChannel2, postAddToChannel3].reverse(); const expectedOutput = { allUserIds: ['added_user_id_1', 'user_id_1', 'added_user_id_2', 'user_id_2', 'added_user_id_3', 'user_id_3'], allUsernames: ['added_username_1', 'added_username_2', 'added_username_3'], messageData: [ {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_1', userIds: ['added_user_id_1']}, {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_2', userIds: ['added_user_id_2']}, {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_3', userIds: ['added_user_id_3']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); }); it('correctly combine Join and Leave Posts', () => { const postJoinChannel1 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_1'}); const postLeaveChannel1 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_1'}); const postJoinChannel2 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_2'}); const postLeaveChannel2 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_2'}); const postJoinChannel3 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_3'}); const postLeaveChannel3 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_3'}); const post = [postJoinChannel1, postLeaveChannel1].reverse(); const expectedOutput = { allUserIds: ['user_id_1'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(post)).toEqual(expectedOutput); const post1 = [postJoinChannel1, postLeaveChannel1, postJoinChannel2, postLeaveChannel2, postJoinChannel3, postLeaveChannel3].reverse(); const expectedOutput1 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1', 'user_id_2', 'user_id_3']}, ], }; expect(combineUserActivitySystemPost(post1)).toEqual(expectedOutput1); const post2 = [postJoinChannel1, postJoinChannel2, postJoinChannel3, postLeaveChannel1, postLeaveChannel2, postLeaveChannel3].reverse(); const expectedOutput2 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1', 'user_id_2', 'user_id_3']}, ], }; expect(combineUserActivitySystemPost(post2)).toEqual(expectedOutput2); const post3 = [postJoinChannel1, postJoinChannel2, postLeaveChannel2, postLeaveChannel1, postJoinChannel3, postLeaveChannel3].reverse(); const expectedOutput3 = { allUserIds: ['user_id_1', 'user_id_2', 'user_id_3'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1', 'user_id_2', 'user_id_3']}, ], }; expect(combineUserActivitySystemPost(post3)).toEqual(expectedOutput3); }); it('should only partially combine mismatched join and leave posts', () => { const postJoinChannel1 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_1'}); const postLeaveChannel1 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_1'}); const postJoinChannel2 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_2'}); const postLeaveChannel2 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_2'}); let posts = [postJoinChannel1, postLeaveChannel1, postJoinChannel2].reverse(); let expectedOutput = { allUserIds: ['user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_2']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postLeaveChannel1, postLeaveChannel2].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_2']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postJoinChannel2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1', 'user_id_2']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postLeaveChannel2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_2', 'user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel2, postJoinChannel1, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_2', 'user_id_1'], allUsernames: [], messageData: [ // This case is arguably incorrect, but it's an edge case {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_2', 'user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postLeaveChannel2, postJoinChannel1, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_2', 'user_id_1'], allUsernames: [], messageData: [ {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_2']}, {postType: PostTypes.JOIN_LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); }); it('should not combine join and leave posts with other actions in between', () => { const postJoinChannel1 = TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, user_id: 'user_id_1'}); const postLeaveChannel1 = TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, user_id: 'user_id_1'}); const postAddToChannel2 = TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, user_id: 'user_id_2', props: {addedUserId: 'added_user_id_1', addedUsername: 'added_username_1'}}); const postAddToTeam2 = TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM, user_id: 'user_id_2', props: {addedUserId: 'added_user_id_1'}}); const postJoinTeam2 = TestHelper.getPostMock({type: PostTypes.JOIN_TEAM, user_id: 'user_id_2'}); const postLeaveTeam2 = TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM, user_id: 'user_id_2'}); const postRemoveFromChannel2 = TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL, user_id: 'user_id_2', props: {removedUserId: 'removed_user_id_1', removedUsername: 'removed_username_1'}}); const postRemoveFromTeam2 = TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM, user_id: 'removed_user_id_1'}); let posts = [postJoinChannel1, postAddToChannel2, postLeaveChannel1].reverse(); let expectedOutput = { allUserIds: ['user_id_1', 'added_user_id_1', 'user_id_2'], allUsernames: ['added_username_1'], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.ADD_TO_CHANNEL, actorId: 'user_id_2', userIds: ['added_user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postAddToTeam2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'added_user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.ADD_TO_TEAM, actorId: 'user_id_2', userIds: ['added_user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postJoinTeam2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.JOIN_TEAM, userIds: ['user_id_2']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postLeaveTeam2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'user_id_2'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.LEAVE_TEAM, userIds: ['user_id_2']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postRemoveFromChannel2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'removed_user_id_1', 'user_id_2'], allUsernames: ['removed_username_1'], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.REMOVE_FROM_CHANNEL, actorId: 'user_id_2', userIds: ['removed_user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); posts = [postJoinChannel1, postRemoveFromTeam2, postLeaveChannel1].reverse(); expectedOutput = { allUserIds: ['user_id_1', 'removed_user_id_1'], allUsernames: [], messageData: [ {postType: PostTypes.JOIN_CHANNEL, userIds: ['user_id_1']}, {postType: PostTypes.REMOVE_FROM_TEAM, userIds: ['removed_user_id_1']}, {postType: PostTypes.LEAVE_CHANNEL, userIds: ['user_id_1']}, ], }; expect(combineUserActivitySystemPost(posts)).toEqual(expectedOutput); }); }); describe('shouldShowJoinLeaveMessages', () => { it('should default to true', () => { const state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'true', }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; // Defaults to show post const show = shouldShowJoinLeaveMessages(state); expect(show).toEqual(true); }); it('set config to false, return false', () => { const state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'false', }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; // Defaults to show post const show = shouldShowJoinLeaveMessages(state); expect(show).toEqual(false); }); it('if user preference, set default wont be used', () => { const state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'false', }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_FILTER_JOIN_LEAVE)]: { category: Preferences.CATEGORY_ADVANCED_SETTINGS, name: Preferences.ADVANCED_FILTER_JOIN_LEAVE, value: 'true', }, }, }, }, } as unknown as GlobalState; // Defaults to show post const show = shouldShowJoinLeaveMessages(state); expect(show).toEqual(true); }); it('if user preference, set default wont be used', () => { const state = { entities: { general: { config: { EnableJoinLeaveMessageByDefault: 'true', }, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_FILTER_JOIN_LEAVE)]: { category: Preferences.CATEGORY_ADVANCED_SETTINGS, name: Preferences.ADVANCED_FILTER_JOIN_LEAVE, value: 'false', }, }, }, }, } as unknown as GlobalState; // Defaults to show post const show = shouldShowJoinLeaveMessages(state); expect(show).toEqual(false); }); });
4,145
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/post_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Post, PostEmbed, PostEmbedType, PostType} from '@mattermost/types/posts'; import type {GlobalState} from '@mattermost/types/store'; import {PostTypes} from 'mattermost-redux/constants/posts'; import { canEditPost, isSystemMessage, shouldIgnorePost, isMeMessage, isUserActivityPost, shouldFilterJoinLeavePost, isPostCommentMention, getEmbedFromMetadata, shouldUpdatePost, isPermalink, } from 'mattermost-redux/utils/post_utils'; import TestHelper from '../../test/test_helper'; import {Permissions} from '../constants'; describe('PostUtils', () => { describe('shouldFilterJoinLeavePost', () => { it('show join/leave posts', () => { const showJoinLeave = true; expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: ''}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.CHANNEL_DELETED}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.DISPLAYNAME_CHANGE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.CONVERT_CHANNEL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.EPHEMERAL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.HEADER_CHANGE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.PURPOSE_CHANGE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_LEAVE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_REMOVE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_TEAM}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM}), showJoinLeave, '')).toBe(false); }); it('hide join/leave posts', () => { const showJoinLeave = false; expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: ''}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.CHANNEL_DELETED}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.DISPLAYNAME_CHANGE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.CONVERT_CHANNEL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.EPHEMERAL}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.HEADER_CHANGE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.PURPOSE_CHANGE}), showJoinLeave, '')).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_LEAVE}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_REMOVE}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_TEAM}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM}), showJoinLeave, '')).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM}), showJoinLeave, '')).toBe(true); }); it('always join/leave posts for the current user', () => { const username = 'user1'; const otherUsername = 'user2'; const showJoinLeave = false; expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, props: {username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL, props: {username: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, props: {username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL, props: {username: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, props: {username, addedUsername: otherUsername}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, props: {username: otherUsername, addedUsername: username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL, props: {username: otherUsername, addedUsername: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL, props: {removedUsername: username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL, props: {removedUsername: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_TEAM, props: {username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.JOIN_TEAM, props: {username: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM, props: {username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM, props: {username: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM, props: {username, addedUsername: otherUsername}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM, props: {username: otherUsername, addedUsername: username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM, props: {username: otherUsername, addedUsername: otherUsername}}), showJoinLeave, username)).toBe(true); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM, props: {removedUsername: username}}), showJoinLeave, username)).toBe(false); expect(shouldFilterJoinLeavePost(TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM, props: {removedUsername: otherUsername}}), showJoinLeave, username)).toBe(true); }); }); describe('canEditPost', () => { const licensed = {IsLicensed: 'true'}; const teamId = 'team-id'; const channelId = 'channel-id'; const userId = 'user-id'; it('should work with new permissions version', () => { let newVersionState = { entities: { general: { serverVersion: '4.9.0', }, users: { currentUserId: userId, profiles: { 'user-id': {roles: 'system_role'}, }, }, teams: { currentTeamId: teamId, myMembers: { 'team-id': {roles: 'team_role'}, }, }, channels: { currentChannelId: channelId, myMembers: { 'channel-id': {roles: 'channel_role'}, }, roles: { 'channel-id': ['channel_role'], }, }, roles: { roles: { system_role: { permissions: [], }, team_role: { permissions: [], }, channel_role: { permissions: [], }, }, }, }, } as unknown as GlobalState; // With new permissions expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_POST]}), team_role: TestHelper.getRoleMock({permissions: []}), channel_role: TestHelper.getRoleMock({permissions: []}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: []}), team_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_POST]}), channel_role: TestHelper.getRoleMock({permissions: []}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: []}), team_role: TestHelper.getRoleMock({permissions: []}), channel_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_POST]}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_OTHERS_POSTS]}), team_role: TestHelper.getRoleMock({permissions: []}), channel_role: TestHelper.getRoleMock({permissions: []}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: []}), team_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_OTHERS_POSTS]}), channel_role: TestHelper.getRoleMock({permissions: []}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: []}), team_role: TestHelper.getRoleMock({permissions: []}), channel_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_OTHERS_POSTS]}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(!canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_OTHERS_POSTS, Permissions.EDIT_POST]}), team_role: TestHelper.getRoleMock({permissions: []}), channel_role: TestHelper.getRoleMock({permissions: []}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: []}), team_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_OTHERS_POSTS, Permissions.EDIT_POST]}), channel_role: TestHelper.getRoleMock({permissions: []}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); newVersionState.entities.roles = { roles: { system_role: TestHelper.getRoleMock({permissions: []}), team_role: TestHelper.getRoleMock({permissions: []}), channel_role: TestHelper.getRoleMock({permissions: [Permissions.EDIT_OTHERS_POSTS, Permissions.EDIT_POST]}), }, pending: new Set(), }; newVersionState = {...newVersionState}; expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: userId, create_at: Date.now() - 6000000}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: -1}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other'}))).toBeTruthy(); expect(canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 100}))).toBeTruthy(); expect(!canEditPost(newVersionState, {PostEditTimeLimit: 300}, licensed, teamId, channelId, userId, TestHelper.getPostMock({user_id: 'other', create_at: Date.now() - 6000000}))).toBeTruthy(); }); }); describe('isSystemMessage', () => { const testCases = [ {input: TestHelper.getPostMock({type: ''}), output: false}, {input: TestHelper.getPostMock({type: PostTypes.CHANNEL_DELETED}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.CHANNEL_UNARCHIVED}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.DISPLAYNAME_CHANGE}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.CONVERT_CHANNEL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.EPHEMERAL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.EPHEMERAL_ADD_TO_CHANNEL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.HEADER_CHANGE}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.PURPOSE_CHANGE}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.JOIN_LEAVE}), output: true}, // deprecated system type {input: TestHelper.getPostMock({type: PostTypes.ADD_REMOVE}), output: true}, // deprecated system type {input: TestHelper.getPostMock({type: PostTypes.COMBINED_USER_ACTIVITY}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.ADD_TO_CHANNEL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.JOIN_CHANNEL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.LEAVE_CHANNEL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_CHANNEL}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.ADD_TO_TEAM}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.JOIN_TEAM}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.LEAVE_TEAM}), output: true}, {input: TestHelper.getPostMock({type: PostTypes.REMOVE_FROM_TEAM}), output: true}, ]; testCases.forEach((testCase) => { it(`should identify if post is system message: isSystemMessage('${testCase.input}') should return ${testCase.output}`, () => { expect(isSystemMessage(testCase.input)).toBe(testCase.output); }); }); }); describe('shouldIgnorePost', () => { it('should return false if system message is adding current user', () => { const currentUserId = 'czduet3upjfupy9xnqswrxaqea'; const post = TestHelper.getPostMock({ type: PostTypes.ADD_TO_CHANNEL, user_id: 'anotherUserId', props: { addedUserId: 'czduet3upjfupy9xnqswrxaqea', }, }); const evalShouldIgnorePost = shouldIgnorePost(post, currentUserId); expect(evalShouldIgnorePost).toBe(false); }); it('should return true if system message is adding a different user', () => { const currentUserId = 'czduet3upjfupy9xnqswrxaqea'; const post = TestHelper.getPostMock({ type: PostTypes.ADD_TO_CHANNEL, props: { addedUserId: 'mrbijaq9mjr3ue569kake9m6do', }, }); const evalShouldIgnorePost = shouldIgnorePost(post, currentUserId); expect(evalShouldIgnorePost).toBe(true); }); }); describe('isUserActivityPost', () => { const testCases = [ {input: '' as any, output: false}, {input: null as any, output: false}, {input: PostTypes.CHANNEL_DELETED, output: false}, {input: PostTypes.DISPLAYNAME_CHANGE, output: false}, {input: PostTypes.CONVERT_CHANNEL, output: false}, {input: PostTypes.EPHEMERAL, output: false}, {input: PostTypes.EPHEMERAL_ADD_TO_CHANNEL, output: false}, {input: PostTypes.HEADER_CHANGE, output: false}, {input: PostTypes.PURPOSE_CHANGE, output: false}, {input: PostTypes.JOIN_LEAVE, output: false}, // deprecated system type {input: PostTypes.ADD_REMOVE, output: false}, // deprecated system type {input: PostTypes.COMBINED_USER_ACTIVITY, output: false}, {input: PostTypes.ADD_TO_CHANNEL, output: true}, {input: PostTypes.JOIN_CHANNEL, output: true}, {input: PostTypes.LEAVE_CHANNEL, output: true}, {input: PostTypes.REMOVE_FROM_CHANNEL, output: true}, {input: PostTypes.ADD_TO_TEAM, output: true}, {input: PostTypes.JOIN_TEAM, output: true}, {input: PostTypes.LEAVE_TEAM, output: true}, {input: PostTypes.REMOVE_FROM_TEAM, output: true}, ]; testCases.forEach((testCase) => { it(`should identify if post is user activity - add/remove/join/leave channel/team: isUserActivityPost('${testCase.input}') should return ${testCase.output}`, () => { expect(isUserActivityPost(testCase.input)).toBe(testCase.output); }); }); }); describe('isPostCommentMention', () => { const currentUser = TestHelper.getUserMock({ id: 'currentUser', notify_props: { ...TestHelper.getUserMock({}).notify_props, comments: 'any', }, }); it('should return true as root post is by user', () => { const post = TestHelper.getPostMock({ user_id: 'someotherUser', }); const rootPost = TestHelper.getPostMock({ user_id: 'currentUser', }); const isCommentMention = isPostCommentMention({currentUser, post, rootPost, threadRepliedToByCurrentUser: false}); expect(isCommentMention).toBe(true); }); it('should return false as root post is not by user and did not participate in thread', () => { const post = TestHelper.getPostMock({ user_id: 'someotherUser', }); const rootPost = TestHelper.getPostMock({ user_id: 'differentUser', }); const isCommentMention = isPostCommentMention({currentUser, post, rootPost, threadRepliedToByCurrentUser: false}); expect(isCommentMention).toBe(false); }); it('should return false post is by current User', () => { const post = TestHelper.getPostMock({ user_id: 'currentUser', }); const rootPost = TestHelper.getPostMock({ user_id: 'differentUser', }); const isCommentMention = isPostCommentMention({currentUser, post, rootPost, threadRepliedToByCurrentUser: false}); expect(isCommentMention).toBe(false); }); it('should return true as post is by current User but it is a webhhok and user participated in thread', () => { const post = TestHelper.getPostMock({ user_id: 'currentUser', props: { from_webhook: true, }, }); const rootPost = TestHelper.getPostMock({ user_id: 'differentUser', }); const isCommentMention = isPostCommentMention({currentUser, post, rootPost, threadRepliedToByCurrentUser: true}); expect(isCommentMention).toBe(true); }); it('should return false as root post is not by currentUser and notify_props is root', () => { const post = TestHelper.getPostMock({ user_id: 'someotherUser', }); const rootPost = TestHelper.getPostMock({ user_id: 'differentUser', }); const modifiedCurrentUser = { ...currentUser, notify_props: { ...currentUser.notify_props, comments: 'root' as const, }, }; const isCommentMention = isPostCommentMention({currentUser: modifiedCurrentUser, post, rootPost, threadRepliedToByCurrentUser: true}); expect(isCommentMention).toBe(false); }); it('should return true as root post is by currentUser and notify_props is root', () => { const post = TestHelper.getPostMock({ user_id: 'someotherUser', }); const rootPost = TestHelper.getPostMock({ user_id: 'currentUser', }); const modifiedCurrentUser = { ...currentUser, notify_props: { ...currentUser.notify_props, comments: 'root' as const, }, }; const isCommentMention = isPostCommentMention({currentUser: modifiedCurrentUser, post, rootPost, threadRepliedToByCurrentUser: true}); expect(isCommentMention).toBe(true); }); }); describe('isMeMessage', () => { it('should correctly identify messages generated from /me', () => { for (const data of [ { post: TestHelper.getPostMock({type: 'hello' as PostType}), result: false, }, { post: TestHelper.getPostMock({type: 'ME' as PostType}), result: false, }, { post: TestHelper.getPostMock({type: PostTypes.ME}), result: true, }, ]) { const confirmation = isMeMessage(data.post); expect(confirmation).toBe(data.result); } }); }); describe('getEmbedFromMetadata', () => { it('should return null if no metadata is not passed as argument', () => { const embedData = (getEmbedFromMetadata as any)(); expect(embedData).toBe(null); }); it('should return null if argument does not contain embed key', () => { const embedData = (getEmbedFromMetadata as any)({}); expect(embedData).toBe(null); }); it('should return null if embed key in argument is empty', () => { const embedData = (getEmbedFromMetadata as any)({embeds: []}); expect(embedData).toBe(null); }); it('should return first entry in embed key', () => { const embedValue = {type: 'opengraph' as PostEmbedType, url: 'url'}; const embedData = getEmbedFromMetadata({embeds: [embedValue, {type: 'image', url: 'url1'}]} as Post['metadata']); expect(embedData).toEqual(embedValue); }); }); describe('isPermalink', () => { it('should return true if post contains permalink', () => { const post = TestHelper.getPostMock({ metadata: {embeds: [{type: 'permalink', url: ''}]} as Post['metadata'], }); expect(isPermalink(post)).toBe(true); }); it('should return false if post contains an embed that is not a permalink', () => { const post = TestHelper.getPostMock({ metadata: {embeds: [{type: 'opengraph', url: ''}]} as Post['metadata'], }); expect(isPermalink(post)).toBe(false); }); it('should return false if post has no embeds', () => { const embeds: PostEmbed[] = []; const post = TestHelper.getPostMock({ metadata: {embeds} as Post['metadata'], }); expect(isPermalink(post)).toBe(false); }); }); describe('shouldUpdatePost', () => { const storedPost = TestHelper.getPostMock({ id: 'post1', message: '123', update_at: 100, is_following: false, participants: null, reply_count: 4, }); it('should return true for new posts', () => { const post = TestHelper.getPostMock({ ...storedPost, update_at: 100, }); expect(shouldUpdatePost(post)).toBe(true); }); it('should return false for older posts', () => { const post = { ...storedPost, update_at: 40, }; expect(shouldUpdatePost(post, storedPost)).toBe(false); }); it('should return true for newer posts', () => { const post = TestHelper.getPostMock({ id: 'post1', message: 'test', update_at: 400, is_following: false, participants: null, reply_count: 4, }); expect(shouldUpdatePost(post, storedPost)).toBe(true); }); it('should return false for same posts', () => { const post = {...storedPost}; expect(shouldUpdatePost(post, storedPost)).toBe(false); }); it('should return true for same posts with participants changed', () => { const post = { ...storedPost, participants: [], }; expect(shouldUpdatePost(post, storedPost)).toBe(true); }); it('should return true for same posts with reply_count changed', () => { const post = { ...storedPost, reply_count: 2, }; expect(shouldUpdatePost(post, storedPost)).toBe(true); }); it('should return true for same posts with is_following changed', () => { const post = { ...storedPost, is_following: true, }; expect(shouldUpdatePost(post, storedPost)).toBe(true); }); it('should return true for same posts with metadata in received post and not in stored post', () => { const post = TestHelper.getPostMock({ ...storedPost, metadata: {embeds: [{type: 'permalink'}]} as Post['metadata'], }); const storedPostSansMetadata = {...storedPost}; delete (storedPostSansMetadata as any).metadata; expect(shouldUpdatePost(post, storedPostSansMetadata)).toBe(true); }); }); });
4,149
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/theme_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as ThemeUtils from 'mattermost-redux/utils/theme_utils'; import {Preferences} from '../constants'; describe('ThemeUtils', () => { describe('getComponents', () => { it('hex color', () => { const input = 'ff77aa'; const expected = {red: 255, green: 119, blue: 170, alpha: 1}; expect(ThemeUtils.getComponents(input)).toEqual(expected); }); it('3 digit hex color', () => { const input = '4a3'; const expected = {red: 68, green: 170, blue: 51, alpha: 1}; expect(ThemeUtils.getComponents(input)).toEqual(expected); }); it('hex color with leading number sign', () => { const input = '#cda43d'; const expected = {red: 205, green: 164, blue: 61, alpha: 1}; expect(ThemeUtils.getComponents(input)).toEqual(expected); }); it('rgb', () => { const input = 'rgb(123,231,67)'; const expected = {red: 123, green: 231, blue: 67, alpha: 1}; expect(ThemeUtils.getComponents(input)).toEqual(expected); }); it('rgba', () => { const input = 'rgb(45,67,89,0.04)'; const expected = {red: 45, green: 67, blue: 89, alpha: 0.04}; expect(ThemeUtils.getComponents(input)).toEqual(expected); }); }); describe('changeOpacity', () => { it('hex color', () => { const input = 'ff77aa'; const expected = 'rgba(255,119,170,0.5)'; expect(ThemeUtils.changeOpacity(input, 0.5)).toEqual(expected); }); it('rgb', () => { const input = 'rgb(123,231,67)'; const expected = 'rgba(123,231,67,0.3)'; expect(ThemeUtils.changeOpacity(input, 0.3)).toEqual(expected); }); it('rgba', () => { const input = 'rgb(45,67,89,0.4)'; const expected = 'rgba(45,67,89,0.2)'; expect(ThemeUtils.changeOpacity(input, 0.5)).toEqual(expected); }); }); describe('setThemeDefaults', () => { it('blank theme', () => { const input = {}; const expected = {...Preferences.THEMES.denim}; delete expected.type; expect(ThemeUtils.setThemeDefaults(input)).toEqual(expected); }); it('correctly updates the sidebarTeamBarBg variable', () => { const input = {sidebarHeaderBg: '#ffaa55'}; expect(ThemeUtils.setThemeDefaults(input).sidebarTeamBarBg).toEqual('#cc8844'); }); it('set defaults on unset properties only', () => { const input = {buttonColor: '#7600ff'}; expect(ThemeUtils.setThemeDefaults(input).buttonColor).toEqual('#7600ff'); }); it('ignore type', () => { const input = {type: 'sometype' as any}; expect(ThemeUtils.setThemeDefaults(input).type).toEqual('sometype'); }); }); });
4,152
0
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src
petrpan-code/mattermost/mattermost/webapp/channels/src/packages/mattermost-redux/src/utils/user_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { displayUsername, filterProfilesStartingWithTerm, filterProfilesMatchingWithTerm, getSuggestionsSplitBy, getSuggestionsSplitByMultiple, includesAnAdminRole, applyRolesFilters, } from 'mattermost-redux/utils/user_utils'; import TestHelper from '../../test/test_helper'; import {Preferences, General} from '../constants'; describe('user utils', () => { describe('displayUsername', () => { const userObj = TestHelper.getUserMock({ id: '100', username: 'testUser', nickname: 'nick', first_name: 'test', last_name: 'user', }); it('should return username', () => { expect(displayUsername(userObj, 'UNKNOWN_PREFERENCE')).toBe('testUser'); }); it('should return nickname', () => { expect(displayUsername(userObj, Preferences.DISPLAY_PREFER_NICKNAME)).toBe('nick'); }); it('should return fullname when no nick name', () => { expect(displayUsername({...userObj, nickname: ''}, Preferences.DISPLAY_PREFER_NICKNAME)).toBe('test user'); }); it('should return username when no nick name and no full name', () => { expect(displayUsername({...userObj, nickname: '', first_name: '', last_name: ''}, Preferences.DISPLAY_PREFER_NICKNAME)).toBe('testUser'); }); it('should return fullname', () => { expect(displayUsername(userObj, Preferences.DISPLAY_PREFER_FULL_NAME)).toBe('test user'); }); it('should return username when no full name', () => { expect(displayUsername({...userObj, first_name: '', last_name: ''}, Preferences.DISPLAY_PREFER_FULL_NAME)).toBe('testUser'); }); it('should return default username string', () => { let noUserObj; expect(displayUsername(noUserObj, 'UNKNOWN_PREFERENCE')).toBe('Someone'); }); it('should return empty string when user does not exist and useDefaultUserName param is false', () => { let noUserObj; expect(displayUsername(noUserObj, 'UNKNOWN_PREFERENCE', false)).toBe(''); }); }); describe('filterProfilesStartingWithTerm', () => { const userA = TestHelper.getUserMock({ id: '100', username: 'testUser.split_10-', nickname: 'nick', first_name: 'First', last_name: 'Last1', }); const userB = TestHelper.getUserMock({ id: '101', username: 'extraPerson-split', nickname: 'somebody', first_name: 'First', last_name: 'Last2', email: '[email protected]', }); const users = [userA, userB]; it('should match all for empty filter', () => { expect(filterProfilesStartingWithTerm(users, '')).toEqual([userA, userB]); }); it('should filter out results which do not match', () => { expect(filterProfilesStartingWithTerm(users, 'testBad')).toEqual([]); }); it('should match by username', () => { expect(filterProfilesStartingWithTerm(users, 'testUser')).toEqual([userA]); }); it('should match by split part of the username', () => { expect(filterProfilesStartingWithTerm(users, 'split')).toEqual([userA, userB]); expect(filterProfilesStartingWithTerm(users, '10')).toEqual([userA]); }); it('should match by firstname', () => { expect(filterProfilesStartingWithTerm(users, 'First')).toEqual([userA, userB]); }); it('should match by lastname prefix', () => { expect(filterProfilesStartingWithTerm(users, 'Last')).toEqual([userA, userB]); }); it('should match by lastname fully', () => { expect(filterProfilesStartingWithTerm(users, 'Last2')).toEqual([userB]); }); it('should match by fullname prefix', () => { expect(filterProfilesStartingWithTerm(users, 'First Last')).toEqual([userA, userB]); }); it('should match by fullname fully', () => { expect(filterProfilesStartingWithTerm(users, 'First Last1')).toEqual([userA]); }); it('should match by fullname case-insensitive', () => { expect(filterProfilesStartingWithTerm(users, 'first LAST')).toEqual([userA, userB]); }); it('should match by nickname', () => { expect(filterProfilesStartingWithTerm(users, 'some')).toEqual([userB]); }); it('should not match by nickname substring', () => { expect(filterProfilesStartingWithTerm(users, 'body')).toEqual([]); }); it('should match by email prefix', () => { expect(filterProfilesStartingWithTerm(users, 'left')).toEqual([userB]); }); it('should match by email domain', () => { expect(filterProfilesStartingWithTerm(users, 'right')).toEqual([userB]); }); it('should match by full email', () => { expect(filterProfilesStartingWithTerm(users, '[email protected]')).toEqual([userB]); }); it('should ignore leading @ for username', () => { expect(filterProfilesStartingWithTerm(users, '@testUser')).toEqual([userA]); }); it('should ignore leading @ for firstname', () => { expect(filterProfilesStartingWithTerm(users, '@first')).toEqual([userA, userB]); }); }); describe('filterProfilesMatchingWithTerm', () => { const userA = TestHelper.getUserMock({ id: '100', username: 'testUser.split_10-', nickname: 'nick', first_name: 'First', last_name: 'Last1', }); const userB = TestHelper.getUserMock({ id: '101', username: 'extraPerson-split', nickname: 'somebody', first_name: 'First', last_name: 'Last2', email: '[email protected]', }); const users = [userA, userB]; it('should match all for empty filter', () => { expect(filterProfilesMatchingWithTerm(users, '')).toEqual([userA, userB]); }); it('should filter out results which do not match', () => { expect(filterProfilesMatchingWithTerm(users, 'testBad')).toEqual([]); }); it('should match by username', () => { expect(filterProfilesMatchingWithTerm(users, 'estUser')).toEqual([userA]); }); it('should match by split part of the username', () => { expect(filterProfilesMatchingWithTerm(users, 'split')).toEqual([userA, userB]); expect(filterProfilesMatchingWithTerm(users, '10')).toEqual([userA]); }); it('should match by firstname substring', () => { expect(filterProfilesMatchingWithTerm(users, 'rst')).toEqual([userA, userB]); }); it('should match by lastname substring', () => { expect(filterProfilesMatchingWithTerm(users, 'as')).toEqual([userA, userB]); expect(filterProfilesMatchingWithTerm(users, 'st2')).toEqual([userB]); }); it('should match by fullname substring', () => { expect(filterProfilesMatchingWithTerm(users, 'rst Last')).toEqual([userA, userB]); }); it('should match by fullname fully', () => { expect(filterProfilesMatchingWithTerm(users, 'First Last1')).toEqual([userA]); }); it('should match by fullname case-insensitive', () => { expect(filterProfilesMatchingWithTerm(users, 'first LAST')).toEqual([userA, userB]); }); it('should match by nickname substring', () => { expect(filterProfilesMatchingWithTerm(users, 'ome')).toEqual([userB]); expect(filterProfilesMatchingWithTerm(users, 'body')).toEqual([userB]); }); it('should match by email prefix', () => { expect(filterProfilesMatchingWithTerm(users, 'left')).toEqual([userB]); }); it('should match by email domain', () => { expect(filterProfilesMatchingWithTerm(users, 'right')).toEqual([userB]); }); it('should match by full email', () => { expect(filterProfilesMatchingWithTerm(users, '[email protected]')).toEqual([userB]); }); it('should ignore leading @ for username', () => { expect(filterProfilesMatchingWithTerm(users, '@testUser')).toEqual([userA]); }); it('should ignore leading @ for firstname', () => { expect(filterProfilesMatchingWithTerm(users, '@first')).toEqual([userA, userB]); }); }); describe('Utils.getSuggestionsSplitBy', () => { test('correct suggestions when splitting by a character', () => { const term = 'one.two.three'; const expectedSuggestions = ['one.two.three', '.two.three', 'two.three', '.three', 'three']; expect(getSuggestionsSplitBy(term, '.')).toEqual(expectedSuggestions); }); }); describe('Utils.getSuggestionsSplitByMultiple', () => { test('correct suggestions when splitting by multiple characters', () => { const term = 'one.two-three'; const expectedSuggestions = ['one.two-three', '.two-three', 'two-three', '-three', 'three']; expect(getSuggestionsSplitByMultiple(term, ['.', '-'])).toEqual(expectedSuggestions); }); }); describe('Utils.applyRolesFilters', () => { const team = TestHelper.fakeTeamWithId(); const adminUser = {...TestHelper.fakeUserWithId(), roles: `${General.SYSTEM_USER_ROLE} ${General.SYSTEM_ADMIN_ROLE}`}; const nonAdminUser = {...TestHelper.fakeUserWithId(), roles: `${General.SYSTEM_USER_ROLE}`}; const guestUser = {...TestHelper.fakeUserWithId(), roles: `${General.SYSTEM_GUEST_ROLE}`}; it('Non admin user with non admin membership', () => { const nonAdminMembership = {...TestHelper.fakeTeamMember(nonAdminUser.id, team.id), scheme_admin: false, scheme_user: true}; expect(applyRolesFilters(nonAdminUser, [General.SYSTEM_USER_ROLE], [], nonAdminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.TEAM_USER_ROLE], [], nonAdminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.CHANNEL_USER_ROLE], [], nonAdminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.SYSTEM_ADMIN_ROLE, General.TEAM_ADMIN_ROLE, General.CHANNEL_ADMIN_ROLE], [], nonAdminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [], [General.SYSTEM_ADMIN_ROLE], nonAdminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [], [General.SYSTEM_USER_ROLE], nonAdminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [], [General.TEAM_USER_ROLE], nonAdminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [], [General.CHANNEL_USER_ROLE], nonAdminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [General.TEAM_USER_ROLE], [General.SYSTEM_ADMIN_ROLE], nonAdminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.TEAM_ADMIN_ROLE], [General.SYSTEM_ADMIN_ROLE], nonAdminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [General.TEAM_USER_ROLE], [General.SYSTEM_USER_ROLE], nonAdminMembership)).toBe(false); }); it('Non admin user with admin membership', () => { const adminMembership = {...TestHelper.fakeTeamMember(nonAdminUser.id, team.id), scheme_admin: true, scheme_user: true}; expect(applyRolesFilters(nonAdminUser, [General.SYSTEM_USER_ROLE], [], adminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.TEAM_ADMIN_ROLE], [], adminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.CHANNEL_ADMIN_ROLE], [], adminMembership)).toBe(true); expect(applyRolesFilters(nonAdminUser, [General.SYSTEM_ADMIN_ROLE, General.TEAM_USER_ROLE, General.CHANNEL_USER_ROLE], [], adminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [], [General.TEAM_ADMIN_ROLE], adminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [], [General.CHANNEL_ADMIN_ROLE], adminMembership)).toBe(false); expect(applyRolesFilters(nonAdminUser, [General.SYSTEM_USER_ROLE], [General.CHANNEL_ADMIN_ROLE], adminMembership)).toBe(false); }); it('Admin user with any membership', () => { const nonAdminMembership = {...TestHelper.fakeTeamMember(adminUser.id, team.id), scheme_admin: false, scheme_user: true}; const adminMembership = {...TestHelper.fakeTeamMember(adminUser.id, team.id), scheme_admin: true, scheme_user: true}; expect(applyRolesFilters(adminUser, [General.SYSTEM_ADMIN_ROLE], [], nonAdminMembership)).toBe(true); expect(applyRolesFilters(adminUser, [General.SYSTEM_USER_ROLE, General.TEAM_USER_ROLE, General.TEAM_ADMIN_ROLE, General.CHANNEL_USER_ROLE, General.CHANNEL_ADMIN_ROLE], [], nonAdminMembership)).toBe(false); expect(applyRolesFilters(adminUser, [General.SYSTEM_ADMIN_ROLE], [], adminMembership)).toBe(true); expect(applyRolesFilters(adminUser, [General.SYSTEM_USER_ROLE, General.TEAM_USER_ROLE, General.TEAM_ADMIN_ROLE, General.CHANNEL_USER_ROLE, General.CHANNEL_ADMIN_ROLE], [], adminMembership)).toBe(false); expect(applyRolesFilters(adminUser, [], [General.SYSTEM_ADMIN_ROLE], nonAdminMembership)).toBe(false); expect(applyRolesFilters(adminUser, [], [General.SYSTEM_USER_ROLE], nonAdminMembership)).toBe(true); }); it('Guest user with any membership', () => { const nonAdminMembership = {...TestHelper.fakeTeamMember(guestUser.id, team.id), scheme_admin: false, scheme_user: true}; const adminMembership = {...TestHelper.fakeTeamMember(guestUser.id, team.id), scheme_admin: true, scheme_user: true}; expect(applyRolesFilters(guestUser, [General.SYSTEM_GUEST_ROLE], [], nonAdminMembership)).toBe(true); expect(applyRolesFilters(guestUser, [General.SYSTEM_USER_ROLE, General.TEAM_USER_ROLE, General.TEAM_ADMIN_ROLE, General.CHANNEL_USER_ROLE, General.CHANNEL_ADMIN_ROLE], [], nonAdminMembership)).toBe(false); expect(applyRolesFilters(guestUser, [General.SYSTEM_GUEST_ROLE], [], adminMembership)).toBe(true); expect(applyRolesFilters(guestUser, [General.SYSTEM_USER_ROLE, General.TEAM_USER_ROLE, General.TEAM_ADMIN_ROLE, General.CHANNEL_USER_ROLE, General.CHANNEL_ADMIN_ROLE], [], adminMembership)).toBe(false); expect(applyRolesFilters(guestUser, [], [General.SYSTEM_GUEST_ROLE], adminMembership)).toBe(false); }); }); describe('includesAnAdminRole', () => { test('returns expected result', () => { [ [General.SYSTEM_ADMIN_ROLE, true], [General.SYSTEM_USER_MANAGER_ROLE, true], [General.SYSTEM_READ_ONLY_ADMIN_ROLE, true], [General.SYSTEM_MANAGER_ROLE, true], ['non_existent', false], ['foo', false], ['bar', false], ].forEach(([role, expected]) => { const mockRoles = `foo ${role} bar`; const actual = includesAnAdminRole(mockRoles); expect(actual).toBe(expected); }); }); }); });
4,171
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/channel_header_plug/channel_header_plug.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {Channel, ChannelMembership} from '@mattermost/types/channels'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import ChannelHeaderPlug from 'plugins/channel_header_plug/channel_header_plug'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import type {PluginComponent} from 'types/store/plugins'; describe('plugins/ChannelHeaderPlug', () => { const testPlug: PluginComponent = { id: 'someid', pluginId: 'pluginid', icon: <i className='fa fa-anchor'/>, action: jest.fn, dropdownText: 'some dropdown text', tooltipText: 'some tooltip text', } as PluginComponent; test('should match snapshot with no extended component', () => { const wrapper = mountWithIntl( <ChannelHeaderPlug components={[]} channel={{} as Channel} channelMember={{} as ChannelMembership} theme={{} as Theme} sidebarOpen={false} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} appBindings={[]} appsEnabled={false} shouldShowAppBar={false} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with one extended component', () => { const wrapper = mountWithIntl( <ChannelHeaderPlug components={[testPlug]} channel={{} as Channel} channelMember={{} as ChannelMembership} theme={{} as Theme} sidebarOpen={false} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} appBindings={[]} appsEnabled={false} shouldShowAppBar={false} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with six extended components', () => { const wrapper = mountWithIntl( <ChannelHeaderPlug components={[ testPlug, {...testPlug, id: 'someid2'}, {...testPlug, id: 'someid3'}, {...testPlug, id: 'someid4'}, {...testPlug, id: 'someid5'}, {...testPlug, id: 'someid6'}, {...testPlug, id: 'someid7'}, {...testPlug, id: 'someid8'}, {...testPlug, id: 'someid9'}, {...testPlug, id: 'someid10'}, {...testPlug, id: 'someid11'}, {...testPlug, id: 'someid12'}, {...testPlug, id: 'someid13'}, {...testPlug, id: 'someid14'}, {...testPlug, id: 'someid15'}, ]} channel={{} as Channel} channelMember={{} as ChannelMembership} theme={{} as Theme} sidebarOpen={false} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} appBindings={[]} appsEnabled={false} shouldShowAppBar={false} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when the App Bar is visible', () => { const wrapper = mountWithIntl( <ChannelHeaderPlug components={[ testPlug, {...testPlug, id: 'someid2'}, {...testPlug, id: 'someid3'}, {...testPlug, id: 'someid4'}, ]} channel={{} as Channel} channelMember={{} as ChannelMembership} theme={{} as Theme} sidebarOpen={false} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} appBindings={[]} appsEnabled={false} shouldShowAppBar={true} />, ); expect(wrapper).toMatchSnapshot(); }); });
4,174
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/channel_header_plug
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/channel_header_plug/__snapshots__/channel_header_plug.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`plugins/ChannelHeaderPlug should match snapshot when the App Bar is visible 1`] = ` <ChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid2", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid3", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid4", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, ] } 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", } } shouldShowAppBar={true} sidebarOpen={false} theme={Object {}} /> `; exports[`plugins/ChannelHeaderPlug should match snapshot with no extended component 1`] = ` <ChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } shouldShowAppBar={false} sidebarOpen={false} theme={Object {}} /> `; exports[`plugins/ChannelHeaderPlug should match snapshot with one extended component 1`] = ` <ChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, ] } 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", } } shouldShowAppBar={false} sidebarOpen={false} theme={Object {}} > <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> </ChannelHeaderPlug> `; exports[`plugins/ChannelHeaderPlug should match snapshot with six extended components 1`] = ` <ChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid2", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid3", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid4", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid5", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid6", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid7", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid8", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid9", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid10", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid11", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid12", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid13", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid14", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, Object { "action": [Function], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid15", "pluginId": "pluginid", "tooltipText": "some tooltip text", }, ] } 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", } } shouldShowAppBar={false} sidebarOpen={false} theme={Object {}} > <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid2" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid2" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid2" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid3" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid3" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid3" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid4" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid4" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid4" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid5" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid5" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid5" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid6" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid6" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid6" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid7" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid7" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid7" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid8" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid8" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid8" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid9" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid9" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid9" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid10" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid10" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid10" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid11" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid11" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid11" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid12" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid12" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid12" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid13" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid13" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid13" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid14" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid14" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid14" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> <HeaderIconWrapper buttonClass="channel-header__icon" buttonId="someid15" iconComponent={ <i className="fa fa-anchor" /> } key="channelHeaderButtonsomeid15" onClick={[Function]} pluginId="pluginid" tooltipKey="plugin" tooltipText="some tooltip text" > <div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip className="" id="pluginTooltip" > <span> some tooltip text </span> </Tooltip> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <OverlayWrapper className="" id="pluginTooltip" 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, } } > <span> some tooltip text </span> </OverlayWrapper> } placement="bottom" trigger={ Array [ "hover", "focus", ] } > <button className="channel-header__icon" id="someid15" onBlur={[Function]} onClick={[Function]} onFocus={[Function]} onMouseOut={[Function]} onMouseOver={[Function]} > <i className="fa fa-anchor" /> </button> </OverlayTrigger> </OverlayTrigger> </div> </HeaderIconWrapper> </ChannelHeaderPlug> `;
4,176
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/mobile_channel_header_plug/mobile_channel_header_plug.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount} from 'enzyme'; import React from 'react'; import type {Channel, ChannelMembership} from '@mattermost/types/channels'; import {AppCallResponseTypes} from 'mattermost-redux/constants/apps'; import type {Theme} from 'mattermost-redux/selectors/entities/preferences'; import MobileChannelHeaderPlug, {RawMobileChannelHeaderPlug} from 'plugins/mobile_channel_header_plug/mobile_channel_header_plug'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {createCallContext} from 'utils/apps'; describe('plugins/MobileChannelHeaderPlug', () => { const testPlug = { id: 'someid', pluginId: 'pluginid', icon: <i className='fa fa-anchor'/>, action: jest.fn(), dropdownText: 'some dropdown text', }; const testBinding = { app_id: 'appid', location: 'test', icon: 'http://test.com/icon.png', label: 'Label', hint: 'Hint', form: { submit: { path: '/call/path', }, }, }; const testChannel = {} as Channel; const testChannelMember = {} as ChannelMembership; const testTheme = {} as Theme; const intl = { formatMessage: (message: {id: string; defaultMessage: string}) => { return message.defaultMessage; }, } as any; test('should match snapshot with no extended component', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with one extended component', () => { const wrapper = mount<RawMobileChannelHeaderPlug>( <RawMobileChannelHeaderPlug components={[testPlug]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} intl={intl} />, ); expect(wrapper).toMatchSnapshot(); // Render a single list item containing a button expect(wrapper.find('li')).toHaveLength(1); expect(wrapper.find('button')).toHaveLength(1); wrapper.instance().fireAction = jest.fn(); wrapper.find('button').first().simulate('click'); expect(wrapper.instance().fireAction).toHaveBeenCalledTimes(1); expect(wrapper.instance().fireAction).toBeCalledWith(testPlug); }); test('should match snapshot with two extended components', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[testPlug, {...testPlug, id: 'someid2'}]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with no bindings', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={true} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with one binding', () => { const wrapper = mount<RawMobileChannelHeaderPlug>( <RawMobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={true} appBindings={[testBinding]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} intl={intl} />, ); expect(wrapper).toMatchSnapshot(); // Render a single list item containing a button expect(wrapper.find('li')).toHaveLength(1); expect(wrapper.find('button')).toHaveLength(1); wrapper.instance().fireAppAction = jest.fn(); wrapper.find('button').first().simulate('click'); expect(wrapper.instance().fireAppAction).toHaveBeenCalledTimes(1); expect(wrapper.instance().fireAppAction).toBeCalledWith(testBinding); }); test('should match snapshot with two bindings', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={false} appBindings={[testBinding, {...testBinding, app_id: 'app2'}]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with one extended components and one binding', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[testPlug]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={false} appsEnabled={true} appBindings={[testBinding]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with no extended component, in dropdown', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with one extended component, in dropdown', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[testPlug]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render a single list item containing an anchor expect(wrapper.find('li')).toHaveLength(1); expect(wrapper.find('a')).toHaveLength(1); }); test('should match snapshot with two extended components, in dropdown', () => { const wrapper = mount<RawMobileChannelHeaderPlug>( <RawMobileChannelHeaderPlug components={[testPlug, {...testPlug, id: 'someid2'}]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} intl={intl} />, ); expect(wrapper).toMatchSnapshot(); // Render a two list items containing anchors expect(wrapper.find('li')).toHaveLength(2); expect(wrapper.find('a')).toHaveLength(2); const instance = wrapper.instance(); instance.fireAction = jest.fn(); wrapper.find('a').first().simulate('click'); expect(instance.fireAction).toHaveBeenCalledTimes(1); expect(instance.fireAction).toBeCalledWith(testPlug); }); test('should match snapshot with no binding, in dropdown', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={true} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render nothing expect(wrapper.find('li').exists()).toBe(false); }); test('should match snapshot with one binding, in dropdown', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={true} appBindings={[testBinding]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render a single list item containing an anchor expect(wrapper.find('li')).toHaveLength(1); expect(wrapper.find('a')).toHaveLength(1); }); test('should match snapshot with two bindings, in dropdown', () => { const wrapper = mount<RawMobileChannelHeaderPlug>( <RawMobileChannelHeaderPlug components={[]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={true} appBindings={[testBinding, {...testBinding, app_id: 'app2'}]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} intl={intl} />, ); expect(wrapper).toMatchSnapshot(); // Render a two list items containing anchors expect(wrapper.find('li')).toHaveLength(2); expect(wrapper.find('a')).toHaveLength(2); const instance = wrapper.instance(); instance.fireAppAction = jest.fn(); wrapper.find('a').first().simulate('click'); expect(instance.fireAppAction).toHaveBeenCalledTimes(1); expect(instance.fireAppAction).toBeCalledWith(testBinding); }); test('should match snapshot with one extended component and one binding, in dropdown', () => { const wrapper = mountWithIntl( <MobileChannelHeaderPlug components={[testPlug]} channel={testChannel} channelMember={testChannelMember} theme={testTheme} isDropdown={true} appsEnabled={true} appBindings={[testBinding]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} />, ); expect(wrapper).toMatchSnapshot(); // Render a two list items containing anchors expect(wrapper.find('li')).toHaveLength(2); expect(wrapper.find('a')).toHaveLength(2); }); test('should call plugin.action on fireAction', () => { const channel = {id: 'channel_id'} as Channel; const channelMember = {} as ChannelMembership; const newTestPlug = { id: 'someid', pluginId: 'pluginid', icon: <i className='fa fa-anchor'/>, action: jest.fn(), dropdownText: 'some dropdown text', }; const wrapper = mount<RawMobileChannelHeaderPlug>( <RawMobileChannelHeaderPlug components={[newTestPlug]} channel={channel} channelMember={channelMember} theme={testTheme} isDropdown={true} appsEnabled={false} appBindings={[]} actions={{ handleBindingClick: jest.fn(), postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} intl={intl} />, ); wrapper.instance().fireAction(newTestPlug); expect(newTestPlug.action).toHaveBeenCalledTimes(1); expect(newTestPlug.action).toBeCalledWith(channel, channelMember); }); test('should call handleBindingClick on fireAppAction', () => { const channel = {id: 'channel_id'} as Channel; const channelMember = {} as ChannelMembership; const handleBindingClick = jest.fn().mockResolvedValue({data: {type: AppCallResponseTypes.OK}}); const wrapper = mount<RawMobileChannelHeaderPlug>( <RawMobileChannelHeaderPlug components={[]} channel={channel} channelMember={channelMember} theme={testTheme} isDropdown={true} appsEnabled={true} appBindings={[testBinding]} actions={{ handleBindingClick, postEphemeralCallResponseForChannel: jest.fn(), openAppsModal: jest.fn(), }} intl={intl} />, ); const context = createCallContext( testBinding.app_id, testBinding.location, channel.id, channel.team_id, ); wrapper.instance().fireAppAction(testBinding); expect(handleBindingClick).toHaveBeenCalledTimes(1); expect(handleBindingClick).toBeCalledWith(testBinding, context, expect.anything()); }); });
4,178
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/mobile_channel_header_plug
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/mobile_channel_header_plug/__snapshots__/mobile_channel_header_plug.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`plugins/MobileChannelHeaderPlug should match snapshot with no binding, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={true} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } isDropdown={true} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with no bindings 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={true} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } isDropdown={false} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with no extended component 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } isDropdown={false} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with no extended component, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } isDropdown={true} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with one binding 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={ Array [ Object { "app_id": "appid", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, ] } appsEnabled={true} channel={Object {}} channelMember={Object {}} components={Array []} intl={ Object { "formatMessage": [Function], } } isDropdown={false} theme={Object {}} > <li className="flex-parent--center" > <button className="navbar-toggle navbar-right__icon" id="appid_test" onClick={[Function]} > <span className="icon navbar-plugin-button" > <img height="16" src="http://test.com/icon.png" width="16" /> </span> </button> </li> </MobileChannelHeaderPlug> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with one binding, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={ Array [ Object { "app_id": "appid", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, ] } appsEnabled={true} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } isDropdown={true} theme={Object {}} > <li className="MenuItem" key="mobileChannelHeaderItemappidtest" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > Label </a> </li> </MobileChannelHeaderPlug> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with one extended component 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", }, ] } intl={ Object { "formatMessage": [Function], } } isDropdown={false} theme={Object {}} > <li className="flex-parent--center" > <button className="navbar-toggle navbar-right__icon" onClick={[Function]} > <span className="icon navbar-plugin-button" > <i className="fa fa-anchor" /> </span> </button> </li> </MobileChannelHeaderPlug> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with one extended component and one binding, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={ Array [ Object { "app_id": "appid", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, ] } appsEnabled={true} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", }, ] } 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", } } isDropdown={true} theme={Object {}} > <li className="MenuItem" key="mobileChannelHeaderItemsomeid" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > some dropdown text </a> </li> <li className="MenuItem" key="mobileChannelHeaderItemappidtest" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > Label </a> </li> </MobileChannelHeaderPlug> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with one extended component, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", }, ] } 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", } } isDropdown={true} theme={Object {}} > <li className="MenuItem" key="mobileChannelHeaderItemsomeid" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > some dropdown text </a> </li> </MobileChannelHeaderPlug> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with one extended components and one binding 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={ Array [ Object { "app_id": "appid", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, ] } appsEnabled={true} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", }, ] } 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", } } isDropdown={false} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with two bindings 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={ Array [ Object { "app_id": "appid", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, Object { "app_id": "app2", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, ] } appsEnabled={false} channel={Object {}} channelMember={Object {}} components={Array []} 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", } } isDropdown={false} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with two bindings, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={ Array [ Object { "app_id": "appid", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, Object { "app_id": "app2", "form": Object { "submit": Object { "path": "/call/path", }, }, "hint": "Hint", "icon": "http://test.com/icon.png", "label": "Label", "location": "test", }, ] } appsEnabled={true} channel={Object {}} channelMember={Object {}} components={Array []} intl={ Object { "formatMessage": [Function], } } isDropdown={true} theme={Object {}} > <li className="MenuItem" key="mobileChannelHeaderItemappidtest" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > Label </a> </li> <li className="MenuItem" key="mobileChannelHeaderItemapp2test" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > Label </a> </li> </MobileChannelHeaderPlug> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with two extended components 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", }, Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid2", "pluginId": "pluginid", }, ] } 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", } } isDropdown={false} theme={Object {}} /> `; exports[`plugins/MobileChannelHeaderPlug should match snapshot with two extended components, in dropdown 1`] = ` <MobileChannelHeaderPlug actions={ Object { "handleBindingClick": [MockFunction], "openAppsModal": [MockFunction], "postEphemeralCallResponseForChannel": [MockFunction], } } appBindings={Array []} appsEnabled={false} channel={Object {}} channelMember={Object {}} components={ Array [ Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid", "pluginId": "pluginid", }, Object { "action": [MockFunction], "dropdownText": "some dropdown text", "icon": <i className="fa fa-anchor" />, "id": "someid2", "pluginId": "pluginid", }, ] } intl={ Object { "formatMessage": [Function], } } isDropdown={true} theme={Object {}} > <li className="MenuItem" key="mobileChannelHeaderItemsomeid" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > some dropdown text </a> </li> <li className="MenuItem" key="mobileChannelHeaderItemsomeid2" role="presentation" > <a href="#" onClick={[Function]} role="menuitem" > some dropdown text </a> </li> </MobileChannelHeaderPlug> `;
4,181
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/pluggable/pluggable.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Preferences} from 'mattermost-redux/constants'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import Pluggable from './pluggable'; class ProfilePopoverPlugin extends React.PureComponent { render() { return <span id='pluginId'>{'ProfilePopoverPlugin'}</span>; } } jest.mock('actions/views/profile_popover'); describe('plugins/Pluggable', () => { const baseProps = { pluggableName: '', components: { Product: [], CallButton: [], PostDropdownMenu: [], PostAction: [], PostEditorAction: [], CodeBlockAction: [], NewMessagesSeparatorAction: [], FilePreview: [], MainMenu: [], LinkTooltip: [], RightHandSidebarComponent: [], ChannelHeaderButton: [], MobileChannelHeaderButton: [], AppBar: [], UserGuideDropdownItem: [], FilesWillUploadHook: [], NeedsTeamComponent: [], CreateBoardFromTemplate: [], DesktopNotificationHooks: [], }, theme: Preferences.THEMES.denim, }; test('should match snapshot with no extended component', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with extended component', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} pluggableName='PopoverSection1' components={{...baseProps.components, PopoverSection1: [{id: '', pluginId: '', component: ProfilePopoverPlugin}]}} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('#pluginId').text()).toBe('ProfilePopoverPlugin'); expect(wrapper.find(ProfilePopoverPlugin).exists()).toBe(true); }); test('should match snapshot with extended component with pluggableName', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} pluggableName='PopoverSection1' components={{...baseProps.components, PopoverSection1: [{id: '', pluginId: '', component: ProfilePopoverPlugin}]}} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('#pluginId').text()).toBe('ProfilePopoverPlugin'); expect(wrapper.find(ProfilePopoverPlugin).exists()).toBe(true); }); test('should return null if neither pluggableName nor children is is defined in props', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} components={{...baseProps.components, PopoverSection1: [{id: '', pluginId: '', component: ProfilePopoverPlugin}]}} />, ); expect(wrapper.find(ProfilePopoverPlugin).exists()).toBe(false); }); test('should return null if with pluggableName but no children', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} pluggableName='PopoverSection1' />, ); expect(wrapper.children().length).toBe(0); }); test('should match snapshot with non-null pluggableId', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} pluggableName='PopoverSection1' pluggableId={'pluggableId'} components={{...baseProps.components, PopoverSection1: [{id: '', pluginId: '', component: ProfilePopoverPlugin}]}} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(ProfilePopoverPlugin).exists()).toBe(false); }); test('should match snapshot with null pluggableId', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} pluggableName='PopoverSection1' components={{...baseProps.components, PopoverSection1: [{id: '', pluginId: '', component: ProfilePopoverPlugin}]}} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(ProfilePopoverPlugin).exists()).toBe(true); }); test('should match snapshot with valid pluggableId', () => { const wrapper = mountWithIntl( <Pluggable {...baseProps} pluggableName='PopoverSection1' pluggableId={'pluggableId'} components={{...baseProps.components, PopoverSection1: [{id: 'pluggableId', pluginId: '', component: ProfilePopoverPlugin}]}} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(ProfilePopoverPlugin).exists()).toBe(true); }); });
4,183
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/pluggable
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/pluggable/__snapshots__/pluggable.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`plugins/Pluggable should match snapshot with extended component 1`] = ` <Pluggable components={ Object { "AppBar": Array [], "CallButton": Array [], "ChannelHeaderButton": Array [], "CodeBlockAction": Array [], "CreateBoardFromTemplate": Array [], "DesktopNotificationHooks": Array [], "FilePreview": Array [], "FilesWillUploadHook": Array [], "LinkTooltip": Array [], "MainMenu": Array [], "MobileChannelHeaderButton": Array [], "NeedsTeamComponent": Array [], "NewMessagesSeparatorAction": Array [], "PopoverSection1": Array [ Object { "component": [Function], "id": "", "pluginId": "", }, ], "PostAction": Array [], "PostDropdownMenu": Array [], "PostEditorAction": Array [], "Product": Array [], "RightHandSidebarComponent": Array [], "UserGuideDropdownItem": Array [], } } pluggableName="PopoverSection1" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } > <PluggableErrorBoundary key="PopoverSection1" pluginId="" > <ProfilePopoverPlugin theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } webSocketClient={ WebSocketClient { "closeCallback": null, "closeListeners": Set {}, "conn": null, "connectFailCount": 0, "connectionId": "", "connectionUrl": null, "errorCallback": null, "errorListeners": Set {}, "eventCallback": null, "firstConnectCallback": null, "firstConnectListeners": Set {}, "messageListeners": Set {}, "missedEventCallback": null, "missedMessageListeners": Set {}, "reconnectCallback": null, "reconnectListeners": Set {}, "responseCallbacks": Object {}, "responseSequence": 1, "serverSequence": 0, } } > <span id="pluginId" > ProfilePopoverPlugin </span> </ProfilePopoverPlugin> </PluggableErrorBoundary> </Pluggable> `; exports[`plugins/Pluggable should match snapshot with extended component with pluggableName 1`] = ` <Pluggable components={ Object { "AppBar": Array [], "CallButton": Array [], "ChannelHeaderButton": Array [], "CodeBlockAction": Array [], "CreateBoardFromTemplate": Array [], "DesktopNotificationHooks": Array [], "FilePreview": Array [], "FilesWillUploadHook": Array [], "LinkTooltip": Array [], "MainMenu": Array [], "MobileChannelHeaderButton": Array [], "NeedsTeamComponent": Array [], "NewMessagesSeparatorAction": Array [], "PopoverSection1": Array [ Object { "component": [Function], "id": "", "pluginId": "", }, ], "PostAction": Array [], "PostDropdownMenu": Array [], "PostEditorAction": Array [], "Product": Array [], "RightHandSidebarComponent": Array [], "UserGuideDropdownItem": Array [], } } pluggableName="PopoverSection1" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } > <PluggableErrorBoundary key="PopoverSection1" pluginId="" > <ProfilePopoverPlugin theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } webSocketClient={ WebSocketClient { "closeCallback": null, "closeListeners": Set {}, "conn": null, "connectFailCount": 0, "connectionId": "", "connectionUrl": null, "errorCallback": null, "errorListeners": Set {}, "eventCallback": null, "firstConnectCallback": null, "firstConnectListeners": Set {}, "messageListeners": Set {}, "missedEventCallback": null, "missedMessageListeners": Set {}, "reconnectCallback": null, "reconnectListeners": Set {}, "responseCallbacks": Object {}, "responseSequence": 1, "serverSequence": 0, } } > <span id="pluginId" > ProfilePopoverPlugin </span> </ProfilePopoverPlugin> </PluggableErrorBoundary> </Pluggable> `; exports[`plugins/Pluggable should match snapshot with no extended component 1`] = ` <Pluggable components={ Object { "AppBar": Array [], "CallButton": Array [], "ChannelHeaderButton": Array [], "CodeBlockAction": Array [], "CreateBoardFromTemplate": Array [], "DesktopNotificationHooks": Array [], "FilePreview": Array [], "FilesWillUploadHook": Array [], "LinkTooltip": Array [], "MainMenu": Array [], "MobileChannelHeaderButton": Array [], "NeedsTeamComponent": Array [], "NewMessagesSeparatorAction": Array [], "PostAction": Array [], "PostDropdownMenu": Array [], "PostEditorAction": Array [], "Product": Array [], "RightHandSidebarComponent": Array [], "UserGuideDropdownItem": Array [], } } pluggableName="" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } /> `; exports[`plugins/Pluggable should match snapshot with non-null pluggableId 1`] = ` <Pluggable components={ Object { "AppBar": Array [], "CallButton": Array [], "ChannelHeaderButton": Array [], "CodeBlockAction": Array [], "CreateBoardFromTemplate": Array [], "DesktopNotificationHooks": Array [], "FilePreview": Array [], "FilesWillUploadHook": Array [], "LinkTooltip": Array [], "MainMenu": Array [], "MobileChannelHeaderButton": Array [], "NeedsTeamComponent": Array [], "NewMessagesSeparatorAction": Array [], "PopoverSection1": Array [ Object { "component": [Function], "id": "", "pluginId": "", }, ], "PostAction": Array [], "PostDropdownMenu": Array [], "PostEditorAction": Array [], "Product": Array [], "RightHandSidebarComponent": Array [], "UserGuideDropdownItem": Array [], } } pluggableId="pluggableId" pluggableName="PopoverSection1" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } /> `; exports[`plugins/Pluggable should match snapshot with null pluggableId 1`] = ` <Pluggable components={ Object { "AppBar": Array [], "CallButton": Array [], "ChannelHeaderButton": Array [], "CodeBlockAction": Array [], "CreateBoardFromTemplate": Array [], "DesktopNotificationHooks": Array [], "FilePreview": Array [], "FilesWillUploadHook": Array [], "LinkTooltip": Array [], "MainMenu": Array [], "MobileChannelHeaderButton": Array [], "NeedsTeamComponent": Array [], "NewMessagesSeparatorAction": Array [], "PopoverSection1": Array [ Object { "component": [Function], "id": "", "pluginId": "", }, ], "PostAction": Array [], "PostDropdownMenu": Array [], "PostEditorAction": Array [], "Product": Array [], "RightHandSidebarComponent": Array [], "UserGuideDropdownItem": Array [], } } pluggableName="PopoverSection1" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } > <PluggableErrorBoundary key="PopoverSection1" pluginId="" > <ProfilePopoverPlugin theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } webSocketClient={ WebSocketClient { "closeCallback": null, "closeListeners": Set {}, "conn": null, "connectFailCount": 0, "connectionId": "", "connectionUrl": null, "errorCallback": null, "errorListeners": Set {}, "eventCallback": null, "firstConnectCallback": null, "firstConnectListeners": Set {}, "messageListeners": Set {}, "missedEventCallback": null, "missedMessageListeners": Set {}, "reconnectCallback": null, "reconnectListeners": Set {}, "responseCallbacks": Object {}, "responseSequence": 1, "serverSequence": 0, } } > <span id="pluginId" > ProfilePopoverPlugin </span> </ProfilePopoverPlugin> </PluggableErrorBoundary> </Pluggable> `; exports[`plugins/Pluggable should match snapshot with valid pluggableId 1`] = ` <Pluggable components={ Object { "AppBar": Array [], "CallButton": Array [], "ChannelHeaderButton": Array [], "CodeBlockAction": Array [], "CreateBoardFromTemplate": Array [], "DesktopNotificationHooks": Array [], "FilePreview": Array [], "FilesWillUploadHook": Array [], "LinkTooltip": Array [], "MainMenu": Array [], "MobileChannelHeaderButton": Array [], "NeedsTeamComponent": Array [], "NewMessagesSeparatorAction": Array [], "PopoverSection1": Array [ Object { "component": [Function], "id": "pluggableId", "pluginId": "", }, ], "PostAction": Array [], "PostDropdownMenu": Array [], "PostEditorAction": Array [], "Product": Array [], "RightHandSidebarComponent": Array [], "UserGuideDropdownItem": Array [], } } pluggableId="pluggableId" pluggableName="PopoverSection1" theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } > <PluggableErrorBoundary key="PopoverSection1pluggableId" pluginId="" > <ProfilePopoverPlugin theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } webSocketClient={ WebSocketClient { "closeCallback": null, "closeListeners": Set {}, "conn": null, "connectFailCount": 0, "connectionId": "", "connectionUrl": null, "errorCallback": null, "errorListeners": Set {}, "eventCallback": null, "firstConnectCallback": null, "firstConnectListeners": Set {}, "messageListeners": Set {}, "missedEventCallback": null, "missedMessageListeners": Set {}, "reconnectCallback": null, "reconnectListeners": Set {}, "responseCallbacks": Object {}, "responseSequence": 1, "serverSequence": 0, } } > <span id="pluginId" > ProfilePopoverPlugin </span> </ProfilePopoverPlugin> </PluggableErrorBoundary> </Pluggable> `;
4,186
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/test/main_menu_action.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {UserProfile} from '@mattermost/types/users'; import MainMenu from 'components/main_menu/main_menu'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; describe('plugins/MainMenuActions', () => { const pluginAction = jest.fn(); const requiredProps = { teamId: 'someteamid', teamType: '', teamDisplayName: 'some name', teamName: 'somename', currentUser: {id: 'someuserid', roles: 'system_user'} as UserProfile, enableCommands: true, enableCustomEmoji: true, enableIncomingWebhooks: true, enableOutgoingWebhooks: true, enableOAuthServiceProvider: true, canManageSystemBots: true, enableUserCreation: true, enableEmailInvitations: false, enablePluginMarketplace: true, showDropdown: true, onToggleDropdown: () => {}, //eslint-disable-line no-empty-function pluginMenuItems: [{id: 'someplugin', pluginId: 'test', text: 'some plugin text', action: pluginAction}], canCreateOrDeleteCustomEmoji: true, canManageIntegrations: true, moreTeamsToJoin: true, guestAccessEnabled: true, teamIsGroupConstrained: true, teamUrl: '/team', location: { pathname: '/team', }, actions: { openModal: jest.fn(), showMentions: jest.fn(), showFlaggedPosts: jest.fn(), closeRightHandSide: jest.fn(), closeRhsMenu: jest.fn(), getCloudLimits: jest.fn(), }, isCloud: false, isStarterFree: false, subscription: {}, userIsAdmin: true, isFirstAdmin: false, canInviteTeamMember: false, isFreeTrial: false, teamsLimitReached: false, usageDeltaTeams: -1, mobile: false, }; test('should match snapshot in web view', () => { let wrapper = shallowWithIntl( <MainMenu {...requiredProps} />, ); wrapper = wrapper.shallow(); expect(wrapper).toMatchSnapshot(); expect(wrapper.findWhere((node) => node.key() === 'someplugin_pluginmenuitem')).toHaveLength(1); }); test('should match snapshot in mobile view with some plugin and ability to click plugin', () => { const props = { ...requiredProps, mobile: true, }; let wrapper = shallowWithIntl( <MainMenu {...props} />, ); wrapper = wrapper.shallow(); expect(wrapper).toMatchSnapshot(); expect(wrapper.findWhere((node) => node.key() === 'someplugin_pluginmenuitem')).toHaveLength(1); wrapper.findWhere((node) => node.key() === 'someplugin_pluginmenuitem').simulate('click'); expect(pluginAction).toBeCalled(); }); });
4,187
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/test/post_type.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow, mount} from 'enzyme'; import React from 'react'; import {Preferences} from 'mattermost-redux/constants'; import PostMessageView from 'components/post_view/post_message_view/post_message_view'; class PostTypePlugin extends React.PureComponent { render() { return <span id='pluginId'>{'PostTypePlugin'}</span>; } } describe('plugins/PostMessageView', () => { const post = {type: 'testtype', message: 'this is some text', id: 'post_id'} as any; const pluginPostTypes = { testtype: {component: PostTypePlugin}, }; const requiredProps = { post, pluginPostTypes, currentUser: {username: 'username'}, team: {name: 'team_name'}, emojis: {name: 'smile'}, theme: Preferences.THEMES.denim, enableFormatting: true, currentRelativeTeamUrl: 'team_url', }; test('should match snapshot with extended post type', () => { const wrapper = mount( <PostMessageView {...requiredProps}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('#pluginId').text()).toBe('PostTypePlugin'); }); test('should match snapshot with no extended post type', () => { const props = {...requiredProps, pluginPostTypes: {}}; const wrapper = shallow( <PostMessageView {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
4,188
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/test
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/test/__snapshots__/main_menu_action.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`plugins/MainMenuActions should match snapshot in mobile view with some plugin and ability to click plugin 1`] = ` <div aria-label="main menu" className="a11y__popup Menu" role="menu" > <ul className="Menu__content dropdown-menu" onClick={[Function]} style={Object {}} > <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_billing", ] } > <MenuCloudTrial id="menuCloudTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "sysconsole_write_about_edition_and_license", ] } > <MenuStartTrial id="startTrial" /> </Connect(SystemPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="mentions" > @ </i> } id="recentMentions" onClick={[Function]} show={true} text="Recent Mentions" /> <MenuItemAction icon={ <i className="fa fa-bookmark" /> } id="flaggedPosts" onClick={[Function]} show={true} text="Saved messages" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": false, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user" /> } id="profileSettings" modalId="user_settings" show={true} text="Profile" /> <MenuItemToggleModalRedux dialogProps={ Object { "isContentProductSettings": true, } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-cog" /> } id="accountSettings" modalId="user_settings" show={true} text="Settings" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="addGroupsToTeam" modalId="add_groups_to_team" show={true} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={ <i className="fa fa-user-plus" /> } id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-globe" /> } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "someteamid", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-user-plus" /> } id="manageGroups" modalId="manage_team_groups" show={true} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-users" /> } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="createTeam" show={true} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <MenuItemLink icon={ <i className="fa fa-plus-square" /> } id="joinTeam" show={true} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={<LeaveTeamIcon />} id="leaveTeam" modalId="leave_team" show={false} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction id="someplugin_pluginmenuitem" key="someplugin_pluginmenuitem" onClick={[Function]} show={true} text="some plugin text" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemLink id="integrations" show={false} text="Integrations" to="/somename/integrations" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemExternalLink icon={ <i className="fa fa-question" /> } id="helpLink" show={false} text="Help" /> <MenuItemExternalLink icon={ <i className="fa fa-phone" /> } id="reportLink" show={false} text="Report a Problem" /> <MenuItemExternalLink icon={ <i className="fa fa-mobile" /> } id="nativeAppLink" show={true} text="Download Apps" url="" /> <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } icon={ <i className="fa fa-info" /> } id="about" modalId="about" show={true} text="About Mattermost" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={ <i className="fa fa-sign-out" /> } id="logout" onClick={[Function]} show={true} text="Log Out" /> </Memo(MenuGroup)> </ul> </div> `; exports[`plugins/MainMenuActions should match snapshot in web view 1`] = ` <div aria-label="team menu" className="a11y__popup Menu" role="menu" > <ul className="Menu__content dropdown-menu" onClick={[Function]} style={Object {}} > <Memo(MenuGroup)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="addGroupsToTeam" modalId="add_groups_to_team" show={true} text="Add Groups to Team" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "add_user_to_team", "invite_guest", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } extraText="Add people to the team" icon={false} id="invitePeople" modalId="invitation" onClick={[Function]} show={true} text="Invite People" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="teamSettings" modalId="team_settings" show={true} text="Team Settings" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "manage_team", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogProps={ Object { "teamID": "someteamid", } } dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageGroups" modalId="manage_team_groups" show={true} text="Manage Groups" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="manageMembers" modalId="team_members" show={true} text="Manage Members" /> </Connect(TeamPermissionGate)> <Connect(TeamPermissionGate) invert={true} permissions={ Array [ "remove_user_from_team", "manage_team_roles", ] } teamId="someteamid" > <MenuItemToggleModalRedux dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="viewMembers" modalId="team_members" show={true} text="View Members" /> </Connect(TeamPermissionGate)> <MenuItemLink id="joinTeam" show={true} text="Join Another Team" to="/select_team" /> <MenuItemToggleModalRedux className="destructive" dialogType={ Object { "$$typeof": Symbol(react.memo), "WrappedComponent": [Function], "compare": null, "type": [Function], } } id="leaveTeam" modalId="leave_team" show={false} text="Leave Team" /> </Memo(MenuGroup)> <Memo(MenuGroup)> <Connect(SystemPermissionGate) permissions={ Array [ "create_team", ] } > <MenuItemLink className="" disabled={false} id="createTeam" show={true} sibling={false} text="Create a Team" to="/create_team" /> </Connect(SystemPermissionGate)> <Memo(MenuGroup)> <div className="MainMenu_dropdown-link" > <LearnAboutTeamsLink /> </div> </Memo(MenuGroup)> </Memo(MenuGroup)> <Memo(MenuGroup)> <MenuItemAction icon={false} id="someplugin_pluginmenuitem" key="someplugin_pluginmenuitem" onClick={[Function]} show={true} text="some plugin text" /> </Memo(MenuGroup)> </ul> </div> `;
4,189
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/test
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/test/__snapshots__/post_type.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`plugins/PostMessageView should match snapshot with extended post type 1`] = ` <PostMessageView currentRelativeTeamUrl="team_url" currentUser={ Object { "username": "username", } } emojis={ Object { "name": "smile", } } enableFormatting={true} isRHS={false} options={Object {}} pluginPostTypes={ Object { "testtype": Object { "component": [Function], }, } } post={ Object { "id": "post_id", "message": "this is some text", "type": "testtype", } } team={ Object { "name": "team_name", } } theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } > <PostTypePlugin isRHS={false} post={ Object { "id": "post_id", "message": "this is some text", "type": "testtype", } } theme={ Object { "awayIndicator": "#ffbc1f", "buttonBg": "#1c58d9", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3f4350", "codeTheme": "github", "dndIndicator": "#d24b4e", "errorTextColor": "#d24b4e", "linkColor": "#386fe5", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#1e325c", "mentionHighlightBg": "#ffd470", "mentionHighlightLink": "#1b1d22", "newMessageSeparator": "#cc8f00", "onlineIndicator": "#3db887", "sidebarBg": "#1e325c", "sidebarHeaderBg": "#192a4d", "sidebarHeaderTextColor": "#ffffff", "sidebarTeamBarBg": "#14213e", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#5d89ea", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#28427b", "sidebarUnreadText": "#ffffff", "type": "Denim", } } > <span id="pluginId" > PostTypePlugin </span> </PostTypePlugin> </PostMessageView> `; exports[`plugins/PostMessageView should match snapshot with no extended post type 1`] = ` <Connect(ShowMore) checkOverflow={0} text="this is some text" > <div className="post-message__text" dir="auto" id="postMessageText_post_id" onClick={[Function]} tabIndex={0} > <Connect(PostMarkdown) imageProps={ Object { "onImageHeightChanged": [Function], "onImageLoaded": [Function], } } message="this is some text" options={Object {}} post={ Object { "id": "post_id", "message": "this is some text", "type": "testtype", } } /> </div> <Connect(Pluggable) onHeightChange={[Function]} pluggableName="PostMessageAttachment" postId="post_id" /> </Connect(ShowMore)> `;
4,190
0
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins
petrpan-code/mattermost/mattermost/webapp/channels/src/plugins/textbox/index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import Textbox from 'components/textbox'; import PluginTextbox from '.'; describe('PluginTextbox', () => { const baseProps = { id: 'id', channelId: 'channelId', rootId: 'rootId', tabIndex: -1, value: '', onChange: jest.fn(), onKeyPress: jest.fn(), createMessage: 'This is a placeholder', supportsCommands: true, characterLimit: 10000, currentUserId: 'currentUserId', currentTeamId: 'currentTeamId', profilesInChannel: [], autocompleteGroups: null, actions: { autocompleteUsersInChannel: jest.fn(), autocompleteChannels: jest.fn(), searchAssociatedGroupsForReference: jest.fn(), }, useChannelMentions: true, }; test('should rename suggestionListStyle to suggestionListPosition', () => { const props: React.ComponentProps<typeof PluginTextbox> = { ...baseProps, suggestionListStyle: 'bottom', }; const wrapper = shallow(<PluginTextbox {...props}/>); expect(wrapper.find(Textbox).prop('suggestionListPosition')).toEqual('bottom'); expect(wrapper.find(Textbox).prop('suggestionListStyle')).toBeUndefined(); }); });
4,193
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/storage.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GenericAction} from 'mattermost-redux/types/actions'; import storageReducer from 'reducers/storage'; import {StorageTypes} from 'utils/constants'; type ReducerState = ReturnType<typeof storageReducer>; describe('Reducers.Storage', () => { const now = new Date(); it('Storage.SET_ITEM', () => { const nextState = storageReducer( { storage: {}, } as ReducerState, { type: StorageTypes.SET_ITEM, data: { name: 'key', prefix: 'user_id_', value: 'value', timestamp: now, }, }, ); expect(nextState.storage).toEqual({ user_id_key: {value: 'value', timestamp: now}, }); }); it('Storage.SET_GLOBAL_ITEM', () => { const nextState = storageReducer( { storage: {}, } as ReducerState, { type: StorageTypes.SET_GLOBAL_ITEM, data: { name: 'key', value: 'value', timestamp: now, }, }, ); expect(nextState.storage).toEqual({ key: {value: 'value', timestamp: now}, }); }); it('Storage.REMOVE_ITEM', () => { let nextState = storageReducer( { storage: { user_id_key: 'value', }, } as unknown as ReducerState, { type: StorageTypes.REMOVE_ITEM, data: { name: 'key', prefix: 'user_id_', }, }, ); expect(nextState.storage).toEqual({}); nextState = storageReducer( { storage: {}, } as ReducerState, { type: StorageTypes.REMOVE_ITEM, data: { name: 'key', prefix: 'user_id_', }, }, ); expect(nextState.storage).toEqual({}); }); it('Storage.REMOVE_GLOBAL_ITEM', () => { let nextState = storageReducer( { storage: { key: 'value', }, } as unknown as ReducerState, { type: StorageTypes.REMOVE_GLOBAL_ITEM, data: { name: 'key', }, }, ); expect(nextState.storage).toEqual({}); nextState = storageReducer( { storage: {}, } as ReducerState, { type: StorageTypes.REMOVE_GLOBAL_ITEM, data: { name: 'key', }, }, ); expect(nextState.storage).toEqual({}); }); describe('Storage.ACTION_ON_GLOBAL_ITEMS_WITH_PREFIX', () => { it('should call the provided action on the given objects', () => { const state = storageReducer({ storage: { prefix_key1: {value: 1, timestamp: now}, prefix_key2: {value: 2, timestamp: now}, not_prefix_key: {value: 3, timestamp: now}, }, } as unknown as ReducerState, {} as GenericAction); const nextState = storageReducer(state, { type: StorageTypes.ACTION_ON_GLOBAL_ITEMS_WITH_PREFIX, data: { prefix: 'prefix', action: (_key: string, value: number) => value + 5, }, }); expect(nextState).not.toBe(state); expect(nextState.storage.prefix_key1.value).toBe(6); expect(nextState.storage.prefix_key1.timestamp).not.toBe(now); expect(nextState.storage.prefix_key2.value).toBe(7); expect(nextState.storage.prefix_key2.timestamp).not.toBe(now); expect(nextState.storage.prefix_key3).toBe(state.storage.prefix_key3); }); it('should return the original state if no results change', () => { const state = storageReducer({ storage: { prefix_key1: {value: 1, timestamp: now}, prefix_key2: {value: 2, timestamp: now}, not_prefix_key: {value: 3, timestamp: now}, }, } as unknown as ReducerState, {} as GenericAction); const nextState = storageReducer(state, { type: StorageTypes.ACTION_ON_GLOBAL_ITEMS_WITH_PREFIX, data: { prefix: 'prefix', action: (key: string, value: number) => value, }, }); expect(nextState).toBe(state); }); }); it('Storage.STORAGE_REHYDRATE', () => { let nextState = storageReducer( { storage: {}, } as ReducerState, { type: StorageTypes.STORAGE_REHYDRATE, data: {test: '123'}, }, ); expect(nextState.storage).toEqual({test: '123'}); nextState = storageReducer( nextState, { type: StorageTypes.STORAGE_REHYDRATE, data: {test: '456'}, }, ); expect(nextState.storage).toEqual({test: '456'}); nextState = storageReducer( nextState, { type: StorageTypes.STORAGE_REHYDRATE, data: {test2: '789'}, }, ); expect(nextState.storage).toEqual({test: '456', test2: '789'}); }); });
4,198
0
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/views/admin.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {ActionTypes} from 'utils/constants'; import {needsLoggedInLimitReachedCheck} from './admin'; describe('views/admin reducers', () => { describe('needsLoggedInLimitReachedCheck', () => { it('defaults to false', () => { const actual = needsLoggedInLimitReachedCheck(undefined, {type: 'asdf'}); expect(actual).toBe(false); }); it('is set by NEEDS_LOGGED_IN_LIMIT_REACHED_CHECK', () => { const falseValue = needsLoggedInLimitReachedCheck( undefined, {type: ActionTypes.NEEDS_LOGGED_IN_LIMIT_REACHED_CHECK, data: false}, ); expect(falseValue).toBe(false); const trueValue = needsLoggedInLimitReachedCheck( false, {type: ActionTypes.NEEDS_LOGGED_IN_LIMIT_REACHED_CHECK, data: true}, ); expect(trueValue).toBe(true); }); }); });
4,206
0
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/views/channel_sidebar.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {ActionTypes} from 'utils/constants'; import * as Reducers from './channel_sidebar'; describe('multiSelectedChannelIds', () => { test('should select single channel when it does not exist in the list', () => { const initialState = [ 'channel-1', 'channel-2', 'channel-3', ]; const state = Reducers.multiSelectedChannelIds( initialState, { type: ActionTypes.MULTISELECT_CHANNEL, data: 'new-channel', }, ); expect(state).toEqual(['new-channel']); }); test('should select single channel when it does exist in the list', () => { const initialState = [ 'channel-1', 'channel-2', 'channel-3', ]; const state = Reducers.multiSelectedChannelIds( initialState, { type: ActionTypes.MULTISELECT_CHANNEL, data: 'channel-1', }, ); expect(state).toEqual(['channel-1']); }); test('should remove selection if its the only channel in the list', () => { const initialState = [ 'channel-1', ]; const state = Reducers.multiSelectedChannelIds( initialState, { type: ActionTypes.MULTISELECT_CHANNEL, data: 'channel-1', }, ); expect(state).toEqual([]); }); test('should select channel if added with Ctrl+Click and not present in list', () => { const initialState = [ 'channel-1', 'channel-2', ]; const state = Reducers.multiSelectedChannelIds( initialState, { type: ActionTypes.MULTISELECT_CHANNEL_ADD, data: 'channel-3', }, ); expect(state).toEqual([ 'channel-1', 'channel-2', 'channel-3', ]); }); test('should unselect channel if added with Ctrl+Click and is present in list', () => { const initialState = [ 'channel-1', 'channel-2', 'channel-3', ]; const state = Reducers.multiSelectedChannelIds( initialState, { type: ActionTypes.MULTISELECT_CHANNEL_ADD, data: 'channel-3', }, ); expect(state).toEqual([ 'channel-1', 'channel-2', ]); }); test('should not update state when clearing without a selection', () => { const initialState: string[] = []; const state = Reducers.multiSelectedChannelIds( initialState, { type: ActionTypes.MULTISELECT_CHANNEL_CLEAR, }, ); expect(state).toBe(initialState); }); });
4,212
0
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/views/lhs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {TeamTypes} from 'mattermost-redux/action_types'; import type {GenericAction} from 'mattermost-redux/types/actions'; import lhsReducer from 'reducers/views/lhs'; import {ActionTypes} from 'utils/constants'; describe('Reducers.LHS', () => { const initialState = { isOpen: false, currentStaticPageId: '', size: 'medium', }; test('initial state', () => { const nextState = lhsReducer( { isOpen: false, currentStaticPageId: '', size: 'medium', }, {} as GenericAction, ); expect(nextState).toEqual(initialState); }); test(`should close on ${ActionTypes.TOGGLE_LHS}`, () => { const nextState = lhsReducer( { isOpen: true, currentStaticPageId: '', size: 'medium', }, { type: ActionTypes.TOGGLE_LHS, }, ); expect(nextState).toEqual({ ...initialState, isOpen: false, }); }); test(`should open on ${ActionTypes.TOGGLE_LHS}`, () => { const nextState = lhsReducer( { isOpen: false, currentStaticPageId: '', size: 'medium', }, { type: ActionTypes.TOGGLE_LHS, }, ); expect(nextState).toEqual({ ...initialState, isOpen: true, }); }); test(`should open on ${ActionTypes.OPEN_LHS}`, () => { const nextState = lhsReducer( { isOpen: false, currentStaticPageId: '', size: 'medium', }, { type: ActionTypes.OPEN_LHS, }, ); expect(nextState).toEqual({ ...initialState, isOpen: true, }); }); test(`should close on ${ActionTypes.CLOSE_LHS}`, () => { const nextState = lhsReducer( { isOpen: true, currentStaticPageId: '', size: 'medium', }, { type: ActionTypes.CLOSE_LHS, }, ); expect(nextState).toEqual({ ...initialState, isOpen: false, }); }); describe('should close', () => { [ ActionTypes.TOGGLE_RHS_MENU, ActionTypes.OPEN_RHS_MENU, TeamTypes.SELECT_TEAM, ].forEach((action) => { it(`on ${action}`, () => { const nextState = lhsReducer( { isOpen: true, currentStaticPageId: '', size: 'medium', }, { type: action, }, ); expect(nextState).toEqual({ ...initialState, isOpen: false, }); }); }); }); });
4,214
0
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/views/marketplace.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {MarketplacePlugin} from '@mattermost/types/marketplace'; import type {GenericAction} from 'mattermost-redux/types/actions'; import marketplaceReducer from 'reducers/views/marketplace'; import {ActionTypes, ModalIdentifiers} from 'utils/constants'; describe('marketplace', () => { test('initial state', () => { const currentState = {} as never; const action: GenericAction = {} as GenericAction; const expectedState = { plugins: [], apps: [], installing: {}, errors: {}, filter: '', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); test(ActionTypes.RECEIVED_MARKETPLACE_PLUGINS, () => { const currentState = { plugins: [], apps: [], installing: {}, errors: {}, filter: '', }; const action: GenericAction = { type: ActionTypes.RECEIVED_MARKETPLACE_PLUGINS, plugins: [{id: 'plugin1'}, {id: 'plugin2'}], }; const expectedState = { plugins: [{id: 'plugin1'}, {id: 'plugin2'}], apps: [], installing: {}, errors: {}, filter: '', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); describe(ActionTypes.INSTALLING_MARKETPLACE_ITEM, () => { const currentState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; it('should set installing for not already installing plugin', () => { const action: GenericAction = { type: ActionTypes.INSTALLING_MARKETPLACE_ITEM, id: 'plugin2', }; const expectedState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); it('should no-op for already installing plugin', () => { const action: GenericAction = { type: ActionTypes.INSTALLING_MARKETPLACE_ITEM, id: 'plugin1', }; const expectedState = currentState; expect(marketplaceReducer(currentState, action)).toBe(expectedState); }); it('should clear error for previously failed plugin', () => { const action: GenericAction = { type: ActionTypes.INSTALLING_MARKETPLACE_ITEM, id: 'plugin3', }; const expectedState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin3: true}, errors: {}, filter: 'existing', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); }); describe(ActionTypes.INSTALLING_MARKETPLACE_ITEM_SUCCEEDED, () => { const currentState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; it('should clear installing', () => { const action: GenericAction = { type: ActionTypes.INSTALLING_MARKETPLACE_ITEM_SUCCEEDED, id: 'plugin1', }; const expectedState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); it('should clear error', () => { const action: GenericAction = { type: ActionTypes.INSTALLING_MARKETPLACE_ITEM_SUCCEEDED, id: 'plugin3', }; const expectedState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {}, filter: 'existing', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); }); describe(ActionTypes.INSTALLING_MARKETPLACE_ITEM_FAILED, () => { const currentState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; it('should clear installing and set error', () => { const action: GenericAction = { type: ActionTypes.INSTALLING_MARKETPLACE_ITEM_FAILED, id: 'plugin1', error: 'Failed to intall', }; const expectedState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin2: true}, errors: {plugin1: 'Failed to intall', plugin3: 'An error occurred'}, filter: 'existing', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); }); describe(ActionTypes.FILTER_MARKETPLACE_LISTING, () => { const currentState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; it('should set filter', () => { const action: GenericAction = { type: ActionTypes.FILTER_MARKETPLACE_LISTING, filter: 'new', }; const expectedState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'new', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); }); describe(ActionTypes.MODAL_CLOSE, () => { const currentState = { plugins: [{manifest: {id: 'plugin1'}}, {manifest: {id: 'plugin2'}}] as MarketplacePlugin[], apps: [], installing: {plugin1: true, plugin2: true}, errors: {plugin3: 'An error occurred'}, filter: 'existing', }; it('should no-op for different modal', () => { const action: GenericAction = { type: ActionTypes.MODAL_CLOSE, modalId: ModalIdentifiers.DELETE_CHANNEL, }; const expectedState = currentState; expect(marketplaceReducer(currentState, action)).toBe(expectedState); }); it('should clear state for marketplace modal', () => { const action: GenericAction = { type: ActionTypes.MODAL_CLOSE, modalId: ModalIdentifiers.PLUGIN_MARKETPLACE, }; const expectedState = { plugins: [], apps: [], installing: {}, errors: {}, filter: '', }; expect(marketplaceReducer(currentState, action)).toEqual(expectedState); }); }); });
4,216
0
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/views/modals.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Modal} from 'react-bootstrap'; import type {GenericAction} from 'mattermost-redux/types/actions'; import {modalState as modalStateReducer} from 'reducers/views/modals'; import {ActionTypes, ModalIdentifiers} from 'utils/constants'; class TestModal extends React.PureComponent { render() { return ( <Modal show={true} onHide={jest.fn()} > <Modal.Header closeButton={true}/> <Modal.Body/> </Modal> ); } } describe('Reducers.Modals', () => { test('Initial state', () => { const nextState = modalStateReducer( {}, {} as GenericAction, ); const expectedState = {}; expect(nextState).toEqual(expectedState); }); test(ActionTypes.MODAL_OPEN, () => { const dialogType = TestModal; const dialogProps = { test: true, }; const nextState = modalStateReducer( {}, { type: ActionTypes.MODAL_OPEN, modalId: ModalIdentifiers.DELETE_CHANNEL, dialogType: TestModal as React.ElementType<unknown>, dialogProps, }, ); const expectedState = { [ModalIdentifiers.DELETE_CHANNEL]: { open: true, dialogProps, dialogType, }, }; expect(nextState).toEqual(expectedState); }); test(ActionTypes.MODAL_CLOSE, () => { const nextState = modalStateReducer( {}, { type: ActionTypes.MODAL_CLOSE, modalId: ModalIdentifiers.DELETE_CHANNEL, }, ); expect(nextState).toEqual({}); }); test(`${ActionTypes.MODAL_CLOSE} with initial state`, () => { const initialState = { test_modal1: { open: true, dialogProps: { test: true, }, dialogType: TestModal as React.ElementType<unknown>, }, }; const nextState = modalStateReducer( initialState, { type: ActionTypes.MODAL_CLOSE, modalId: ModalIdentifiers.DELETE_CHANNEL, }, ); expect(nextState).toEqual(initialState); }); });
4,224
0
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers
petrpan-code/mattermost/mattermost/webapp/channels/src/reducers/views/rhs_suppressed.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GenericAction} from 'mattermost-redux/types/actions'; import rhsSuppressed from 'reducers/views/rhs_suppressed'; import {ActionTypes} from 'utils/constants'; describe('Reducers.views.rhsSuppressed', () => { test('initialState', () => { expect(rhsSuppressed(undefined, {} as GenericAction)).toBe(false); }); test('should handle SUPPRESS_RHS', () => { const action = { type: ActionTypes.SUPPRESS_RHS, }; expect(rhsSuppressed(false, action)).toEqual(true); }); test.each([ [{type: ActionTypes.UNSUPPRESS_RHS}], [{type: ActionTypes.UPDATE_RHS_STATE}], [{type: ActionTypes.SELECT_POST}], [{type: ActionTypes.SELECT_POST_CARD}], ])('receiving an action that opens the RHS should unsuppress it', (action) => { expect(rhsSuppressed(true, action)).toEqual(false); }); test.each([ [{type: ActionTypes.UPDATE_RHS_STATE, state: null}], [{type: ActionTypes.SELECT_POST, postId: ''}], [{type: ActionTypes.SELECT_POST_CARD, postId: ''}], ])('receiving an action that closes the RHS should do nothing', (action) => { expect(rhsSuppressed(true, action)).toEqual(true); expect(rhsSuppressed(false, action)).toEqual(false); }); });
4,344
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/drafts.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import {StoragePrefixes} from 'utils/constants'; import type {GlobalState} from 'types/store'; import {makeGetDrafts, makeGetDraftsByPrefix, makeGetDraftsCount} from './drafts'; const currentUserId = 'currentUserId'; const currentChannelId = 'channelId'; const rootId = 'rootId'; const currentTeamId = 'teamId'; const initialState = { entities: { users: { currentUserId, profiles: { currentUserId: { id: currentUserId, roles: 'system_role', }, }, }, channels: { currentChannelId, channels: { currentChannelId: {id: currentChannelId, team_id: currentTeamId}, }, channelsInTeam: { currentTeamId: [currentChannelId], }, myMembers: { currentChannelId: { channel_id: currentChannelId, user_id: currentUserId, roles: 'channel_role', mention_count: 1, msg_count: 9, }, }, }, teams: { currentTeamId, teams: { currentTeamId: { id: currentTeamId, name: 'team-1', displayName: 'Team 1', }, }, myMembers: { currentTeamId: {roles: 'team_role'}, }, }, general: { config: {}, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState; const commentDrafts = [ { message: 'comment_draft', fileInfos: [], uploadsInProgress: [], channelId: currentChannelId, rootId, show: true, }, ]; const channelDrafts = [ { message: 'channel_draft', fileInfos: [], uploadsInProgress: [], channelId: currentChannelId, show: true, }, ]; const state = mergeObjects(initialState, { storage: { storage: { [`${StoragePrefixes.COMMENT_DRAFT}${rootId}`]: { value: commentDrafts[0], timestamp: new Date('2022-11-20T23:21:53.552Z'), }, [`${StoragePrefixes.DRAFT}${currentChannelId}`]: { value: channelDrafts[0], timestamp: new Date('2022-11-20T23:21:53.552Z'), }, }, }, }); const expectedCommentDrafts = [ { id: rootId, key: `${StoragePrefixes.COMMENT_DRAFT}${rootId}`, type: 'thread', timestamp: new Date('2022-11-20T23:21:53.552Z'), value: commentDrafts[0], }, ]; const expectedChannelDrafts = [ { id: currentChannelId, key: `${StoragePrefixes.DRAFT}${currentChannelId}`, type: 'channel', timestamp: new Date('2022-11-20T23:21:53.552Z'), value: channelDrafts[0], }, ]; jest.mock('mattermost-redux/selectors/entities/channels', () => ({ getMyActiveChannelIds: () => currentChannelId, })); describe('makeGetDraftsByPrefix', () => { it('should return comment drafts when given the comment_draft prefix', () => { const getDraftsByPrefix = makeGetDraftsByPrefix(StoragePrefixes.COMMENT_DRAFT); const drafts = getDraftsByPrefix(state); expect(drafts).toEqual(expectedCommentDrafts); }); it('should return channel drafts when given the comment_draft prefix', () => { const getDraftsByPrefix = makeGetDraftsByPrefix(StoragePrefixes.DRAFT); const drafts = getDraftsByPrefix(state); expect(drafts).toEqual(expectedChannelDrafts); }); }); describe('makeGetDrafts', () => { it('should return all drafts', () => { const getDrafts = makeGetDrafts(); const drafts = getDrafts(state); expect(drafts).toEqual([...expectedChannelDrafts, ...expectedCommentDrafts]); }); }); describe('makeGetDraftsCount', () => { it('should return drafts count', () => { const getDraftsCount = makeGetDraftsCount(); const draftCount = getDraftsCount(state); expect(draftCount).toEqual([...expectedChannelDrafts, ...expectedCommentDrafts].length); }); });
4,351
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/lhs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as PreferencesSelectors from 'mattermost-redux/selectors/entities/preferences'; import type {GlobalState} from 'types/store'; import * as Lhs from './lhs'; jest.mock('selectors/drafts', () => ({ makeGetDraftsCount: jest.fn().mockImplementation(() => jest.fn()), })); jest.mock('mattermost-redux/selectors/entities/preferences', () => ({ isCollapsedThreadsEnabled: jest.fn(), })); beforeEach(() => { jest.resetModules(); }); describe('Selectors.Lhs', () => { let state: unknown; beforeEach(() => { state = {}; }); describe('should return the open state of the sidebar menu', () => { [true, false].forEach((expected) => { it(`when open is ${expected}`, () => { state = { views: { lhs: { isOpen: expected, }, }, }; expect(Lhs.getIsLhsOpen(state as GlobalState)).toEqual(expected); }); }); }); describe('getVisibleLhsStaticPages', () => { beforeEach(() => { state = { views: { lhs: { isOpen: false, currentStaticPageId: '', }, }, }; }); it('handles nothing enabled', () => { jest.spyOn(PreferencesSelectors, 'isCollapsedThreadsEnabled').mockImplementationOnce(() => false); jest.spyOn(Lhs, 'getDraftsCount').mockImplementationOnce(() => 0); const items = Lhs.getVisibleStaticPages(state as GlobalState); expect(items).toEqual([]); }); it('handles threads - default off', () => { jest.spyOn(PreferencesSelectors, 'isCollapsedThreadsEnabled').mockImplementation(() => true); jest.spyOn(Lhs, 'getDraftsCount').mockImplementationOnce(() => 0); const items = Lhs.getVisibleStaticPages(state as GlobalState); expect(items).toEqual([ { id: 'threads', isVisible: true, }, ]); }); it('should not return drafts when empty', () => { jest.spyOn(PreferencesSelectors, 'isCollapsedThreadsEnabled').mockImplementation(() => false); jest.spyOn(Lhs, 'getDraftsCount').mockImplementationOnce(() => 0); const items = Lhs.getVisibleStaticPages(state as GlobalState); expect(items).toEqual([]); }); it('should return drafts when there are available', () => { jest.spyOn(PreferencesSelectors, 'isCollapsedThreadsEnabled').mockImplementation(() => false); jest.spyOn(Lhs, 'getDraftsCount').mockImplementationOnce(() => 1); const items = Lhs.getVisibleStaticPages(state as GlobalState); expect(items).toEqual([ { id: 'drafts', isVisible: true, }, ]); }); }); });
4,354
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/onboarding.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import {getShowTaskListBool} from 'selectors/onboarding'; import {OnboardingTaskCategory, OnboardingTaskList} from 'components/onboarding_tasks'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import {RecommendedNextStepsLegacy, Preferences} from 'utils/constants'; import type {GlobalState} from 'types/store'; describe('selectors/onboarding', () => { describe('getShowTaskListBool', () => { test('first time user logs in aka firstTimeOnboarding', () => { const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const state = { entities: { general: { config: {}, }, preferences: { myPreferences: {}, }, users: { currentUserId: user.id, profiles, }, }, views: { browser: { windowSize: '', }, }, } as unknown as GlobalState; const [showTaskList, firstTimeOnboarding] = getShowTaskListBool(state); expect(showTaskList).toBeTruthy(); expect(firstTimeOnboarding).toBeTruthy(); }); test('previous user skipped legacy next steps so not show the tasklist', () => { const prefSkip = {category: Preferences.RECOMMENDED_NEXT_STEPS, name: RecommendedNextStepsLegacy.SKIP, value: 'true'}; const prefHide = {category: Preferences.RECOMMENDED_NEXT_STEPS, name: RecommendedNextStepsLegacy.HIDE, value: 'false'}; const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const state = { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.RECOMMENDED_NEXT_STEPS, RecommendedNextStepsLegacy.HIDE)]: prefHide, [getPreferenceKey(Preferences.RECOMMENDED_NEXT_STEPS, RecommendedNextStepsLegacy.SKIP)]: prefSkip, }, }, users: { currentUserId: user.id, profiles, }, }, views: { browser: { windowSize: '', }, }, } as unknown as GlobalState; const [showTaskList, firstTimeOnboarding] = getShowTaskListBool(state); expect(showTaskList).toBeFalsy(); expect(firstTimeOnboarding).toBeFalsy(); }); test('previous user hided legacy next steps so not show the tasklist', () => { const prefSkip = {category: Preferences.RECOMMENDED_NEXT_STEPS, name: RecommendedNextStepsLegacy.SKIP, value: 'false'}; const prefHide = {category: Preferences.RECOMMENDED_NEXT_STEPS, name: RecommendedNextStepsLegacy.HIDE, value: 'true'}; const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const state = { entities: { preferences: { myPreferences: { [getPreferenceKey(Preferences.RECOMMENDED_NEXT_STEPS, RecommendedNextStepsLegacy.HIDE)]: prefHide, [getPreferenceKey(Preferences.RECOMMENDED_NEXT_STEPS, RecommendedNextStepsLegacy.SKIP)]: prefSkip, }, }, users: { currentUserId: user.id, profiles, }, }, views: { browser: { windowSize: '', }, }, } as unknown as GlobalState; const [showTaskList, firstTimeOnboarding] = getShowTaskListBool(state); expect(showTaskList).toBeFalsy(); expect(firstTimeOnboarding).toBeFalsy(); }); test('user has preferences set to true for showing the tasklist', () => { const prefShow = {category: OnboardingTaskCategory, name: OnboardingTaskList.ONBOARDING_TASK_LIST_SHOW, value: 'true'}; const prefOpen = {category: OnboardingTaskCategory, name: OnboardingTaskList.ONBOARDING_TASK_LIST_OPEN, value: 'true'}; const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const state = { entities: { general: { config: {}, }, preferences: { myPreferences: { [getPreferenceKey(OnboardingTaskCategory, OnboardingTaskList.ONBOARDING_TASK_LIST_SHOW)]: prefShow, [getPreferenceKey(OnboardingTaskCategory, OnboardingTaskList.ONBOARDING_TASK_LIST_OPEN)]: prefOpen, }, }, users: { currentUserId: user.id, profiles, }, }, views: { browser: { windowSize: '', }, }, } as unknown as GlobalState; const [showTaskList, firstTimeOnboarding] = getShowTaskListBool(state); expect(showTaskList).toBeTruthy(); expect(firstTimeOnboarding).toBeFalsy(); }); test('user has preferences set to false for showing the tasklist', () => { const prefSkip = {category: Preferences.RECOMMENDED_NEXT_STEPS, name: RecommendedNextStepsLegacy.SKIP, value: 'true'}; const prefHide = {category: Preferences.RECOMMENDED_NEXT_STEPS, name: RecommendedNextStepsLegacy.HIDE, value: 'false'}; const prefShow = {category: OnboardingTaskCategory, name: OnboardingTaskList.ONBOARDING_TASK_LIST_SHOW, value: 'false'}; const prefOpen = {category: OnboardingTaskCategory, name: OnboardingTaskList.ONBOARDING_TASK_LIST_OPEN, value: 'false'}; const user = TestHelper.fakeUserWithId(); const profiles = { [user.id]: user, }; const state = { entities: { general: { config: {}, }, preferences: { myPreferences: { [getPreferenceKey(OnboardingTaskCategory, OnboardingTaskList.ONBOARDING_TASK_LIST_SHOW)]: prefShow, [getPreferenceKey(OnboardingTaskCategory, OnboardingTaskList.ONBOARDING_TASK_LIST_OPEN)]: prefOpen, [getPreferenceKey(Preferences.RECOMMENDED_NEXT_STEPS, RecommendedNextStepsLegacy.SKIP)]: prefSkip, [getPreferenceKey(Preferences.RECOMMENDED_NEXT_STEPS, RecommendedNextStepsLegacy.HIDE)]: prefHide, }, }, users: { currentUserId: user.id, profiles, }, }, views: { browser: { windowSize: '', }, }, } as unknown as GlobalState; const [showTaskList, firstTimeOnboarding] = getShowTaskListBool(state); expect(showTaskList).toBeFalsy(); expect(firstTimeOnboarding).toBeFalsy(); }); }); });
4,361
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/rhs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Selectors from 'selectors/rhs'; import type {GlobalState} from 'types/store'; describe('Selectors.Rhs', () => { describe('should return the last time a post was selected', () => { [0, 1000000, 2000000].forEach((expected) => { it(`when open is ${expected}`, () => { const state = {views: {rhs: { selectedPostFocussedAt: expected, }}} as GlobalState; expect(Selectors.getSelectedPostFocussedAt(state)).toEqual(expected); }); }); }); describe('should return the open state of the sidebar', () => { [true, false].forEach((expected) => { it(`when open is ${expected}`, () => { const state = {views: {rhs: { isSidebarOpen: expected, }}} as GlobalState; expect(Selectors.getIsRhsOpen(state)).toEqual(expected); }); }); }); describe('should return the open state of the sidebar menu', () => { [true, false].forEach((expected) => { it(`when open is ${expected}`, () => { const state = {views: {rhs: { isMenuOpen: expected, }}} as GlobalState; expect(Selectors.getIsRhsMenuOpen(state)).toEqual(expected); }); }); }); describe('should return the highlighted reply\'s id', () => { test.each(['42', ''])('when id is %s', (expected) => { const state = {views: {rhs: { highlightedPostId: expected, }}} as GlobalState; expect(Selectors.getHighlightedPostId(state)).toEqual(expected); }); }); describe('should return the previousRhsState', () => { test.each([ [[], null], [['channel-info'], 'channel-info'], [['channel-info', 'pinned'], 'pinned'], ])('%p gives %p', (previousArray, previous) => { const state = { views: {rhs: { previousRhsStates: previousArray, }}} as GlobalState; expect(Selectors.getPreviousRhsState(state)).toEqual(previous); }); }); });
4,363
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/storage.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Selectors from 'selectors/storage'; import {getPrefix} from 'utils/storage_utils'; import type {GlobalState} from 'types/store'; describe('Selectors.Storage', () => { const testState = { entities: { users: { currentUserId: 'user_id', profiles: { user_id: { id: 'user_id', }, }, }, }, storage: { storage: { 'global-item': {value: 'global-item-value', timestamp: new Date()}, user_id_item: {value: 'item-value', timestamp: new Date()}, }, }, } as unknown as GlobalState; it('getPrefix', () => { expect(getPrefix({} as GlobalState)).toEqual('unknown_'); expect(getPrefix({entities: {}} as GlobalState)).toEqual('unknown_'); expect(getPrefix({entities: {users: {currentUserId: 'not-exists'}}} as GlobalState)).toEqual('unknown_'); expect(getPrefix({entities: {users: {currentUserId: 'not-exists', profiles: {}}}} as GlobalState)).toEqual('unknown_'); expect(getPrefix({entities: {users: {currentUserId: 'exists', profiles: {exists: {id: 'user_id'}}}}} as unknown as GlobalState)).toEqual('user_id_'); }); it('makeGetGlobalItem', () => { expect(Selectors.makeGetGlobalItem('not-existing-global-item', undefined)(testState)).toEqual(undefined); expect(Selectors.makeGetGlobalItem('not-existing-global-item', 'default')(testState)).toEqual('default'); expect(Selectors.makeGetGlobalItem('global-item', undefined)(testState)).toEqual('global-item-value'); }); it('makeGetItem', () => { expect(Selectors.makeGetItem('not-existing-item', undefined)(testState)).toEqual(undefined); expect(Selectors.makeGetItem('not-existing-item', 'default')(testState)).toEqual('default'); expect(Selectors.makeGetItem('item', undefined)(testState)).toEqual('item-value'); }); });
4,373
0
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/views/custom_status.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {CustomStatusDuration} from '@mattermost/types/users'; import {Preferences} from 'mattermost-redux/constants'; import * as GeneralSelectors from 'mattermost-redux/selectors/entities/general'; import * as PreferenceSelectors from 'mattermost-redux/selectors/entities/preferences'; import * as UserSelectors from 'mattermost-redux/selectors/entities/users'; import {makeGetCustomStatus, getRecentCustomStatuses, isCustomStatusEnabled, showStatusDropdownPulsatingDot, showPostHeaderUpdateStatusButton} from 'selectors/views/custom_status'; import configureStore from 'store'; import {TestHelper} from 'utils/test_helper'; import {addTimeToTimestamp, TimeInformation} from 'utils/utils'; jest.mock('mattermost-redux/selectors/entities/users'); jest.mock('mattermost-redux/selectors/entities/general'); jest.mock('mattermost-redux/selectors/entities/preferences'); const customStatus = { emoji: 'speech_balloon', text: 'speaking', duration: CustomStatusDuration.DONT_CLEAR, }; describe('getCustomStatus', () => { const user = TestHelper.getUserMock(); const getCustomStatus = makeGetCustomStatus(); it('should return undefined when current user has no custom status set', async () => { const store = await configureStore(); (UserSelectors.getCurrentUser as jest.Mock).mockReturnValue(user); expect(getCustomStatus(store.getState())).toBeUndefined(); }); it('should return undefined when user with given id has no custom status set', async () => { const store = await configureStore(); (UserSelectors.getUser as jest.Mock).mockReturnValue(user); expect(getCustomStatus(store.getState(), user.id)).toBeUndefined(); }); it('should return customStatus object when there is custom status set', async () => { const store = await configureStore(); const newUser = {...user}; newUser.props.customStatus = JSON.stringify(customStatus); (UserSelectors.getCurrentUser as jest.Mock).mockReturnValue(newUser); expect(getCustomStatus(store.getState())).toStrictEqual(customStatus); }); }); describe('getRecentCustomStatuses', () => { const preference = { myPreference: { value: JSON.stringify([]), }, }; it('should return empty arr if there are no recent custom statuses', async () => { const store = await configureStore(); (PreferenceSelectors.get as jest.Mock).mockReturnValue(preference.myPreference.value); expect(getRecentCustomStatuses(store.getState())).toStrictEqual([]); }); it('should return arr of custom statuses if there are recent custom statuses', async () => { const store = await configureStore(); preference.myPreference.value = JSON.stringify([customStatus]); (PreferenceSelectors.get as jest.Mock).mockReturnValue(preference.myPreference.value); expect(getRecentCustomStatuses(store.getState())).toStrictEqual([customStatus]); }); }); describe('isCustomStatusEnabled', () => { const config = { EnableCustomUserStatuses: 'true', }; it('should return false if EnableCustomUserStatuses is false in the config', async () => { const store = await configureStore(); expect(isCustomStatusEnabled(store.getState())).toBeFalsy(); }); it('should return true if EnableCustomUserStatuses is true in the config', async () => { const store = await configureStore(); (GeneralSelectors.getConfig as jest.Mock).mockReturnValue(config); expect(isCustomStatusEnabled(store.getState())).toBeTruthy(); }); }); describe('showStatusDropdownPulsatingDot and showPostHeaderUpdateStatusButton', () => { const user = TestHelper.getUserMock(); const preference = { myPreference: { value: '', }, }; it('should return true if user has not opened the custom status modal before', async () => { const store = await configureStore(); (PreferenceSelectors.get as jest.Mock).mockReturnValue(preference.myPreference.value); expect(showStatusDropdownPulsatingDot(store.getState())).toBeTruthy(); }); it('should return false if user has opened the custom status modal before', async () => { const store = await configureStore(); preference.myPreference.value = JSON.stringify({[Preferences.CUSTOM_STATUS_MODAL_VIEWED]: true}); (PreferenceSelectors.get as jest.Mock).mockReturnValue(preference.myPreference.value); expect(showPostHeaderUpdateStatusButton(store.getState())).toBeFalsy(); }); it('should return false if user was created less than seven days before from today', async () => { const store = await configureStore(); (PreferenceSelectors.get as jest.Mock).mockReturnValue(preference.myPreference.value); const todayTimestamp = new Date().getTime(); // set the user create date to 6 days in the past from today const todayMinusSixDays = addTimeToTimestamp(todayTimestamp, TimeInformation.DAYS, 6, TimeInformation.PAST); const newUser = {...user, create_at: todayMinusSixDays}; newUser.props.customStatus = JSON.stringify(customStatus); (UserSelectors.getCurrentUser as jest.Mock).mockReturnValue(newUser); expect(showStatusDropdownPulsatingDot(store.getState())).toBeFalsy(); }); it('should return true if user was created more than seven days before from today', async () => { const store = await configureStore(); preference.myPreference.value = JSON.stringify({[Preferences.CUSTOM_STATUS_MODAL_VIEWED]: false}); (PreferenceSelectors.get as jest.Mock).mockReturnValue(preference.myPreference.value); const todayTimestamp = new Date().getTime(); // set the user create date to 8 days in the past from today const todayMinusEightDays = addTimeToTimestamp(todayTimestamp, TimeInformation.DAYS, 8, TimeInformation.PAST); const newUser = {...user, create_at: todayMinusEightDays}; newUser.props.customStatus = JSON.stringify(customStatus); (UserSelectors.getCurrentUser as jest.Mock).mockReturnValue(newUser); expect(showStatusDropdownPulsatingDot(store.getState())).toBeTruthy(); }); });
4,375
0
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/views/marketplace.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {AuthorType, ReleaseStage} from '@mattermost/types/marketplace'; import type {MarketplaceApp, MarketplacePlugin} from '@mattermost/types/marketplace'; import { getPlugins, getListing, getInstalledListing, getApp, getPlugin, getFilter, getInstalling, getError, } from 'selectors/views/marketplace'; import type {GlobalState} from 'types/store'; describe('marketplace', () => { const samplePlugin: MarketplacePlugin = { homepage_url: 'https://github.com/mattermost/mattermost-plugin-nps', download_url: 'https://github.com/mattermost/mattermost-plugin-nps/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz', author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { id: 'com.mattermost.nps', name: 'User Satisfaction Surveys', description: 'This plugin sends quarterly user satisfaction surveys to gather feedback and help improve Mattermost', version: '1.0.3', min_server_version: '5.14.0', }, installed_version: '', }; const sampleInstalledPlugin: MarketplacePlugin = { homepage_url: 'https://github.com/mattermost/mattermost-test', download_url: 'https://github.com/mattermost/mattermost-test/releases/download/v1.0.3/com.mattermost.nps-1.0.3.tar.gz', author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { id: 'com.mattermost.test', name: 'Test', description: 'This plugin is to test', version: '1.0.3', min_server_version: '5.14.0', }, installed_version: '1.0.3', }; const sampleApp: MarketplaceApp = { installed: false, author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { app_id: 'some.id', display_name: 'Some App', }, }; const sampleInstalledApp: MarketplaceApp = { installed: true, author_type: AuthorType.Mattermost, release_stage: ReleaseStage.Production, enterprise: false, manifest: { app_id: 'some.other.id', display_name: 'Some other App', }, }; const state = { views: { marketplace: { plugins: [samplePlugin, sampleInstalledPlugin], apps: [sampleApp, sampleInstalledApp], installing: {'com.mattermost.nps': true}, errors: {'com.mattermost.test': 'An error occurred'}, filter: 'existing', }, }, } as unknown as GlobalState; it('getListing should return all plugins and apps', () => { expect(getListing(state)).toEqual([samplePlugin, sampleInstalledPlugin, sampleApp, sampleInstalledApp]); }); it('getInstalledListing should return only installed plugins and apps', () => { expect(getInstalledListing(state)).toEqual([sampleInstalledPlugin, sampleInstalledApp]); }); it('getPlugins should return all plugins', () => { expect(getPlugins(state)).toEqual([samplePlugin, sampleInstalledPlugin]); }); describe('getPlugin', () => { it('should return samplePlugin', () => { expect(getPlugin(state, 'com.mattermost.nps')).toEqual(samplePlugin); }); it('should return sampleInstalledPlugin', () => { expect(getPlugin(state, 'com.mattermost.test')).toEqual(sampleInstalledPlugin); }); it('should return undefined for unknown plugin', () => { expect(getPlugin(state, 'unknown')).toBeUndefined(); }); }); describe('getApp', () => { it('should return sampleApp', () => { expect(getApp(state, 'some.id')).toEqual(sampleApp); }); it('should return sampleInstalledApp', () => { expect(getApp(state, 'some.other.id')).toEqual(sampleInstalledApp); }); it('should return undefined for unknown app', () => { expect(getApp(state, 'unknown')).toBeUndefined(); }); }); it('getFilter should return the active filter', () => { expect(getFilter(state)).toEqual('existing'); }); describe('getInstalling', () => { it('should return true for samplePlugin', () => { expect(getInstalling(state, 'com.mattermost.nps')).toBe(true); }); it('should return false for sampleInstalledPlugin', () => { expect(getInstalling(state, 'com.mattermost.test')).toBe(false); }); it('should return false for unknown plugin', () => { expect(getInstalling(state, 'unknown')).toBe(false); }); }); describe('getError', () => { it('should return undefined for samplePlugin', () => { expect(getError(state, 'com.mattermost.nps')).toBeUndefined(); }); it('should return error value for sampleInstalledPlugin', () => { expect(getError(state, 'com.mattermost.test')).toBe('An error occurred'); }); it('should return undefined for unknown plugin', () => { expect(getError(state, 'unknown')).toBeUndefined(); }); }); });
4,381
0
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/views/status_dropdown.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {setStatusDropdown} from 'actions/views/status_dropdown'; import {isStatusDropdownOpen} from 'selectors/views/status_dropdown'; import configureStore from 'store'; describe('status_dropdown selector', () => { it('should return the isOpen value from the state', async () => { const store = await configureStore(); expect(isStatusDropdownOpen(store.getState())).toBeFalsy(); }); it('should return true if statusDropdown in explicitly opened', async () => { const store = await configureStore(); await store.dispatch(setStatusDropdown(true)); expect(isStatusDropdownOpen(store.getState())).toBeTruthy(); }); });
4,385
0
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors
petrpan-code/mattermost/mattermost/webapp/channels/src/selectors/views/threads.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {GlobalState} from 'types/store'; import * as selectors from './threads'; describe('selectors/views/threads', () => { const makeState = (selectedThreadId: string|null, selectedPostId: string, isSidebarOpen = true) => ({ entities: { teams: { currentTeamId: 'current_team_id', }, threads: { selected_thread_id: { id: 'selected_thread_id', }, selected_post_id: { id: 'selected_post_id', }, post_id: { id: 'post_id', }, }, }, views: { threads: { selectedThreadIdInTeam: { current_team_id: selectedThreadId, }, }, rhs: { selectedPostId, isSidebarOpen, }, rhsSuppressed: false, }, }) as unknown as GlobalState; describe('isThreadOpen', () => { test('should return true when a specific thread is open', () => { const state = makeState('selected_thread_id', ''); expect(selectors.isThreadOpen(state, 'selected_thread_id')).toBe(true); }); test('should return false when another thread is open', () => { const state = makeState(null, 'selected_post_id'); expect(selectors.isThreadOpen(state, 'selected_thread_id')).toBe(false); }); test('should return false when no threads are open', () => { const state = makeState(null, ''); expect(selectors.isThreadOpen(state, 'post_id')).toBe(false); }); test('should return true for either thread with both threads are open', () => { const state = makeState('selected_thread_id', 'selected_post_id'); expect(selectors.isThreadOpen(state, 'selected_thread_id')).toBe(true); expect(selectors.isThreadOpen(state, 'selected_post_id')).toBe(true); }); }); });
4,392
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/stores/local_storage_store.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import LocalStorageStore, {getPenultimateChannelNameKey} from 'stores/local_storage_store'; describe('stores/LocalStorageStore', () => { test('should persist previous team id per user', () => { const userId1 = 'userId1'; const userId2 = 'userId2'; const teamId1 = 'teamId1'; const teamId2 = 'teamId2'; LocalStorageStore.setPreviousTeamId(userId1, teamId1); LocalStorageStore.setPreviousTeamId(userId2, teamId2); expect(LocalStorageStore.getPreviousTeamId(userId1)).toEqual(teamId1); expect(LocalStorageStore.getPreviousTeamId(userId2)).toEqual(teamId2); }); test('should persist previous channel name per team and user', () => { const userId1 = 'userId1'; const userId2 = 'userId2'; const teamId1 = 'teamId1'; const teamId2 = 'teamId2'; const channel1 = 'channel1'; const channel2 = 'channel2'; const channel3 = 'channel3'; LocalStorageStore.setPreviousChannelName(userId1, teamId1, channel1); LocalStorageStore.setPreviousChannelName(userId2, teamId1, channel2); LocalStorageStore.setPreviousChannelName(userId2, teamId2, channel3); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel1); expect(LocalStorageStore.getPreviousChannelName(userId2, teamId1)).toEqual(channel2); expect(LocalStorageStore.getPreviousChannelName(userId2, teamId2)).toEqual(channel3); }); describe('should persist separately for different subpaths', () => { test('getWasLoggedIn', () => { delete (window as any).basename; // Initially false expect(LocalStorageStore.getWasLoggedIn()).toEqual(false); // True after set LocalStorageStore.setWasLoggedIn(true); expect(LocalStorageStore.getWasLoggedIn()).toEqual(true); // Still true when basename explicitly set window.basename = '/'; expect(LocalStorageStore.getWasLoggedIn()).toEqual(true); // Different with different basename window.basename = '/subpath'; expect(LocalStorageStore.getWasLoggedIn()).toEqual(false); LocalStorageStore.setWasLoggedIn(true); expect(LocalStorageStore.getWasLoggedIn()).toEqual(true); // Back to old value with original basename window.basename = '/'; expect(LocalStorageStore.getWasLoggedIn()).toEqual(true); LocalStorageStore.setWasLoggedIn(false); expect(LocalStorageStore.getWasLoggedIn()).toEqual(false); // Value with different basename remains unchanged. window.basename = '/subpath'; expect(LocalStorageStore.getWasLoggedIn()).toEqual(true); }); }); describe('testing previous channel', () => { test('should remove previous channel without subpath', () => { const userId1 = 'userId1'; const teamId1 = 'teamId1'; const channel1 = 'channel1'; const channel2 = 'channel2'; LocalStorageStore.setPreviousChannelName(userId1, teamId1, channel1); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel1); LocalStorageStore.setPenultimateChannelName(userId1, teamId1, channel2); expect(LocalStorageStore.getPenultimateChannelName(userId1, teamId1)).toEqual(channel2); LocalStorageStore.removePreviousChannelName(userId1, teamId1); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel2); }); test('should remove previous channel using subpath', () => { const userId1 = 'userId1'; const teamId1 = 'teamId1'; const channel1 = 'channel1'; const channel2 = 'channel2'; window.basename = '/subpath'; LocalStorageStore.setPreviousChannelName(userId1, teamId1, channel1); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel1); LocalStorageStore.setPenultimateChannelName(userId1, teamId1, channel2); expect(LocalStorageStore.getPenultimateChannelName(userId1, teamId1)).toEqual(channel2); LocalStorageStore.removePreviousChannelName(userId1, teamId1); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel2); }); }); describe('test removing penultimate channel', () => { test('should remove previous channel without subpath', () => { const userId1 = 'userId1'; const teamId1 = 'teamId1'; const channel1 = 'channel1'; const channel2 = 'channel2'; LocalStorageStore.setPreviousChannelName(userId1, teamId1, channel1); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel1); LocalStorageStore.setPenultimateChannelName(userId1, teamId1, channel2); expect(LocalStorageStore.getPenultimateChannelName(userId1, teamId1)).toEqual(channel2); LocalStorageStore.removePenultimateChannelName(userId1, teamId1); expect(LocalStorageStore.getPreviousChannelName(userId1, teamId1)).toEqual(channel1); expect(LocalStorageStore.getItem(getPenultimateChannelNameKey(userId1, teamId1))).toEqual(null); }); }); });
4,399
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/tests/react_testing_utils.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {FormattedMessage, useIntl} from 'react-intl'; import {connect, useDispatch, useSelector} from 'react-redux'; import {Link, Route} from 'react-router-dom'; import {GenericModal} from '@mattermost/components'; import {UserTypes} from 'mattermost-redux/action_types'; import {getUser} from 'mattermost-redux/selectors/entities/users'; import {openModal} from 'actions/views/modals'; import ModalController from 'components/modal_controller'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import {TestHelper} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; import { renderWithContext, screen, userEvent, waitFor, } from './react_testing_utils'; describe('renderWithContext', () => { test('should be able to render anything', () => { const TestComponent = () => { return <div>{'Anything'}</div>; }; renderWithContext( <TestComponent/>, {}, ); expect(screen.getByText('Anything')).toBeInTheDocument(); }); test('should be able to render react-intl components', () => { const TestComponent = () => { return ( <FormattedMessage id='about.buildnumber' defaultMessage='Build Number:' /> ); }; renderWithContext( <TestComponent/>, ); expect(screen.getByText('Build Number:')).toBeInTheDocument(); }); test('should be able to render components using react-intl hooks', () => { const TestComponent = () => { const intl = useIntl(); return <div>{intl.formatMessage({id: 'about.hash', defaultMessage: 'Build Hash:'})}</div>; }; renderWithContext( <TestComponent/>, ); expect(screen.getByText('Build Hash:')).toBeInTheDocument(); }); test('should be able to render react-router components', () => { const RouteComponent = () => { return <div>{'this is the route component'}</div>; }; const TestComponent = () => { return ( <div> <Route path={''} component={RouteComponent} /> <Link to={'/another_page'}>{'Test Link'}</Link> </div> ); }; renderWithContext( <TestComponent/>, ); expect(screen.getByText('this is the route component')).toBeInTheDocument(); expect(screen.getByRole('link', {name: 'Test Link'})).toBeInTheDocument(); }); test('should be able to render components that use connect to access the Redux store', () => { const UnconnectedTestComponent = (props: {numProfiles: number}) => { return <div>{`There are ${props.numProfiles} users loaded`}</div>; }; const TestComponent = connect((state: GlobalState) => ({ numProfiles: Object.keys(state.entities.users.profiles).length, }))(UnconnectedTestComponent); renderWithContext( <TestComponent/>, ); expect(screen.getByText('There are 0 users loaded')).toBeInTheDocument(); }); test('should be able to render components that use hooks to access the Redux store', () => { const TestComponent = () => { const numProfiles = useSelector((state: GlobalState) => Object.keys(state.entities.users.profiles).length); return <div>{`There are ${numProfiles} users loaded`}</div>; }; renderWithContext( <TestComponent/>, ); expect(screen.getByText('There are 0 users loaded')).toBeInTheDocument(); }); test('should be able to rerender components without losing context', () => { const TestComponent = (props: {appTitle: string}) => { return ( <FormattedMessage id='about.title' defaultMessage='About {appTitle}' values={{ appTitle: props.appTitle, }} /> ); }; const {rerender} = renderWithContext( <TestComponent appTitle='Mattermost'/>, ); expect(screen.getByText('About Mattermost')).toBeInTheDocument(); rerender( <TestComponent appTitle='Mattermots'/>, ); expect(screen.getByText('About Mattermots')).toBeInTheDocument(); }); test('should be able to inject store state and replace it later', () => { const initialState = { entities: { users: { profiles: { user1: TestHelper.getUserMock({id: 'user1', username: 'Alpha'}), user2: TestHelper.getUserMock({id: 'user2', username: 'Bravo'}), }, }, }, }; const TestComponent = () => { const user1 = useSelector((state: GlobalState) => getUser(state, 'user1')); const user2 = useSelector((state: GlobalState) => getUser(state, 'user2')); return <div>{`User1 is ${user1.username} and User2 is ${user2.username}!`}</div>; }; const {replaceStoreState} = renderWithContext( <TestComponent/>, initialState, ); expect(screen.getByText('User1 is Alpha and User2 is Bravo!')).toBeInTheDocument(); replaceStoreState(mergeObjects(initialState, { entities: { users: { profiles: { user1: {username: 'Charlie'}, }, }, }, })); expect(screen.getByText('User1 is Charlie and User2 is Bravo!')).toBeInTheDocument(); replaceStoreState(mergeObjects(initialState, { entities: { users: { profiles: { user2: {username: 'Delta'}, }, }, }, })); // Since this replaces the state, user1's username goes back to the initial value expect(screen.getByText('User1 is Alpha and User2 is Delta!')).toBeInTheDocument(); }); test('should be able to update store state', () => { const initialState = { entities: { users: { profiles: { user1: TestHelper.getUserMock({id: 'user1', username: 'Echo'}), user2: TestHelper.getUserMock({id: 'user2', username: 'Foxtrot'}), }, }, }, }; const TestComponent = () => { const user1 = useSelector((state: GlobalState) => getUser(state, 'user1')); const user2 = useSelector((state: GlobalState) => getUser(state, 'user2')); return <div>{`User1 is ${user1.username} and User2 is ${user2.username}!`}</div>; }; const {updateStoreState} = renderWithContext( <TestComponent/>, initialState, ); expect(screen.getByText('User1 is Echo and User2 is Foxtrot!')).toBeInTheDocument(); updateStoreState({ entities: { users: { profiles: { user1: {username: 'Golf'}, }, }, }, }); expect(screen.getByText('User1 is Golf and User2 is Foxtrot!')).toBeInTheDocument(); updateStoreState({ entities: { users: { profiles: { user2: {username: 'Hotel'}, }, }, }, }); expect(screen.getByText('User1 is Golf and User2 is Hotel!')).toBeInTheDocument(); }); test('should be able to mix rerendering and updating store state', () => { const initialState = { entities: { users: { profiles: { user1: TestHelper.getUserMock({id: 'user1', username: 'India'}), }, }, }, }; const TestComponent = (props: {greeting: string}) => { const user1 = useSelector((state: GlobalState) => getUser(state, 'user1')); return <div>{`${props.greeting}, ${user1.username}!`}</div>; }; const {rerender, updateStoreState} = renderWithContext( <TestComponent greeting='Hello'/>, initialState, ); expect(screen.getByText('Hello, India!')).toBeInTheDocument(); updateStoreState({ entities: { users: { profiles: { user1: {username: 'Juliet'}, }, }, }, }); expect(screen.getByText('Hello, Juliet!')).toBeInTheDocument(); rerender(<TestComponent greeting='Salutations'/>); expect(screen.getByText('Salutations, Juliet!')).toBeInTheDocument(); updateStoreState({ entities: { users: { profiles: { user1: {username: 'Kilo'}, }, }, }, }); expect(screen.getByText('Salutations, Kilo!')).toBeInTheDocument(); rerender(<TestComponent greeting='Bonjour'/>); expect(screen.getByText('Bonjour, Kilo!')).toBeInTheDocument(); }); test('should be able to dispatch and handle redux actions', () => { const TestComponent = () => { const user1 = useSelector((state: GlobalState) => getUser(state, 'user1')); const dispatch = useDispatch(); const username = user1 ? user1.username : 'NOT_LOADED'; const loadUser = () => { dispatch({ type: UserTypes.RECEIVED_PROFILE, data: {id: 'user1', username: 'Lima'}, }); }; return ( <div> <span>{`User1 is ${username}!`}</span> <button onClick={loadUser}>{'Load User'}</button> </div> ); }; renderWithContext(<TestComponent/>); expect(screen.getByText('User1 is NOT_LOADED!')).toBeInTheDocument(); userEvent.click(screen.getByText('Load User')); expect(screen.getByText('User1 is Lima!')).toBeInTheDocument(); }); test('should be able to render modals using a ModalController', async () => { const TestComponent = () => { const dispatch = useDispatch(); const openTestModal = () => { dispatch(openModal({ modalId: 'test_modal', dialogType: TestModal, })); }; return ( <div> <button onClick={openTestModal}>{'Open Modal'}</button> </div> ); }; const TestModal = (props: {onExited: () => void}) => { return ( <GenericModal onExited={props.onExited}> <p>{'This is a modal!'}</p> </GenericModal> ); }; renderWithContext( <> <TestComponent/> <ModalController/> </>, ); expect(screen.getByText('Open Modal')).toBeVisible(); userEvent.click(screen.getByText('Open Modal')); // Use waitFor because the modal animates in and out await waitFor(() => { expect(screen.queryByText('This is a modal!')).toBeInTheDocument(); }); userEvent.click(screen.getByLabelText('Close')); await waitFor(() => { expect(screen.queryByText('This is a modal!')).not.toBeInTheDocument(); }); }); });
4,442
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/admin_console_index.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {createIntl} from 'react-intl'; import AdminDefinition from 'components/admin_console/admin_definition'; import {samplePlugin1, samplePlugin2} from 'tests/helpers/admin_console_plugin_index_sample_pluings'; import {generateIndex} from './admin_console_index'; const enMessages = require('../i18n/en'); const esMessages = require('../i18n/es'); describe('AdminConsoleIndex.generateIndex', () => { it('should generate an index where I can search', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const idx = generateIndex(AdminDefinition, intl, {}); expect(idx.search('ldap')).toEqual([ 'environment/session_lengths', 'authentication/mfa', 'authentication/ldap', 'authentication/saml', 'experimental/features', 'authentication/email', 'authentication/guest_access', ]); expect(idx.search('saml')).toEqual([ 'authentication/saml', 'environment/session_lengths', 'authentication/email', 'experimental/features', ]); expect(idx.search('nginx')).toEqual([ 'environment/rate_limiting', ]); expect(idx.search('characters')).toEqual([ 'site_config/customization', 'authentication/password', ]); expect(idx.search('caracteres')).toEqual([]); expect(idx.search('notexistingword')).toEqual([]); }); xit('should generate a index where I can search in other language', () => { const intl = createIntl({locale: 'es', messages: esMessages, defaultLocale: 'es'}); const idx = generateIndex(AdminDefinition, intl, {}); expect(idx.search('ldap').sort()).toEqual([ 'authentication/mfa', 'authentication/ldap', 'authentication/saml', 'experimental/features', 'authentication/email', 'environment/session_lengths', 'authentication/guest_access', ].sort()); expect(idx.search('saml').sort()).toEqual([ 'authentication/saml', 'environment/session_lengths', 'authentication/email', 'experimental/features', ].sort()); expect(idx.search('nginx')).toEqual([ 'environment/rate_limiting', ]); expect(idx.search('caracteres').sort()).toEqual([ 'site_config/customization', 'authentication/password', ].sort()); expect(idx.search('characters')).toEqual([]); expect(idx.search('notexistingword')).toEqual([]); }); it('should generate a index including the plugin settings', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const idx = generateIndex(AdminDefinition, intl, {[samplePlugin1.id]: samplePlugin1, [samplePlugin2.id]: samplePlugin2}); expect(idx.search('random')).toEqual(['plugin_Some-random-plugin', 'site_config/public_links']); expect(idx.search('autolink')).toEqual(['plugin_mattermost-autolink']); }); });
4,444
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/admin_console_plugin_index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {samplePlugin1, samplePlugin2, samplePlugin3, samplePlugin4} from 'tests/helpers/admin_console_plugin_index_sample_pluings'; import {getPluginEntries} from './admin_console_plugin_index'; describe('AdminConsolePluginsIndex.getPluginEntries', () => { it('should return an empty map in case of plugins is undefined', () => { const entries = getPluginEntries(); expect(entries).toEqual({}); }); it('should return an empty map in case of plugins is undefined', () => { const entries = getPluginEntries(undefined); expect(entries).toEqual({}); }); it('should return an empty map in case of plugins is empty', () => { const entries = getPluginEntries({}); expect(entries).toEqual({}); }); it('should return map with the text extracted from plugins', () => { const entries = getPluginEntries({[samplePlugin1.id]: samplePlugin1}); expect(entries).toMatchSnapshot(); expect(entries).toHaveProperty('plugin_mattermost-autolink'); }); it('should return map with the text extracted from plugins', () => { const entries = getPluginEntries({[samplePlugin1.id]: samplePlugin1, [samplePlugin2.id]: samplePlugin2}); expect(entries).toMatchSnapshot(); expect(entries).toHaveProperty('plugin_mattermost-autolink'); expect(entries).toHaveProperty('plugin_Some-random-plugin'); }); it('should not return the markdown link texts', () => { const entries = getPluginEntries({[samplePlugin3.id]: samplePlugin3}); expect(entries).toHaveProperty('plugin_plugin-with-markdown'); expect(entries['plugin_plugin-with-markdown']).toContain('click here'); expect(entries['plugin_plugin-with-markdown']).toContain('Markdown plugin label'); expect(entries['plugin_plugin-with-markdown']).not.toContain('localhost'); }); it('should extract the text from label field', () => { const entries = getPluginEntries({[samplePlugin3.id]: samplePlugin3}); expect(entries).toHaveProperty('plugin_plugin-with-markdown'); expect(entries['plugin_plugin-with-markdown']).toContain('Markdown plugin label'); }); it('should index the enable plugin setting', () => { const entries = getPluginEntries({[samplePlugin3.id]: samplePlugin3}); expect(entries).toHaveProperty('plugin_plugin-with-markdown'); expect(entries['plugin_plugin-with-markdown']).toContain('admin.plugin.enable_plugin'); expect(entries['plugin_plugin-with-markdown']).toContain('PluginSettings.PluginStates.plugin-with-markdown.Enable'); }); it('should index the enable plugin setting even if other settings are not present', () => { const entries = getPluginEntries({[samplePlugin4.id]: samplePlugin4}); expect(entries).toHaveProperty('plugin_plugin-without-settings'); expect(entries['plugin_plugin-without-settings']).toContain('admin.plugin.enable_plugin'); expect(entries['plugin_plugin-without-settings']).toContain('PluginSettings.PluginStates.plugin-without-settings.Enable'); }); });
4,448
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/channel_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Utils from 'utils/channel_utils'; describe('Channel Utils', () => { describe('findNextUnreadChannelId', () => { test('no channels are unread', () => { const curChannelId = '3'; const allChannelIds = ['1', '2', '3', '4', '5']; const unreadChannelIds: string[] = []; expect(Utils.findNextUnreadChannelId(curChannelId, allChannelIds, unreadChannelIds, 1)).toEqual(-1); }); test('only current channel is unread', () => { const curChannelId = '3'; const allChannelIds = ['1', '2', '3', '4', '5']; const unreadChannelIds = ['3']; expect(Utils.findNextUnreadChannelId(curChannelId, allChannelIds, unreadChannelIds, 1)).toEqual(-1); }); test('going forward to unread channels', () => { const curChannelId = '3'; const allChannelIds = ['1', '2', '3', '4', '5']; const unreadChannelIds = ['1', '4', '5']; expect(Utils.findNextUnreadChannelId(curChannelId, allChannelIds, unreadChannelIds, 1)).toEqual(3); }); test('going forward to unread channels with wrapping', () => { const curChannelId = '3'; const allChannelIds = ['1', '2', '3', '4', '5']; const unreadChannelIds = ['1', '2']; expect(Utils.findNextUnreadChannelId(curChannelId, allChannelIds, unreadChannelIds, 1)).toEqual(0); }); test('going backwards to unread channels', () => { const curChannelId = '3'; const allChannelIds = ['1', '2', '3', '4', '5']; const unreadChannelIds = ['1', '4', '5']; expect(Utils.findNextUnreadChannelId(curChannelId, allChannelIds, unreadChannelIds, -1)).toEqual(0); }); test('going backwards to unread channels with wrapping', () => { const curChannelId = '3'; const allChannelIds = ['1', '2', '3', '4', '5']; const unreadChannelIds = ['3', '4', '5']; expect(Utils.findNextUnreadChannelId(curChannelId, allChannelIds, unreadChannelIds, -1)).toEqual(4); }); }); });
4,454
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/datetime.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { getDiff, isToday, isYesterday, } from './datetime'; describe('isToday and isYesterday', () => { test('tomorrow at 12am', () => { const date = new Date(); date.setDate(date.getDate() + 1); date.setHours(0); date.setMinutes(0); expect(isToday(date)).toBe(false); expect(isYesterday(date)).toBe(false); }); test('now', () => { const date = new Date(); expect(isToday(date)).toBe(true); expect(isYesterday(date)).toBe(false); }); test('today at 12am', () => { const date = new Date(); date.setHours(0); date.setMinutes(0); expect(isToday(date)).toBe(true); expect(isYesterday(date)).toBe(false); }); test('today at 11:59pm', () => { const date = new Date(); date.setHours(23); date.setMinutes(59); expect(isToday(date)).toBe(true); expect(isYesterday(date)).toBe(false); }); test('yesterday at 11:59pm', () => { const date = new Date(); date.setDate(date.getDate() - 1); date.setHours(23); date.setMinutes(59); expect(isToday(date)).toBe(false); expect(isYesterday(date)).toBe(true); }); test('yesterday at 12am', () => { const date = new Date(); date.setDate(date.getDate() - 1); date.setHours(0); date.setMinutes(0); expect(isToday(date)).toBe(false); expect(isYesterday(date)).toBe(true); }); test('two days ago at 11:59pm', () => { const date = new Date(); date.setDate(date.getDate() - 2); date.setHours(23); date.setMinutes(59); expect(isToday(date)).toBe(false); expect(isYesterday(date)).toBe(false); }); }); describe('diff: day', () => { const tz = ''; test('tomorrow at 12am', () => { const now = new Date(); const date = new Date(); date.setDate(date.getDate() + 1); date.setHours(0); date.setMinutes(0); expect(getDiff(date, now, tz, 'day')).toBe(+1); }); test('now', () => { const now = new Date(); const date = new Date(); expect(getDiff(date, now, tz, 'day')).toBe(0); }); test('today at 12am', () => { const now = new Date(); const date = new Date(); date.setHours(0); date.setMinutes(0); expect(getDiff(date, now, tz, 'day')).toBe(0); }); test('today at 11:59pm', () => { const now = new Date(); const date = new Date(); date.setHours(23); date.setMinutes(59); expect(getDiff(date, now, tz, 'day')).toBe(0); }); test('yesterday at 11:59pm', () => { const now = new Date(); const date = new Date(); date.setDate(date.getDate() - 1); date.setHours(23); date.setMinutes(59); expect(getDiff(date, now, tz, 'day')).toBe(-1); }); test('yesterday at 12am', () => { const now = new Date(); const date = new Date(); date.setDate(date.getDate() - 1); date.setHours(0); date.setMinutes(0); expect(getDiff(date, now, tz, 'day')).toBe(-1); }); test('two days ago at 11:59pm', () => { const now = new Date(); const date = new Date(); date.setDate(date.getDate() - 2); date.setHours(23); date.setMinutes(59); expect(getDiff(date, now, tz, 'day')).toBe(-2); }); test('366 days ago at 11:59pm', () => { const now = new Date(); const date = new Date(); date.setDate(date.getDate() - 366); date.setHours(23); date.setMinutes(59); expect(getDiff(date, now, tz, 'day')).toBe(-366); }); });
4,457
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/dragster.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import dragster from './dragster'; describe('utils.dragster', () => { let div: HTMLElement; let unbind: () => void; let enterEvent: CustomEvent | null; let leaveEvent: CustomEvent | null; let overEvent: CustomEvent | null; let dropEvent: CustomEvent | null; const id = 'utils_dragster_test'; const dragenter = new CustomEvent('dragenter', {detail: 'dragenter_detail'}); const dragleave = new CustomEvent('dragleave', {detail: 'dragleave_detail'}); const dragover = new CustomEvent('dragover', {detail: 'dragover_detail'}); const drop = new CustomEvent('drop', {detail: 'drop_detail'}); const options = { enter: (event: CustomEvent) => { enterEvent = event; }, leave: (event: CustomEvent) => { leaveEvent = event; }, over: (event: CustomEvent) => { overEvent = event; }, drop: (event: CustomEvent) => { dropEvent = event; }, }; beforeAll(() => { div = document.createElement('div'); document.body.appendChild(div); div.setAttribute('id', id); unbind = dragster(`#${id}`, options); }); afterAll(() => { unbind(); div.remove(); }); afterEach(() => { enterEvent = null; leaveEvent = null; overEvent = null; dropEvent = null; }); it('should dispatch dragenter event', () => { div.dispatchEvent(dragenter); expect(enterEvent!.detail.detail).toEqual('dragenter_detail'); }); it('should dispatch dragleave event', () => { div.dispatchEvent(dragleave); expect(leaveEvent!.detail.detail).toEqual('dragleave_detail'); }); it('should dispatch dragover event', () => { div.dispatchEvent(dragover); expect(overEvent!.detail.detail).toEqual('dragover_detail'); }); it('should dispatch drop event', () => { div.dispatchEvent(drop); expect(dropEvent!.detail.detail).toEqual('drop_detail'); }); it('should dispatch dragenter event again', () => { div.dispatchEvent(dragenter); expect(enterEvent!.detail.detail).toEqual('dragenter_detail'); }); it('should dispatch dragenter event once if dispatched 2 times', () => { div.dispatchEvent(dragenter); expect(enterEvent).toBeNull(); }); });
4,462
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/emoji_utils.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {EmojiIndicesByAlias, Emojis} from 'utils/emoji'; import {TestHelper as TH} from 'utils/test_helper'; import {compareEmojis, convertEmojiSkinTone, wrapEmojis} from './emoji_utils'; describe('compareEmojis', () => { test('should sort an array of emojis alphabetically', () => { const goatEmoji = TH.getCustomEmojiMock({ name: 'goat', }); const dashEmoji = TH.getCustomEmojiMock({ name: 'dash', }); const smileEmoji = TH.getCustomEmojiMock({ name: 'smile', }); const emojiArray = [goatEmoji, dashEmoji, smileEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, '')); expect(emojiArray).toEqual([dashEmoji, goatEmoji, smileEmoji]); }); test('should have partial matched emoji first', () => { const goatEmoji = TH.getSystemEmojiMock({ short_name: 'goat', short_names: ['goat'], }); const dashEmoji = TH.getSystemEmojiMock({ short_name: 'dash', short_names: ['dash'], }); const smileEmoji = TH.getSystemEmojiMock({ short_name: 'smile', short_names: ['smile'], }); const emojiArray = [goatEmoji, dashEmoji, smileEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, 'smi')); expect(emojiArray).toEqual([smileEmoji, dashEmoji, goatEmoji]); }); test('should be able to sort on aliases', () => { const goatEmoji = TH.getSystemEmojiMock({ short_names: [':goat:'], short_name: ':goat:', }); const dashEmoji = TH.getSystemEmojiMock({ short_names: [':dash:'], short_name: ':dash:', }); const smileEmoji = TH.getSystemEmojiMock({ short_names: [':smile:'], short_name: ':smile:', }); const emojiArray = [goatEmoji, dashEmoji, smileEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, '')); expect(emojiArray).toEqual([dashEmoji, goatEmoji, smileEmoji]); }); test('special case for thumbsup emoji should sort it before thumbsdown by aliases', () => { const thumbsUpEmoji = TH.getSystemEmojiMock({ short_names: ['+1'], short_name: '+1', }); const thumbsDownEmoji = TH.getSystemEmojiMock({ short_names: ['-1'], short_name: '-1', }); const smileEmoji = TH.getSystemEmojiMock({ short_names: ['smile'], short_name: 'smile', }); const emojiArray = [thumbsDownEmoji, thumbsUpEmoji, smileEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, '')); expect(emojiArray).toEqual([thumbsUpEmoji, thumbsDownEmoji, smileEmoji]); }); test('special case for thumbsup emoji should sort it before thumbsdown by names', () => { const thumbsUpEmoji = TH.getSystemEmojiMock({ short_name: 'thumbsup', }); const thumbsDownEmoji = TH.getSystemEmojiMock({ short_name: 'thumbsdown', }); const smileEmoji = TH.getSystemEmojiMock({ short_name: 'smile', }); const emojiArray = [thumbsDownEmoji, thumbsUpEmoji, smileEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, '')); expect(emojiArray).toEqual([smileEmoji, thumbsUpEmoji, thumbsDownEmoji]); }); test('special case for thumbsup emoji should sort it when emoji is matched', () => { const thumbsUpEmoji = TH.getSystemEmojiMock({ short_name: 'thumbsup', }); const thumbsDownEmoji = TH.getSystemEmojiMock({ short_name: 'thumbsdown', }); const smileEmoji = TH.getSystemEmojiMock({ short_name: 'smile', }); const emojiArray = [thumbsDownEmoji, thumbsUpEmoji, smileEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, 'thumb')); expect(emojiArray).toEqual([thumbsUpEmoji, thumbsDownEmoji, smileEmoji]); }); test('special case for thumbsup emoji should sort custom "thumb" emojis after system', () => { const thumbsUpEmoji = TH.getSystemEmojiMock({ short_names: ['+1', 'thumbsup'], category: 'people-body', }); const thumbsDownEmoji = TH.getSystemEmojiMock({ short_name: 'thumbsdown', category: 'people-body', }); const thumbsUpCustomEmoji = TH.getSystemEmojiMock({ short_name: 'thumbsup-custom', category: 'custom', }); const emojiArray = [thumbsUpCustomEmoji, thumbsDownEmoji, thumbsUpEmoji]; emojiArray.sort((a, b) => compareEmojis(a, b, 'thumb')); expect(emojiArray).toEqual([thumbsUpEmoji, thumbsDownEmoji, thumbsUpCustomEmoji]); }); }); describe('wrapEmojis', () => { // Note that the keys used by some of these may appear to be incorrect because they're counting Unicode code points // instead of just characters. Also, if these tests return results that serialize to the same string, that means // that the key for a span is incorrect. test('should return the original string if it contains no emojis', () => { const input = 'this is a test 1234'; expect(wrapEmojis(input)).toBe(input); }); test('should wrap a single emoji in a span', () => { const input = '🌮'; expect(wrapEmojis(input)).toEqual( <span key='0' className='emoji' > {'🌮'} </span>, ); }); test('should wrap a single emoji in a span with surrounding text', () => { const input = 'this is 🌮 a test 1234'; expect(wrapEmojis(input)).toEqual([ 'this is ', <span key='8' className='emoji' > {'🌮'} </span>, ' a test 1234', ]); }); test('should wrap multiple emojis in spans', () => { const input = 'this is 🌮 a taco 🎉 1234'; expect(wrapEmojis(input)).toEqual([ 'this is ', <span key='8' className='emoji' > {'🌮'} </span>, ' a taco ', <span key='18' className='emoji' > {'🎉'} </span>, ' 1234', ]); }); test('should properly handle adjacent emojis', () => { const input = '🌮🎉🇫🇮🍒'; expect(wrapEmojis(input)).toEqual([ <span key='0' className='emoji' > {'🌮'} </span>, <span key='2' className='emoji' > {'🎉'} </span>, <span key='4' className='emoji' > {'🇫🇮'} </span>, <span key='8' className='emoji' > {'🍒'} </span>, ]); }); test('should properly handle unsupported emojis', () => { const input = 'this is 🤟 a test'; expect(wrapEmojis(input)).toEqual([ 'this is ', <span key='8' className='emoji' > {'🤟'} </span>, ' a test', ]); }); test('should properly handle emojis with variations', () => { const input = 'this is 👍🏿👍🏻 a test ✊🏻✊🏿'; expect(wrapEmojis(input)).toEqual([ 'this is ', <span key='8' className='emoji' > {'👍🏿'} </span>, <span key='12' className='emoji' > {'👍🏻'} </span>, ' a test ', <span key='24' className='emoji' > {'✊🏻'} </span>, <span key='27' className='emoji' > {'✊🏿'} </span>, ]); }); test('should return a one character string if it contains no emojis', () => { const input = 'a'; expect(wrapEmojis(input)).toBe(input); }); test('should properly wrap an emoji followed by a single character', () => { const input = '🌮a'; expect(wrapEmojis(input)).toEqual([ <span key='0' className='emoji' > {'🌮'} </span>, 'a', ]); }); }); describe('convertEmojiSkinTone', () => { test('should convert a default skin toned emoji', () => { const emoji = getEmoji('nose'); expect(convertEmojiSkinTone(emoji, 'default')).toBe(getEmoji('nose')); expect(convertEmojiSkinTone(emoji, '1F3FB')).toBe(getEmoji('nose_light_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FC')).toBe(getEmoji('nose_medium_light_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FD')).toBe(getEmoji('nose_medium_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FE')).toBe(getEmoji('nose_medium_dark_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FF')).toBe(getEmoji('nose_dark_skin_tone')); }); test('should convert a non-default skin toned emoji', () => { const emoji = getEmoji('ear_dark_skin_tone'); expect(convertEmojiSkinTone(emoji, 'default')).toBe(getEmoji('ear')); expect(convertEmojiSkinTone(emoji, '1F3FB')).toBe(getEmoji('ear_light_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FC')).toBe(getEmoji('ear_medium_light_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FD')).toBe(getEmoji('ear_medium_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FE')).toBe(getEmoji('ear_medium_dark_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FF')).toBe(getEmoji('ear_dark_skin_tone')); }); test('should convert a gendered emoji', () => { const emoji = getEmoji('male-teacher'); expect(convertEmojiSkinTone(emoji, 'default')).toBe(getEmoji('male-teacher')); expect(convertEmojiSkinTone(emoji, '1F3FB')).toBe(getEmoji('male-teacher_light_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FC')).toBe(getEmoji('male-teacher_medium_light_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FD')).toBe(getEmoji('male-teacher_medium_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FE')).toBe(getEmoji('male-teacher_medium_dark_skin_tone')); expect(convertEmojiSkinTone(emoji, '1F3FF')).toBe(getEmoji('male-teacher_dark_skin_tone')); }); test('should convert emojis made up of ZWJ sequences', () => { const astronaut = getEmoji('astronaut'); expect(convertEmojiSkinTone(astronaut, 'default')).toBe(getEmoji('astronaut')); expect(convertEmojiSkinTone(astronaut, '1F3FB')).toBe(getEmoji('astronaut_light_skin_tone')); expect(convertEmojiSkinTone(astronaut, '1F3FC')).toBe(getEmoji('astronaut_medium_light_skin_tone')); expect(convertEmojiSkinTone(astronaut, '1F3FD')).toBe(getEmoji('astronaut_medium_skin_tone')); expect(convertEmojiSkinTone(astronaut, '1F3FE')).toBe(getEmoji('astronaut_medium_dark_skin_tone')); expect(convertEmojiSkinTone(astronaut, '1F3FF')).toBe(getEmoji('astronaut_dark_skin_tone')); const redHairedWoman = getEmoji('red_haired_woman_dark_skin_tone'); expect(convertEmojiSkinTone(redHairedWoman, 'default')).toBe(getEmoji('red_haired_woman')); expect(convertEmojiSkinTone(redHairedWoman, '1F3FB')).toBe(getEmoji('red_haired_woman_light_skin_tone')); expect(convertEmojiSkinTone(redHairedWoman, '1F3FC')).toBe(getEmoji('red_haired_woman_medium_light_skin_tone')); expect(convertEmojiSkinTone(redHairedWoman, '1F3FD')).toBe(getEmoji('red_haired_woman_medium_skin_tone')); expect(convertEmojiSkinTone(redHairedWoman, '1F3FE')).toBe(getEmoji('red_haired_woman_medium_dark_skin_tone')); expect(convertEmojiSkinTone(redHairedWoman, '1F3FF')).toBe(getEmoji('red_haired_woman_dark_skin_tone')); }); test('should do nothing for emojis without skin tones', () => { const strawberry = getEmoji('strawberry'); expect(convertEmojiSkinTone(strawberry, 'default')).toBe(strawberry); expect(convertEmojiSkinTone(strawberry, '1F3FB')).toBe(strawberry); expect(convertEmojiSkinTone(strawberry, '1F3FC')).toBe(strawberry); expect(convertEmojiSkinTone(strawberry, '1F3FD')).toBe(strawberry); expect(convertEmojiSkinTone(strawberry, '1F3FE')).toBe(strawberry); expect(convertEmojiSkinTone(strawberry, '1F3FF')).toBe(strawberry); }); test('should do nothing for emojis with multiple skin tones', () => { const emoji = getEmoji('man_and_woman_holding_hands_medium_light_skin_tone_medium_dark_skin_tone'); expect(convertEmojiSkinTone(emoji, 'default')).toBe(emoji); expect(convertEmojiSkinTone(emoji, '1F3FB')).toBe(emoji); expect(convertEmojiSkinTone(emoji, '1F3FC')).toBe(emoji); expect(convertEmojiSkinTone(emoji, '1F3FD')).toBe(emoji); expect(convertEmojiSkinTone(emoji, '1F3FE')).toBe(emoji); expect(convertEmojiSkinTone(emoji, '1F3FF')).toBe(emoji); }); }); function getEmoji(name: string) { return Emojis[EmojiIndicesByAlias.get(name)!]; }
4,464
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/emoticons.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Emoticons from 'utils/emoticons'; describe('Emoticons', () => { describe('handleEmoticons', () => { // test emoticon patterns const emoticonPatterns = { slightly_smiling_face: [':)', ':-)'], wink: [';)', ';-)'], open_mouth: [':o'], scream: [':-o'], smirk: [':]', ':-]'], smile: [':D', ':-D'], stuck_out_tongue_closed_eyes: ['x-d'], stuck_out_tongue: [':p', ':-p'], rage: [':@', ':-@'], slightly_frowning_face: [':(', ':-('], cry: [':`(', ':\'(', ':’('], confused: [':/', ':-/'], confounded: [':s', ':-s'], neutral_face: [':|', ':-|'], flushed: [':$', ':-$'], mask: [':-x'], heart: ['<3', '&lt;3'], broken_heart: ['</3', '&lt;/3'], }; Array.prototype.concat(...Object.values(emoticonPatterns)).forEach((emoticon) => { test(`text sequence '${emoticon}' should be recognized as an emoticon`, () => { expect(Emoticons.handleEmoticons(emoticon, new Map())).toEqual('$MM_EMOTICON0$'); }); }); // test various uses of emoticons test('should replace emoticons with tokens', () => { expect(Emoticons.handleEmoticons(':goat: :dash:', new Map())). toEqual('$MM_EMOTICON0$ $MM_EMOTICON1$'); }); test('should replace emoticons not separated by whitespace', () => { expect(Emoticons.handleEmoticons(':goat::dash:', new Map())). toEqual('$MM_EMOTICON0$$MM_EMOTICON1$'); }); test('should replace emoticons separated by punctuation', () => { expect(Emoticons.handleEmoticons('/:goat:..:dash:)', new Map())). toEqual('/$MM_EMOTICON0$..$MM_EMOTICON1$)'); }); test('should replace emoticons separated by text', () => { expect(Emoticons.handleEmoticons('asdf:goat:asdf:dash:asdf', new Map())). toEqual('asdf$MM_EMOTICON0$asdf$MM_EMOTICON1$asdf'); }); test('shouldn\'t replace invalid emoticons', () => { expect(Emoticons.handleEmoticons(':goat : : dash:', new Map())). toEqual(':goat : : dash:'); }); test('should allow comma immediately following emoticon :)', () => { expect(Emoticons.handleEmoticons(':),', new Map())). toEqual('$MM_EMOTICON0$,'); }); test('should allow comma immediately following emoticon :P', () => { expect(Emoticons.handleEmoticons(':P,', new Map())). toEqual('$MM_EMOTICON0$,'); }); test('should allow punctuation immediately following emoticon :)', () => { expect(Emoticons.handleEmoticons(':)!', new Map())). toEqual('$MM_EMOTICON0$!'); }); test('should allow punctuation immediately following emoticon :P', () => { expect(Emoticons.handleEmoticons(':P!', new Map())). toEqual('$MM_EMOTICON0$!'); }); test('should allow punctuation immediately before and following emoticon :)', () => { expect(Emoticons.handleEmoticons('":)"', new Map())). toEqual('"$MM_EMOTICON0$"'); }); test('should allow punctuation immediately before and following emoticon :P', () => { expect(Emoticons.handleEmoticons('":P"', new Map())). toEqual('"$MM_EMOTICON0$"'); }); }); describe('matchEmoticons', () => { test('empty message', () => { expect(Emoticons.matchEmoticons('')). toEqual(null); }); test('no emoticons', () => { expect(Emoticons.matchEmoticons('test')). toEqual(null); }); describe('single', () => { test('shorthand forms', () => { expect(Emoticons.matchEmoticons(':+1:')). toEqual([':+1:']); }); test('named emoticons forms', () => { expect(Emoticons.matchEmoticons(':thumbs_up:')). toEqual([':thumbs_up:']); }); }); describe('multiple', () => { test('shorthand forms', () => { expect(Emoticons.matchEmoticons(':+1: :D')). toEqual([':+1:', ':D']); }); test('named emoticons forms', () => { expect(Emoticons.matchEmoticons(':thumbs_up: :smile:')). toEqual([':thumbs_up:', ':smile:']); }); test('mixed', () => { expect(Emoticons.matchEmoticons(':thumbs_up: :smile: :+1: :D')). toEqual([':thumbs_up:', ':smile:', ':+1:', ':D']); }); }); test('inline', () => { expect(Emoticons.matchEmoticons('I am feeling pretty :D -- you are: ok?')). toEqual([':D']); }); test('shouldn\'t render emoticons in code blocks', () => { expect(Emoticons.matchEmoticons('`:goat:`')). toEqual(null); }); test('shouldn\'t render emoticons in multiline code blocks', () => { expect(Emoticons.matchEmoticons('`:goat:` \n `:smile:`')). toEqual(null); }); test('shouldn\'t render emoticons in links', () => { expect(Emoticons.matchEmoticons('[link](www.google.com/:goat:)')). toEqual(null); }); test('shouldn\'t render emoticons in multiline links', () => { expect(Emoticons.matchEmoticons('[link](www.google.com/:goat:) \n [link](www.google.com/:smile:)')). toEqual(null); }); }); });
4,468
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/file_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { trimFilename, canUploadFiles, getFileTypeFromMime, } from 'utils/file_utils'; import * as UserAgent from 'utils/user_agent'; describe('FileUtils.trimFilename', () => { it('trimFilename: should return same filename', () => { expect(trimFilename('abcdefghijklmnopqrstuvwxyz')).toBe('abcdefghijklmnopqrstuvwxyz'); }); it('trimFilename: should return trimmed filename', () => { expect(trimFilename('abcdefghijklmnopqrstuvwxyz0123456789')).toBe('abcdefghijklmnopqrstuvwxyz012345678...'); }); }); describe('FileUtils.canUploadFiles', () => { (UserAgent as any).isMobileApp = jest.fn().mockImplementation(() => false); // eslint-disable-line no-import-assign it('is false when file attachments are disabled', () => { const config = { EnableFileAttachments: 'false', EnableMobileFileUpload: 'true', }; expect(canUploadFiles(config)).toBe(false); }); describe('is true when file attachments are enabled', () => { (UserAgent as any).isMobileApp.mockImplementation(() => false); it('and not on mobile', () => { (UserAgent as any).isMobileApp.mockImplementation(() => false); const config = { EnableFileAttachments: 'true', EnableMobileFileUpload: 'false', }; expect(canUploadFiles(config)).toBe(true); }); it('and on mobile with mobile file upload enabled', () => { (UserAgent as any).isMobileApp.mockImplementation(() => true); const config = { EnableFileAttachments: 'true', EnableMobileFileUpload: 'true', }; expect(canUploadFiles(config)).toBe(true); }); it('unless on mobile with mobile file upload disabled', () => { (UserAgent as any).isMobileApp.mockImplementation(() => true); const config = { EnableFileAttachments: 'true', EnableMobileFileUpload: 'false', }; expect(canUploadFiles(config)).toBe(false); }); }); describe('get filetypes based on mime interpreted from browsers', () => { it('mime type for videos', () => { expect(getFileTypeFromMime('video/mp4')).toBe('video'); }); it('mime type for audio', () => { expect(getFileTypeFromMime('audio/mp3')).toBe('audio'); }); it('mime type for image', () => { expect(getFileTypeFromMime('image/JPEG')).toBe('image'); }); it('mime type for pdf', () => { expect(getFileTypeFromMime('application/pdf')).toBe('pdf'); }); it('mime type for spreadsheet', () => { expect(getFileTypeFromMime('application/vnd.ms-excel')).toBe('spreadsheet'); }); it('mime type for presentation', () => { expect(getFileTypeFromMime('application/vnd.ms-powerpoint')).toBe('presentation'); }); it('mime type for word', () => { expect(getFileTypeFromMime('application/vnd.ms-word')).toBe('word'); }); it('mime type for unknown file format', () => { expect(getFileTypeFromMime('application/unknownFormat')).toBe('other'); }); it('mime type for no suffix', () => { expect(getFileTypeFromMime('asdasd')).toBe('other'); }); }); });
4,470
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/filter_users.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {getUserOptionsFromFilter, searchUserOptionsFromFilter, isActive} from './filter_users'; import type {FilterOptions} from './filter_users'; describe('filter_users', () => { describe('getUserOptionsFromFilter', () => { it('should return empty options in case of empty filter', () => { const filters: FilterOptions = getUserOptionsFromFilter(''); expect(filters).toEqual({}); }); it('should return empty options in case of undefined', () => { const filters: FilterOptions = getUserOptionsFromFilter(undefined); expect(filters).toEqual({}); }); it('should return role options in case of system_admin', () => { const filters: FilterOptions = getUserOptionsFromFilter('system_admin'); expect(filters).toEqual({role: 'system_admin'}); }); it('should return inactive option in case of inactive', () => { const filters: FilterOptions = getUserOptionsFromFilter('inactive'); expect(filters).toEqual({inactive: true}); }); }); describe('searchUserOptionsFromFilter', () => { it('should return empty options in case of empty filter', () => { const filters: FilterOptions = searchUserOptionsFromFilter(''); expect(filters).toEqual({}); }); it('should return empty options in case of undefined', () => { const filters: FilterOptions = searchUserOptionsFromFilter(undefined); expect(filters).toEqual({}); }); it('should return role options in case of system_admin', () => { const filters: FilterOptions = searchUserOptionsFromFilter('system_admin'); expect(filters).toEqual({role: 'system_admin'}); }); it('should return allow_inactive option in case of inactive', () => { const filters: FilterOptions = searchUserOptionsFromFilter('inactive'); expect(filters).toEqual({allow_inactive: true}); }); }); describe('isActive', () => { it('should return true for an active user', () => { const active = isActive({delete_at: 0}); expect(active).toEqual(true); }); it('should return false for an inactive user', () => { const active = isActive({delete_at: 1}); expect(active).toEqual(false); }); }); });
4,472
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/func.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {reArg} from './func'; describe('utils/func', () => { const a = 1; const b = 2; const c = 3; const component = 'Component'; const node = 'Node'; const children = 'Children'; describe('reArg', () => { type TArgs = {a: 1; b: 2; c: 3; component: string; node: string; children: string}; const method = reArg(['a', 'b', 'c', 'component', 'node', 'children'], (props: TArgs) => props); const normalizedArgs = {a, b, c, component, node, children}; test('should support traditional ordered-arguments', () => { const result = method(a, b, c, component, node, children); expect(result).toMatchObject(normalizedArgs); }); test('should support object-argument', () => { const result = method({a, b, c, component, node, children}); expect(result).toMatchObject(normalizedArgs); }); }); });
4,477
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/keyboard.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Keyboard from './keyboard'; describe('isKeyPressed', () => { test('Key match is used over keyCode if it exists', () => { for (const data of [ { event: new KeyboardEvent('keydown', {key: '/', keyCode: 55}), key: ['/', 191], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'ù', keyCode: 191}), key: ['/', 191], valid: true, }, ]) { expect(Keyboard.isKeyPressed(data.event, data.key as [string, number])).toEqual(data.valid); } }); test('Key match works for both uppercase and lower case', () => { for (const data of [ { event: new KeyboardEvent('keydown', {key: 'A', keyCode: 65, code: 'KeyA'}), key: ['a', 65], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'a', keyCode: 65, code: 'KeyA'}), key: ['a', 65], valid: true, }, ]) { expect(Keyboard.isKeyPressed(data.event, data.key as [string, number])).toEqual(data.valid); } }); test('KeyCode is used for dead letter keys', () => { for (const data of [ { event: new KeyboardEvent('keydown', {key: 'Dead', keyCode: 222}), key: ['', 222], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'Dead', keyCode: 222}), key: ['not-used-field', 222], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'Dead', keyCode: 222}), key: [null, 222], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'Dead', keyCode: 222}), key: [null, 223], valid: false, }, ]) { expect(Keyboard.isKeyPressed(data.event, data.key as [string, number])).toEqual(data.valid); } }); test('KeyCode is used for unidentified keys', () => { for (const data of [ { event: new KeyboardEvent('keydown', {key: 'Unidentified', keyCode: 2220, code: 'Unidentified'}), key: ['', 2220], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'Unidentified', keyCode: 2220, code: 'Unidentified'}), key: ['not-used-field', 2220], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'Unidentified', keyCode: 2220, code: 'Unidentified'}), key: [null, 2220], valid: true, }, { event: new KeyboardEvent('keydown', {key: 'Unidentified', keyCode: 2220, code: 'Unidentified'}), key: [null, 2221], valid: false, }, ]) { expect(Keyboard.isKeyPressed(data.event, data.key as [string, number])).toEqual(data.valid); } }); test('KeyCode is used for undefined keys', () => { for (const data of [ { event: {keyCode: 2221}, key: ['', 2221], valid: true, }, { event: {keyCode: 2221}, key: ['not-used-field', 2221], valid: true, }, { event: {keyCode: 2221}, key: [null, 2221], valid: true, }, { event: {keyCode: 2221}, key: [null, 2222], valid: false, }, ]) { expect(Keyboard.isKeyPressed(data.event as KeyboardEvent, data.key as [string, number])).toEqual(data.valid); } }); test('keyCode is used for determining if it exists', () => { for (const data of [ { event: {key: 'a', keyCode: 65}, key: ['k', 65], valid: true, }, { event: {key: 'b', keyCode: 66}, key: ['y', 66], valid: true, }, ]) { expect(Keyboard.isKeyPressed(data.event as KeyboardEvent, data.key as [string, number])).toEqual(data.valid); } }); test('key should be tested as fallback for different layout of english keyboards', () => { //key will be k for keyboards like dvorak but code will be keyV as `v` is pressed const event = {key: 'k', code: 'KeyV'}; const key: [string, number] = ['k', 2221]; expect(Keyboard.isKeyPressed(event as KeyboardEvent, key)).toEqual(true); }); });
4,479
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/latinise.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {latinise} from 'utils/latinise'; describe('Latinise', () => { test('should return ascii version of Dév Spé', () => { expect(latinise('Dév Spé')). toEqual('Dev Spe'); }); test('should not replace any characters', () => { expect(latinise('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')). toEqual('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'); }); test('should replace characters with diacritics with ascii equivalents', () => { expect(latinise('àáâãäåæçèéêëìíîïñòóôõöœùúûüýÿ')). toEqual('aaaaaaaeceeeeiiiinooooooeuuuuyy'); }); });
4,481
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/license_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {LicenseSkus} from 'utils/constants'; import {isLicenseExpired, isLicenseExpiring, isLicensePastGracePeriod, isEnterpriseOrE20License} from 'utils/license_utils'; describe('license_utils', () => { const millisPerDay = 24 * 60 * 60 * 1000; describe('isLicenseExpiring', () => { it('should return false if cloud expiring in 5 days', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'true', ExpiresAt: `${Date.now() + (5 * millisPerDay)}`}; expect(isLicenseExpiring(license)).toBeFalsy(); }); it('should return True if expiring in 5 days - non Cloud', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'false', ExpiresAt: `${Date.now() + (5 * millisPerDay)}`}; expect(isLicenseExpiring(license)).toBeTruthy(); }); }); describe('isLicenseExpired', () => { it('should return false if cloud expired 1 day ago', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'true', ExpiresAt: `${Date.now() - (Number(millisPerDay))}`}; expect(isLicenseExpired(license)).toBeFalsy(); }); it('should return True if expired 1 day ago - non Cloud', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'false', ExpiresAt: `${Date.now() - (Number(millisPerDay))}`}; expect(isLicenseExpired(license)).toBeTruthy(); }); }); describe('isLicensePastGracePeriod', () => { it('should return False if cloud expired 11 days ago', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'true', ExpiresAt: `${Date.now() - (11 * millisPerDay)}`}; expect(isLicensePastGracePeriod(license)).toBeFalsy(); }); it('should return True if expired 1 day ago - non Cloud', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'false', ExpiresAt: `${Date.now() - (11 * millisPerDay)}`}; expect(isLicensePastGracePeriod(license)).toBeTruthy(); }); }); describe('isEnterpriseOrE20License', () => { it('should return False if not Enterprise or E20', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'false', SkuShortName: LicenseSkus.Starter}; expect(isEnterpriseOrE20License(license)).toBeFalsy(); }); it('should return True if Enterprise', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'false', SkuShortName: LicenseSkus.Enterprise}; expect(isEnterpriseOrE20License(license)).toBeTruthy(); }); it('should return True if E20', () => { const license = {Id: '1234', IsLicensed: 'true', Cloud: 'false', SkuShortName: LicenseSkus.E20}; expect(isEnterpriseOrE20License(license)).toBeTruthy(); }); }); });