level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
8,396
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/caroseltemBehavior-test.tsx
import { carouselItemBehavior } from '@fluentui/accessibility'; describe('carouselItemBehavior.ts', () => { test('sets tabIndex="0" on root when carousel has navigation and item is visible ', () => { const expectedResult = carouselItemBehavior({ navigation: true, active: true }); expect(expectedResult.attributes.root.tabIndex).toEqual(0); }); test('sets tabIndex="-1" on root when carousel has navigation and item is NOT visible ', () => { const expectedResult = carouselItemBehavior({ navigation: true, active: false }); expect(expectedResult.attributes.root.tabIndex).toEqual(-1); }); test('do NOT set tabIndex on root when carousel has NO navigation', () => { const expectedResult = carouselItemBehavior({ navigation: false, active: true }); expect(expectedResult.attributes.root.tabIndex).toBeUndefined; }); });
8,397
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/dialogBehavior-test.tsx
import { dialogBehavior } from '@fluentui/accessibility'; import * as React from 'react'; describe('DialogBehavior.ts', () => { test('adds tabIndex=0 to trigger if element is not tabbable and tabIndex attribute is not provided', () => { const expectedResult = dialogBehavior({ trigger: <div />, tabbableTrigger: true }); expect(expectedResult.attributes.trigger.tabIndex).toEqual(0); }); test('adds tabIndex attribute with value passed as prop', () => { const expectedResult = dialogBehavior({ trigger: <div tabIndex={-1} />, tabbableTrigger: true, }); expect(expectedResult.attributes.trigger.tabIndex).toEqual(-1); }); test('does not add tabIndex if element is already tabbable', () => { const expectedResult = dialogBehavior({ trigger: <button />, tabbableTrigger: true }); expect(expectedResult.attributes.trigger.tabIndex).toBeUndefined(); }); test('uses computed "aria-describedby" based on "contentId"', () => { const expectedResult = dialogBehavior({ contentId: 'content-id' }); expect(expectedResult.attributes.popup['aria-describedby']).toEqual('content-id'); expect(expectedResult.attributes.content.id).toEqual('content-id'); }); test('uses computed "aria-labelledby" based on "headerId"', () => { const expectedResult = dialogBehavior({ headerId: 'header-id' }); expect(expectedResult.attributes.popup['aria-labelledby']).toEqual('header-id'); expect(expectedResult.attributes.header.id).toEqual('header-id'); }); });
8,398
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/gridRowBehavior-test.tsx
import { gridRowBehavior } from '@fluentui/accessibility'; describe('gridRowBehavior.ts', () => { test('use gridHeaderRowBehavior if grid row has header prop defined', () => { const props = { header: true, }; const expectedResult = gridRowBehavior(props); expect(expectedResult.childBehaviors.cell.name).toEqual('gridHeaderCellBehavior'); }); test('use gridRowNestedBehavior if grid row has NOT header prop defined', () => { const props = {}; const expectedResult = gridRowBehavior(props); expect(expectedResult.childBehaviors.cell.name).toEqual('gridCellBehavior'); }); });
8,399
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/listBehavior-test.tsx
import { listBehavior } from '@fluentui/accessibility'; describe('ListBehavior.ts', () => { test('use SelectableListBehavior if selectable prop is defined', () => { const property = { selectable: true, }; const expectedResult = listBehavior(property); expect(expectedResult.attributes.root.role).toEqual('listbox'); }); test('use NavigableListBehavior if navigable prop is defined', () => { const property = { navigable: true, }; const expectedResult = listBehavior(property); expect(expectedResult.attributes.root.role).toEqual('menu'); expect(expectedResult.focusZone).toBeTruthy(); }); test('use BasicListItemBehavior if selectable prop is NOT defined', () => { const property = {}; const expectedResult = listBehavior(property); expect(expectedResult.attributes.root.role).toEqual('list'); }); });
8,400
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/listItemBehavior-test.tsx
import { listItemBehavior, IS_FOCUSABLE_ATTRIBUTE } from '@fluentui/accessibility'; describe('ListItemBehavior.ts', () => { test('use SelectableListItemBehavior if selectable prop is defined', () => { const property = { selectable: true, }; const expectedResult = listItemBehavior(property); expect(expectedResult.attributes.root.role).toEqual('option'); }); test('use NavigableListItemBehavior if navigable prop is defined', () => { const property = { navigable: true, }; const expectedResult = listItemBehavior(property); expect(expectedResult.attributes.root.role).toEqual('menuitem'); expect(expectedResult.attributes.root[IS_FOCUSABLE_ATTRIBUTE]).toEqual(true); }); test('use BasicListBehavior if selectable prop is NOT defined', () => { const property = {}; const expectedResult = listItemBehavior(property); expect(expectedResult.attributes.root.role).toEqual('listitem'); }); });
8,401
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/loaderBehavior-test.tsx
import { loaderBehavior } from '@fluentui/accessibility'; describe('LoaderBehavior.ts', () => { test('do NOT add aria-labelledby, when aria-label was set already', () => { const props = { labelId: 'label-id', 'aria-label': 'any loading string' }; const expectedResult = loaderBehavior(props); expect(expectedResult.attributes.root['aria-labelledby']).toEqual(undefined); }); test('do NOT add aria-labelledby, when aria-labelled was set already', () => { const props = { labelId: 'label-id', 'aria-labelledby': 'id' }; const expectedResult = loaderBehavior(props); expect(expectedResult.attributes.root['aria-labelledby']).toEqual(undefined); }); test('do NOT add aria-labelledby, when there is no tabIndex specified', () => { const props = { labelId: 'label-id' }; const expectedResult = loaderBehavior(props); expect(expectedResult.attributes.root['aria-labelledby']).toEqual(undefined); }); test('add aria-labelledby, when there is tabIndex=0 specified', () => { const props = { labelId: 'label-id', tabIndex: 0 }; const expectedResult = loaderBehavior(props); expect(expectedResult.attributes.root['aria-labelledby']).toEqual('label-id'); }); test('add aria-labelledby, when there is tabIndex=-1 specified', () => { const props = { labelId: 'label-id', tabIndex: -1 }; const expectedResult = loaderBehavior(props); expect(expectedResult.attributes.root['aria-labelledby']).toEqual('label-id'); }); });
8,402
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/menuButtonBehavior-test.tsx
import { menuButtonBehavior } from '@fluentui/accessibility'; const mockedMenuId = 'anyMenuId'; describe('MenuButtonBehavior.ts', () => { test('aria-controls are NOT defined, when menu is NOT open', () => { const property = { open: false, menuId: mockedMenuId, }; const expectedResult = menuButtonBehavior(property); expect(expectedResult.attributes.trigger['aria-controls']).toBe(undefined); }); test('aria-controls are defined, when menu is open', () => { const property = { open: true, menuId: mockedMenuId, }; const expectedResult = menuButtonBehavior(property); expect(expectedResult.attributes.trigger['aria-controls']).toBe(mockedMenuId); }); });
8,403
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/popupBehavior-test.tsx
import { popupBehavior } from '@fluentui/accessibility'; import * as React from 'react'; describe('PopupBehavior.ts', () => { test('adds tabIndex=0 to trigger if element is not tabbable and tabIndex attribute is not provided', () => { const expectedResult = popupBehavior({ trigger: <div />, tabbableTrigger: true }); expect(expectedResult.attributes.trigger.tabIndex).toEqual(0); }); test('does not add tabIndex=0 to trigger if element is not tabbable and tabIndex attribute is not provided and tabbableTrigger is false', () => { const expectedResult = popupBehavior({ trigger: <div />, tabbableTrigger: false }); expect(expectedResult.attributes.trigger.tabIndex).toBeUndefined(); }); test('adds tabIndex attribute with value passed as prop', () => { const expectedResult = popupBehavior({ trigger: <div tabIndex={-1} />, tabbableTrigger: true, }); expect(expectedResult.attributes.trigger.tabIndex).toEqual(-1); }); test('Do not override trigger aria-haspopup attribute', () => { const expectedResult = popupBehavior({ trigger: <button aria-haspopup={null} />, tabbableTrigger: true, }); expect(expectedResult.attributes.trigger['aria-haspopup']).toBeNull(); }); // TODO: Fix me // test('does not add tabIndex if element is already tabbable', () => { // const expectedResult = popupBehavior({ trigger: <Button />, tabbableTrigger: true }) // expect(expectedResult.attributes.trigger.tabIndex).toBeUndefined() // }) });
8,404
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/sliderBehavior-test.ts
import { sliderBehavior } from '@fluentui/accessibility'; type SliderBehaviorTestOptions = { propName: string; propValue: string | boolean | number; slotName: string; attrName: string; result?: string; }; function generatePropertyTest({ result, attrName, propName, propValue, slotName }: SliderBehaviorTestOptions) { test(`${attrName} is set based on property ${propName}:${propValue}`, () => { const resultValue = result || propValue; const props = { [propName]: propValue, getA11yValueMessageOnChange: () => { return undefined; }, }; const expectedResult = sliderBehavior(props); expect(expectedResult.attributes[slotName][attrName]).toEqual(resultValue); }); } describe('SliderBehavior.ts', () => { generatePropertyTest({ propName: 'disabled', propValue: true, slotName: 'root', attrName: 'aria-disabled', }); generatePropertyTest({ propName: 'min', propValue: 0, slotName: 'input', attrName: 'aria-valuemin', }); generatePropertyTest({ propName: 'max', propValue: 0, slotName: 'input', attrName: 'aria-valuemax', }); generatePropertyTest({ propName: 'value', propValue: 0, slotName: 'input', attrName: 'aria-valuenow', }); generatePropertyTest({ propName: 'vertical', propValue: true, slotName: 'input', attrName: 'aria-orientation', result: 'vertical', }); generatePropertyTest({ propName: 'vertical', propValue: false, slotName: 'input', attrName: 'aria-orientation', result: 'horizontal', }); test('aria-valuetext is set based on the property getA11yValueMessageOnChange', () => { const ariaValueText = 'custom aria value text'; const customAriaValueText = () => { return ariaValueText; }; const property = { getA11yValueMessageOnChange: customAriaValueText, }; const expectedResult = sliderBehavior(property); expect(expectedResult.attributes.input['aria-valuetext']).toEqual(ariaValueText); }); });
8,405
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/splitButtonBehavior-test.tsx
import { splitButtonBehavior, keyboardKey } from '@fluentui/accessibility'; import * as _ from 'lodash'; function verifyKeys(supportedKeys, keysFromBehavior) { keysFromBehavior.forEach(keyCombination => { const keyCombinationFound = _.find(supportedKeys, keyCombination); expect(keyCombinationFound).toEqual(keyCombination); }); } describe('SplitButtonBehavior.ts', () => { test('aria-haspopup is not defined for splitButton', () => { const property = { contextMenu: false, }; const expectedResult = splitButtonBehavior(property); expect(expectedResult['childBehaviors']['menuButton'](property).attributes.trigger['aria-haspopup']).toBe( undefined, ); }); test('close menu with different keys', () => { const property = {}; const supportedKeys = [ { keyCode: keyboardKey.Escape }, { altKey: true, keyCode: keyboardKey.ArrowUp }, { keyCode: keyboardKey.Tab, shiftKey: false }, { keyCode: keyboardKey.Tab, shiftKey: true }, ]; const keysFromBehavior = splitButtonBehavior(property)['childBehaviors']['menuButton'](property).keyActions.popup.closeAndFocusTrigger .keyCombinations; verifyKeys(supportedKeys, keysFromBehavior); }); test('open menu with alt + arrow down ', () => { const property = {}; const supportedKeys = [{ altKey: true, keyCode: keyboardKey.ArrowDown }]; const keysFromBehavior = splitButtonBehavior(property)['childBehaviors']['menuButton'](property).keyActions.root.openAndFocusFirst .keyCombinations; verifyKeys(supportedKeys, keysFromBehavior); }); });
8,406
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/tableRowBehavior-test.tsx
import { tableRowBehavior } from '@fluentui/accessibility'; describe('tableRowBehavior.ts', () => { test('use tableHeaderCellBehavior if table row has header prop defined', () => { const props = { header: true, }; const expectedResult = tableRowBehavior(props); expect(expectedResult.childBehaviors.cell.name).toEqual('tableHeaderCellBehavior'); }); test('use tableCellBehavior if table row has NOT header prop defined', () => { const props = {}; const expectedResult = tableRowBehavior(props); expect(expectedResult.childBehaviors.cell.name).toEqual('tableCellBehavior'); }); });
8,409
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/treeItemAsListItemBehavior-test.tsx
import { treeItemAsListItemBehavior } from '@fluentui/accessibility'; describe('TreeItemAsListItemBehavior', () => { describe('role', () => { test(`is 'listitem' if not a leaf`, () => { const expectedResult = treeItemAsListItemBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.role).toEqual('listitem'); }); test(`is 'none' if a leaf`, () => { const expectedResult = treeItemAsListItemBehavior({ hasSubtree: false }); expect(expectedResult.attributes.root.role).toEqual('none'); }); }); });
8,410
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/treeItemAsOptionBehavior-test.tsx
import { treeItemAsOptionBehavior } from '@fluentui/accessibility'; describe('treeItemAsOptionBehavior', () => { describe('role', () => { test(`is 'option' when item hasSubtree`, () => { const expectedResult = treeItemAsOptionBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.role).toEqual('option'); }); }); describe('aria-selected', () => { test(`is added with 'true' value to an item hasSubtree, is selectable and selected`, () => { const expectedResult = treeItemAsOptionBehavior({ hasSubtree: true, selectable: true, selected: true }); expect(expectedResult.attributes.root['aria-selected']).toEqual(true); }); test(`is added with 'false' value to an item hasSubtree, is selectable and not selected`, () => { const expectedResult = treeItemAsOptionBehavior({ hasSubtree: true, selectable: true }); expect(expectedResult.attributes.root['aria-selected']).toEqual(false); }); test(`is not added to an item that is not selectable `, () => { const expectedResult = treeItemAsOptionBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root['aria-selected']).toBeUndefined(); }); }); });
8,411
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/treeItemBehavior-test.tsx
import { treeItemBehavior, keyboardKey, SpacebarKey } from '@fluentui/accessibility'; describe('TreeItemBehavior', () => { describe('tabIndex', () => { test(`is added with '0' value to an item that is expandable`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.tabIndex).toEqual(-1); }); test(`is not added to a leaf item (no items)`, () => { const expectedResult = treeItemBehavior({}); expect(expectedResult.attributes.root.tabIndex).toBeUndefined(); }); }); describe('aria-expanded', () => { test(`is not added to a leaf item`, () => { const expectedResult = treeItemBehavior({}); expect(expectedResult.attributes.root['aria-expanded']).toBeUndefined(); }); test(`is added with 'false' value to an item that is expandable but not open`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true, expanded: false }); expect(expectedResult.attributes.root['aria-expanded']).toEqual(false); }); test(`is added with 'false' value to an item that is expandable and open`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true, expanded: true }); expect(expectedResult.attributes.root['aria-expanded']).toEqual(true); }); }); describe('role', () => { test(`is 'treeitem' if not a leaf`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.role).toEqual('treeitem'); }); test(`is 'none' if a leaf`, () => { const expectedResult = treeItemBehavior({}); expect(expectedResult.attributes.root.role).toEqual('none'); }); }); describe('keyboard interaction', () => { test(`click is executed only with 'spacebar', when tree item is 'selectable' and tree item has no subtree`, () => { const expectedResult = treeItemBehavior({ selectable: true, hasSubtree: false }); expect(expectedResult.keyActions.root.performClick.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.performClick.keyCombinations[0].keyCode).toEqual(SpacebarKey); }); test(`selection is executed only with 'spacebar', when tree item is 'selectable'`, () => { const expectedResult = treeItemBehavior({ selectable: true }); expect(expectedResult.keyActions.root.performSelection.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.performSelection.keyCombinations[0].keyCode).toEqual(SpacebarKey); }); test(`click is executed with 'enter' key, when tree item is 'selectable' and tree item has subtree`, () => { const expectedResult = treeItemBehavior({ selectable: true, hasSubtree: true }); expect(expectedResult.keyActions.root.performClick.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.performClick.keyCombinations[0].keyCode).toEqual(keyboardKey.Enter); }); test(`arrow left navigation, should collapse when tree expanded`, () => { const expectedResult = treeItemBehavior({ expanded: true, hasSubtree: true }); expect(expectedResult.keyActions.root.collapse.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.collapse.keyCombinations[0].keyCode).toEqual(keyboardKey.ArrowLeft); }); test(`arrow left navigation, should focus on parent when tree is not expanded`, () => { const expectedResult = treeItemBehavior({ expanded: false, hasSubtree: true }); expect(expectedResult.keyActions.root.focusParent.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.focusParent.keyCombinations[0].keyCode).toEqual(keyboardKey.ArrowLeft); }); test(`arrow left navigation, should focus on parent when treeItem has no subtree`, () => { const expectedResult = treeItemBehavior({ hasSubtree: false }); expect(expectedResult.keyActions.root.focusParent.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.focusParent.keyCombinations[0].keyCode).toEqual(keyboardKey.ArrowLeft); }); test(`arrow right navigation, should expand when tree collapsed`, () => { const expectedResult = treeItemBehavior({ expanded: false, hasSubtree: true }); expect(expectedResult.keyActions.root.expand.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.expand.keyCombinations[0].keyCode).toEqual(keyboardKey.ArrowRight); }); test(`arrow right navigation, should focus on frist child when tree expanded`, () => { const expectedResult = treeItemBehavior({ expanded: true, hasSubtree: true }); expect(expectedResult.keyActions.root.focusFirstChild.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.focusFirstChild.keyCombinations[0].keyCode).toEqual(keyboardKey.ArrowRight); }); }); describe('aria-checked', () => { test(`is added with 'true' value to an item that has hasSubtree, is selectable and selected`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true, selectable: true, selected: true }); expect(expectedResult.attributes.root['aria-checked']).toEqual(true); }); test(`is added with 'false' value to an item that has hasSubtree, is selectable and not selected`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true, selectable: true }); expect(expectedResult.attributes.root['aria-checked']).toEqual(false); }); test(`is added with 'mixed' value to an item that has hasSubtree, is selectable and in indeterminate state`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true, selectable: true, indeterminate: true }); expect(expectedResult.attributes.root['aria-checked']).toEqual('mixed'); }); test(`is not added to an item that is not selectable`, () => { const expectedResult = treeItemBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root['aria-checked']).toBeUndefined(); }); }); });
8,412
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/treeTitleAsListItemTitleBehavior-test.tsx
import { treeTitleAsListItemTitleBehavior } from '@fluentui/accessibility'; describe('TreeTitleBehavior', () => { describe('role', () => { test(`is added with 'listitem' value to a title with hasSubtree prop false`, () => { const expectedResult = treeTitleAsListItemTitleBehavior({ hasSubtree: false }); expect(expectedResult.attributes.root.role).toEqual('listitem'); }); test(`is not added to a title with hasSubtree prop true`, () => { const expectedResult = treeTitleAsListItemTitleBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.role).toBeUndefined(); }); }); });
8,413
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/treeTitleAsOptionBehavior-test.tsx
import { treeTitleAsOptionBehavior } from '@fluentui/accessibility'; describe('TreeTitleBehavior', () => { describe('role', () => { test(`is 'option' when item does not hasSubtree`, () => { const expectedResult = treeTitleAsOptionBehavior({ selectable: true }); expect(expectedResult.attributes.root.role).toEqual('option'); }); }); describe('aria-selected', () => { test(`is added with 'selected' prop value to a title when tree title does not hasSubtree, and is 'selectable'`, () => { const expectedResultWhenSelected = treeTitleAsOptionBehavior({ selectable: true, selected: true, }); const expectedResultWhenNotSelected = treeTitleAsOptionBehavior({ selectable: true, selected: false, }); expect(expectedResultWhenSelected.attributes.root['aria-selected']).toEqual(true); expect(expectedResultWhenNotSelected.attributes.root['aria-selected']).toEqual(false); }); test(`is not added to a title, when tree title is NOT 'selectable'`, () => { const expectedResult = treeTitleAsOptionBehavior({ selectable: false }); expect(expectedResult.attributes.root['aria-selected']).toBeUndefined(); }); }); });
8,414
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/treeTitleBehavior-test.tsx
import { treeTitleBehavior, keyboardKey, SpacebarKey } from '@fluentui/accessibility'; describe('TreeTitleBehavior', () => { describe('tabIndex', () => { test(`is added with '0' value to a title with hasSubtree prop false`, () => { const expectedResult = treeTitleBehavior({ hasSubtree: false }); expect(expectedResult.attributes.root.tabIndex).toEqual(-1); }); test(`is not added to a title with hasSubtree prop true`, () => { const expectedResult = treeTitleBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.tabIndex).toBeUndefined(); }); }); describe('role', () => { test(`is added with 'treeitem' value to a title with hasSubtree prop false`, () => { const expectedResult = treeTitleBehavior({ hasSubtree: false }); expect(expectedResult.attributes.root.role).toEqual('treeitem'); }); test(`is not added to a title with hasSubtree prop true`, () => { const expectedResult = treeTitleBehavior({ hasSubtree: true }); expect(expectedResult.attributes.root.role).toBeUndefined(); }); }); describe('aria-checked', () => { test(`is added with 'selected' prop value to a title with hasSubtree prop false, when tree title is 'selectable'`, () => { const expectedResultWhenSelected = treeTitleBehavior({ hasSubtree: false, selectable: true, selected: true }); const expectedResultWhenNotSelected = treeTitleBehavior({ hasSubtree: false, selectable: true, selected: false }); expect(expectedResultWhenSelected.attributes.root['aria-checked']).toEqual(true); expect(expectedResultWhenNotSelected.attributes.root['aria-checked']).toEqual(false); }); test(`is not added to a title, when tree title is NOT 'selectable'`, () => { const expectedResult = treeTitleBehavior({ selectable: false }); expect(expectedResult.attributes.root['aria-checked']).toBeUndefined(); }); }); describe('keyboard interaction', () => { test(`click is executed only with 'spacebar' or 'enter', when tree title is 'selectable'`, () => { const expectedResult = treeTitleBehavior({ selectable: true, hasSubtree: true }); expect(expectedResult.keyActions.root.performClick.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.performClick.keyCombinations[0].keyCode).toEqual(SpacebarKey); }); test(`arrow left navigation, should focus on parent `, () => { const expectedResult = treeTitleBehavior({ hasSubtree: false }); expect(expectedResult.keyActions.root.focusParent.keyCombinations).toHaveLength(1); expect(expectedResult.keyActions.root.focusParent.keyCombinations[0].keyCode).toEqual(keyboardKey.ArrowLeft); }); }); });
9,883
0
petrpan-code/microsoft/fluentui/packages/fluentui/perf-test-northstar
petrpan-code/microsoft/fluentui/packages/fluentui/perf-test-northstar/tasks/perf-test.ts
import fs from 'fs'; import path from 'path'; import _ from 'lodash'; import flamegrill, { CookResult, CookResults, ScenarioConfig, Scenarios } from 'flamegrill'; import { generateUrl } from '@fluentui/digest'; import { perfTestEnv, PerfRegressionConfig } from '@fluentui/scripts-tasks'; import { getFluentPerfRegressions } from './fluentPerfRegressions'; type ExtendedCookResult = CookResult & { extended: { kind: string; story: string; iterations: number; tpi?: number; filename?: number; }; }; type ExtendedCookResults = Record<string, ExtendedCookResult>; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: // // As much of this file should be absorbed into flamegrill as possible. // Flamegrill knows all possible kinds and stories from digest. Could default to running tests against all. // Embed iterations in stories as well as scenarios. That way they would apply for static tests as well. // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: We can't do CI, measure baseline or do regression analysis until master & PR files are deployed and publicly accessible. // TODO: Fluent reporting is outside of this script so this code will probably be moved entirely on perf-test consolidation. const urlForDeployPath = `file://${path.resolve(__dirname, '../dist/')}`; const urlForDeploy = `${urlForDeployPath}/index.html`; const defaultIterations = 1; console.log(`__dirname: ${__dirname}`); export async function getPerfRegressions(config: PerfRegressionConfig, baselineOnly = false) { const { outDir, tempDir, scenariosSrcDirPath, projectName, projectRootPath } = config; const projectRootDirectoryName = path.basename(projectRootPath); const projectEnvVars = perfTestEnv.EnvVariablesByProject[projectName]; const targetPath = `heads/${perfTestEnv.SYSTEM_PULLREQUEST_TARGETBRANCH || 'master'}`; const urlForMaster = baselineOnly ? undefined : `https://${perfTestEnv.DEPLOYHOST}/${targetPath}/${projectRootDirectoryName}/index.html`; // For debugging, in case the environment variables used to generate these have unexpected values console.log(`urlForDeployPath: "${urlForDeployPath}"`); console.log(`urlForMaster: "${urlForMaster}"`); // TODO: support iteration/kind/story via commandline as in other perf-test script // TODO: can do this now that we have story information // TODO: align flamegrill terminology with CSF (story vs. scenario) const scenarios: Scenarios = {}; const scenarioList: string[] = []; // TODO: can this get typing somehow? can't be imported since file is only available after build const test = require(scenariosSrcDirPath); const { stories } = test.default; console.log('stories:'); console.dir(stories, { depth: null }); Object.keys(stories).forEach(kindKey => { Object.keys(stories[kindKey]) .filter(storyKey => typeof stories[kindKey][storyKey] === 'function') .forEach(storyKey => { const scenarioName = `${kindKey}.${storyKey}`; scenarioList.push(scenarioName); scenarios[scenarioName] = { scenario: generateUrl(urlForDeploy, kindKey, storyKey, getIterations(stories, kindKey, storyKey)), ...(!baselineOnly && storyKey !== 'Fabric' && { // Optimization: skip baseline comparison for Fabric baseline: generateUrl( urlForMaster as string, kindKey, storyKey, getIterations(stories, kindKey, storyKey), ), }), }; }); }); console.log(`\nRunning scenarios: ${scenarioList}\n`); if (!fs.existsSync(tempDir)) { console.log(`Making temp directory ${tempDir}...`); fs.mkdirSync(tempDir); } const tempContents = fs.readdirSync(tempDir); if (tempContents.length > 0) { console.log(`Unexpected files already present in ${tempDir}`); tempContents.forEach(logFile => { const logFilePath = path.join(tempDir, logFile); console.log(`Deleting ${logFilePath}`); fs.unlinkSync(logFilePath); }); } const scenarioConfig: ScenarioConfig = { outDir, tempDir, pageActions: async (page, options) => { // Occasionally during our CI, page takes unexpected amount of time to navigate (unsure about the root cause). // Removing the timeout to avoid perf-test failures but be cautious about long test runs. page.setDefaultTimeout(0); await page.goto(options.url); }, }; const scenarioResults = await flamegrill.cook(scenarios, scenarioConfig); const extendedCookResults = extendCookResults(stories, scenarioResults); fs.writeFileSync(path.join(outDir, 'perfCounts.json'), JSON.stringify(extendedCookResults, null, 2)); const comment = createReport(stories, extendedCookResults); // TODO: determine status according to perf numbers const status = 'success'; console.log(`Perf evaluation status: ${status}`); // Write results to file fs.writeFileSync(path.join(outDir, 'perfCounts.html'), comment); console.log(`##vso[task.setvariable variable=${projectEnvVars.filePath};]${projectRootPath}/dist/perfCounts.html`); console.log(`##vso[task.setvariable variable=${projectEnvVars.status};]${status}`); } function extendCookResults( stories: { [x: string]: { [x: string]: any } }, testResults: CookResults, ): ExtendedCookResults { return _.mapValues(testResults, (testResult, resultKey) => { const kind = getKindKey(resultKey); const story = getStoryKey(resultKey); const iterations = getIterations(stories, kind, story); const tpi = getTpiResult(testResults, stories, kind, story); // || 'n/a' return { ...testResult, extended: { kind, story, iterations, tpi, filename: stories[kind][story].filename, }, }; }); } /** * Create test summary based on test results. * * @param {CookResults} testResults * @returns {string} */ function createReport(stories: any, testResults: ExtendedCookResults): string { // TODO: We can't do CI, measure baseline or do regression analysis until master & PR files are deployed and publicly accessible. // TODO: Fluent reporting is outside of this script so this code will probably be moved entirely on perf-test consolidation. // // Show only significant changes by default. // .concat(createScenarioTable(testResults, false)) // // Show all results in a collapsible table. // .concat('<details><summary>All results</summary><p>') // .concat(createScenarioTable(testResults, true)) // .concat('</p></details>'); return getFluentPerfRegressions(); } /** * Create a table of scenario results. * * @param {CookResults} testResults * @param {boolean} showAll Show only significant results by default. * @returns {string} */ function createScenarioTable(stories: any, testResults: ExtendedCookResults, showAll: boolean): string { const resultsToDisplay = Object.keys(testResults) .filter(key => showAll || testResults[key]?.analysis?.regression?.isRegression) .filter(testResultKey => getStoryKey(testResultKey) !== 'Fabric') .sort(); if (resultsToDisplay.length === 0) { return '<p>No significant results to display.</p>'; } // TODO: We can't do CI, measure baseline or do regression analysis until master & PR files are deployed and publicly accessible. // TODO: Fluent reporting is outside of this script so this code will probably be moved entirely on perf-test consolidation. // const result = ` // <table> // <tr> // <th>Scenario</th> // <th> // <a href="https://github.com/microsoft/fluentui/wiki/Perf-Testing#why-are-results-listed-in-ticks-instead-of-time-units">Master Ticks</a> // </th> // <th> // <a href="https://github.com/microsoft/fluentui/wiki/Perf-Testing#why-are-results-listed-in-ticks-instead-of-time-units">PR Ticks</a> // </th> // <th>Status</th> // </tr>`.concat( // resultsToDisplay // .map(key => { // const testResult = testResults[key]; // return `<tr> // <td>${scenarioNames[key] || key}</td> // ${getCell(testResult, true)} // ${getCell(testResult, false)} // ${getRegression(testResult)} // </tr>`; // }) // .join('\n') // .concat(`</table>`), // ); // TODO: add iterations column (and maybe ticks per iteration) const result = ` <table> <tr> <th>Kind</th> <th>Story</th> <th>TPI</th> <th>Iterations</th> <th> <a href="https://github.com/microsoft/fluentui/wiki/Perf-Testing#why-are-results-listed-in-ticks-instead-of-time-units">PR Ticks</a> </th> </tr>`.concat( resultsToDisplay .map(resultKey => { const testResult = testResults[resultKey]; const tpi = testResult.extended.tpi ? linkifyResult( testResult, testResult.extended.tpi.toLocaleString('en', { maximumSignificantDigits: 2 }), false, ) : 'n/a'; return `<tr> <td>${testResult.extended.kind}</td> <td>${testResult.extended.story}</td> <td>${tpi}</td> <td>${testResult.extended.iterations}</td> <td>${getTicksResult(testResult, false)}</td> </tr>`; }) .join('\n') .concat(`</table>`), ); return result; } function getKindKey(resultKey: string): string { const [kind] = resultKey.split('.'); return kind; } function getStoryKey(resultKey: string): string { const [, story] = resultKey.split('.'); return story; } function getTpiResult( testResults: CookResults, stories: { [x: string]: { [x: string]: any } }, kind: string, story: string, ): number | undefined { let tpi: number | undefined; if (stories[kind][story]) { const resultKey = `${kind}.${story}`; const testResult = testResults[resultKey]; const ticks = getTicks(testResult); const iterations = getIterations(stories, kind, story); tpi = ticks && iterations && Math.round((ticks / iterations) * 100) / 100; } return tpi; } function getIterations( stories: { [x: string]: Partial<{ default: { iterations?: number }; [x: string]: { iterations?: number }; }>; }, kind: string, story: string, ): number { // Give highest priority to most localized definition of iterations. Story => kind => default. return stories[kind][story]?.iterations || stories[kind].default?.iterations || defaultIterations; } function getTicks(testResult: CookResult): number | undefined { return testResult.analysis && testResult.analysis.numTicks; } function linkifyResult(testResult: CookResult, resultContent: string | number | undefined, getBaseline: boolean) { let flamegraphFile = testResult.processed.output && testResult.processed.output.flamegraphFile; let errorFile = testResult.processed.error && testResult.processed.error.errorFile; if (getBaseline) { const processedBaseline = testResult.processed.baseline; flamegraphFile = processedBaseline && processedBaseline.output && processedBaseline.output.flamegraphFile; errorFile = processedBaseline && processedBaseline.error && processedBaseline.error.errorFile; } const cell = errorFile ? `<a href="${path.basename(errorFile)}">err</a>` : flamegraphFile ? `<a href="${path.basename(flamegraphFile)}">${resultContent}</a>` : `n/a`; return cell; } /** * Helper that renders an output cell based on a test result. * * @param {CookResult} testResult * @param {boolean} getBaseline * @returns {string} */ function getTicksResult(testResult: CookResult, getBaseline: boolean): string { let numTicks = testResult.analysis && testResult.analysis.numTicks; if (getBaseline) { numTicks = testResult.analysis && testResult.analysis.baseline && testResult.analysis.baseline.numTicks; } return linkifyResult(testResult, numTicks, getBaseline); } /** * Helper that renders an output cell based on a test result. * * @param {CookResult} testResult * @returns {string} */ // TODO: We can't do CI, measure baseline or do regression analysis until master & PR files are deployed and publicly accessible. // TODO: Fluent reporting is outside of this script so this code will probably be moved entirely on perf-test consolidation. // function getRegression(testResult: CookResult): string { // const cell = testResult.analysis && testResult.analysis.regression && testResult.analysis.regression.isRegression // ? testResult.analysis.regression.regressionFile // ? `<a href="${urlForDeployPath}/${path.basename(testResult.analysis.regression.regressionFile)}">Possible regression</a>` // : '' // : ''; // return `<td>${cell}</td>`; // }
9,905
0
petrpan-code/microsoft/fluentui/packages/fluentui
petrpan-code/microsoft/fluentui/packages/fluentui/projects-test/tsconfig.json
{ "extends": "../../../tsconfig.base.v0.json", "compilerOptions": { "allowSyntheticDefaultImports": true, "module": "esnext", "types": ["node"], "outDir": "dist/dts", "emitDeclarationOnly": false, "composite": true }, "include": ["src"], "references": [ { "path": "../react-northstar" } ] }
9,992
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/FocusZone/AutoFocusZone-test.tsx
import { FocusZone, AutoFocusZone } from '@fluentui/react-bindings'; import * as React from 'react'; import * as ReactTestUtils from 'react-dom/test-utils'; const animationFrame = () => new Promise(resolve => window.requestAnimationFrame(resolve)); const originalRAF = window.requestAnimationFrame; describe('AutoFocusZone', () => { let lastFocusedElement: HTMLElement | undefined; const _onFocus = (ev: any): void => (lastFocusedElement = ev.target); const setupElement = ( element: HTMLElement, { clientRect, isVisible = true, }: { clientRect: { top: number; left: number; bottom: number; right: number; }; isVisible?: boolean; }, ): void => { // @ts-ignore element.getBoundingClientRect = () => ({ top: clientRect.top, left: clientRect.left, bottom: clientRect.bottom, right: clientRect.right, width: clientRect.right - clientRect.left, height: clientRect.bottom - clientRect.top, }); element.setAttribute('data-is-visible', String(isVisible)); element.focus = () => ReactTestUtils.Simulate.focus(element); }; beforeEach(() => { jest.useFakeTimers(); Object.defineProperty(window, 'requestAnimationFrame', { writable: true, value: (callback: FrameRequestCallback) => callback(0), }); lastFocusedElement = undefined; }); afterEach(() => { jest.useRealTimers(); window.requestAnimationFrame = originalRAF; }); describe('Focusing the ATZ', () => { function setupTest(firstFocusableSelector?: string) { let autoFocusZoneRef: AutoFocusZone | null = null; const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <AutoFocusZone data-is-focusable={true} firstFocusableSelector={firstFocusableSelector} ref={ftz => { autoFocusZoneRef = ftz; }} > <button className={'f'}>f</button> <FocusZone> <button className={'a'}>a</button> <button className={'b'}>b</button> </FocusZone> </AutoFocusZone> <button className={'z'}>z</button> </div>, ) as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonZ = topLevelDiv.querySelector('.z') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonF, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonZ, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); return { autoFocusZone: autoFocusZoneRef, buttonF, buttonA, buttonB, buttonZ }; } it('goes to first focusable element when focusing the ATZ', async () => { expect.assertions(1); const { autoFocusZone, buttonF } = setupTest(); // By calling `componentDidMount`, AFZ will behave as just initialized and focus needed element // Focus within should go to 1st focusable inner element. // @ts-ignore autoFocusZone.componentDidMount(); await animationFrame(); expect(lastFocusedElement).toBe(buttonF); }); it('goes to the element with containing the firstFocusableSelector if provided when focusing the ATZ', async () => { expect.assertions(1); const { autoFocusZone, buttonB } = setupTest('.b'); // By calling `componentDidMount`, AFZ will behave as just initialized and focus needed element // Focus within should go to the element containing the selector. // @ts-ignore autoFocusZone.componentDidMount(); await animationFrame(); expect(lastFocusedElement).toBe(buttonB); }); }); });
9,993
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/FocusZone/FocusTrapZone-test.tsx
import { FocusZoneDirection, keyboardKey } from '@fluentui/accessibility'; import { FocusTrapZone, FocusZone, FocusTrapZoneProps } from '@fluentui/react-bindings'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as ReactTestUtils from 'react-dom/test-utils'; import { createTestContainer } from './test-utils'; import * as FocusUtilities from '../../src/FocusZone/focusUtilities'; const originalRAF = window.requestAnimationFrame; class FocusTrapZoneTestComponent extends React.Component< {}, { isShowingFirst: boolean; isShowingSecond: boolean; } > { constructor(props: {}) { super(props); this.state = { isShowingFirst: false, isShowingSecond: false }; } render() { return ( <div> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus isClickableOutsideFocusTrap={false}> <button className={'a'} onClick={this._toggleFirst}> a </button> <button className={'b'} onClick={this._toggleSecond}> b </button> </FocusTrapZone> {this.state.isShowingFirst && ( <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} isClickableOutsideFocusTrap={false}> <FocusZone data-is-visible={true}>First</FocusZone> </FocusTrapZone> )} {this.state.isShowingSecond && ( <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} isClickableOutsideFocusTrap={true}> <FocusZone data-is-visible={true}>First</FocusZone> </FocusTrapZone> )} </div> ); } _toggleFirst = () => this.setState({ isShowingFirst: !this.state.isShowingFirst }); _toggleSecond = () => this.setState({ isShowingSecond: !this.state.isShowingSecond }); } describe('FocusTrapZone', () => { // document.activeElement can be used to detect activeElement after component mount, but it does not // update based on focus events due to limitations of ReactDOM. Use lastFocusedElement to detect focus // change events. let lastFocusedElement: HTMLElement | undefined; const ftzClassname = 'ftzTestClassname'; function _onFocus(ev: any): void { lastFocusedElement = ev.target; } function setupElement( element: HTMLElement, { clientRect, isVisible = true, }: { clientRect: { top: number; left: number; bottom: number; right: number; }; isVisible?: boolean; }, ): void { ReactTestUtils.act(() => { element.getBoundingClientRect = () => ({ top: clientRect.top, left: clientRect.left, bottom: clientRect.bottom, right: clientRect.right, width: clientRect.right - clientRect.left, height: clientRect.bottom - clientRect.top, } as DOMRect); element.setAttribute('data-is-visible', String(isVisible)); element.focus = () => ReactTestUtils.Simulate.focus(element); }); } /** * Helper to get FocusTrapZone bumpers. Requires classname attribute of * 'ftzClassname' on FTZ. */ function getFtzBumpers(element: HTMLElement): { firstBumper: Element; lastBumper: Element; } { const ftz = element.querySelector(`.${ftzClassname}`) as HTMLElement; const ftzNodes = ftz.children; const firstBumper = ftzNodes[0]; const lastBumper = ftzNodes[ftzNodes.length - 1]; return { firstBumper, lastBumper }; } beforeEach(() => { jest.useFakeTimers(); Object.defineProperty(window, 'requestAnimationFrame', { writable: true, value: (callback: FrameRequestCallback) => callback(0), }); lastFocusedElement = undefined; }); afterAll(() => { window.addEventListener = addEventListener; window.requestAnimationFrame = originalRAF; jest.useRealTimers(); }); describe('Tab and shift-tab wrap at extreme ends of the FTZ', () => { it('can tab across FocusZones with different button structures', async () => { expect.assertions(3); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} className={ftzClassname}> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <div data-is-visible={true}> <button className="a">a</button> </div> <div data-is-visible={true}> <button className="b">b</button> </div> <div data-is-visible={true}> <button className="c">c</button> </div> </FocusZone> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <div data-is-visible={true}> <div data-is-visible={true}> <button className="d">d</button> <button className="e">e</button> <button className="f">f</button> </div> </div> </FocusZone> </FocusTrapZone> </div>, ) as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonD = topLevelDiv.querySelector('.d') as HTMLElement; const buttonE = topLevelDiv.querySelector('.e') as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 30 } }); setupElement(buttonB, { clientRect: { top: 0, bottom: 30, left: 30, right: 60 } }); setupElement(buttonC, { clientRect: { top: 0, bottom: 30, left: 60, right: 90 } }); setupElement(buttonD, { clientRect: { top: 30, bottom: 60, left: 0, right: 30 } }); setupElement(buttonE, { clientRect: { top: 30, bottom: 60, left: 30, right: 60 } }); setupElement(buttonF, { clientRect: { top: 30, bottom: 60, left: 60, right: 90 } }); const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonD); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonA); }); it('can tab across a FocusZone with different button structures', async () => { expect.assertions(3); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} className={ftzClassname}> <div data-is-visible={true}> <button className="x">x</button> </div> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <div data-is-visible={true}> <button className="a">a</button> </div> <div data-is-visible={true}> <div data-is-visible={true}> <button className="b">b</button> <button className="c">c</button> <button className="d">d</button> </div> </div> </FocusZone> </FocusTrapZone> </div>, ) as HTMLElement; const buttonX = topLevelDiv.querySelector('.x') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonD = topLevelDiv.querySelector('.d') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Assign bounding locations to buttons. setupElement(buttonX, { clientRect: { top: 0, bottom: 30, left: 0, right: 30 } }); setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 30 } }); setupElement(buttonB, { clientRect: { top: 0, bottom: 30, left: 30, right: 60 } }); setupElement(buttonC, { clientRect: { top: 0, bottom: 30, left: 60, right: 90 } }); setupElement(buttonD, { clientRect: { top: 30, bottom: 60, left: 0, right: 30 } }); ReactTestUtils.Simulate.focus(buttonX); expect(lastFocusedElement).toBe(buttonX); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonA); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonX); }); it('can trap focus when FTZ bookmark elements are FocusZones, and those elements have inner elements focused that are not the first inner element', async () => { expect.assertions(4); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} className={ftzClassname}> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <button className={'a'}>a</button> <button className={'b'}>b</button> <button className={'c'}>c</button> </FocusZone> <button className={'d'}>d</button> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <button className={'e'}>e</button> <button className={'f'}>f</button> <button className={'g'}>g</button> </FocusZone> </FocusTrapZone> <button className={'z2'}>z2</button> </div>, ) as HTMLElement; const buttonZ1 = topLevelDiv.querySelector('.z1') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonD = topLevelDiv.querySelector('.d') as HTMLElement; const buttonE = topLevelDiv.querySelector('.e') as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; const buttonG = topLevelDiv.querySelector('.g') as HTMLElement; const buttonZ2 = topLevelDiv.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 30, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 10, bottom: 30, left: 10, right: 20 } }); setupElement(buttonC, { clientRect: { top: 10, bottom: 30, left: 20, right: 30 } }); setupElement(buttonD, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonE, { clientRect: { top: 40, bottom: 60, left: 0, right: 10 } }); setupElement(buttonF, { clientRect: { top: 40, bottom: 60, left: 10, right: 20 } }); setupElement(buttonG, { clientRect: { top: 40, bottom: 60, left: 20, right: 30 } }); setupElement(buttonZ2, { clientRect: { top: 60, bottom: 70, left: 0, right: 10 } }); // Focus the middle button in the first FZ. ReactTestUtils.Simulate.focus(buttonA); ReactTestUtils.Simulate.keyDown(buttonA, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Focus the middle button in the second FZ. ReactTestUtils.Simulate.focus(buttonE); ReactTestUtils.Simulate.keyDown(buttonE, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonF); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonB); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonF); }); }); describe('Tab and shift-tab do nothing (keep focus where it is) when the FTZ contains 0 tabbable items', () => { function setupTest(props: FocusTrapZoneProps) { const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone className={ftzClassname} forceFocusInsideTrapOnOutsideFocus={true} {...props}> <button className={'a'} tabIndex={-1}> a </button> <button className={'b'} tabIndex={-1}> b </button> <button className={'c'} tabIndex={-1}> c </button> </FocusTrapZone> <button className={'z2'}>z2</button> </div>, ) as HTMLElement; const buttonZ1 = topLevelDiv.querySelector('.z1') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonZ2 = topLevelDiv.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Have to set bumpers as "visible" for focus utilities to find them. // This is needed for 0 tabbable element tests to make sure that next tabbable element // from one bumper is the other bumper. firstBumper.setAttribute('data-is-visible', String(true)); lastBumper.setAttribute('data-is-visible', String(true)); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonC, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonZ2, { clientRect: { top: 40, bottom: 50, left: 0, right: 10 } }); return { buttonZ1, buttonA, buttonB, buttonC, buttonZ2, firstBumper, lastBumper }; } it('focuses first focusable element when focusing first bumper', async () => { expect.assertions(2); const { buttonB, buttonA, firstBumper } = setupTest({}); ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonA); }); it('focuses first focusable element when focusing last bumper', async () => { expect.assertions(2); const { buttonA, buttonB, lastBumper } = setupTest({}); ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonA); }); }); describe('Focus behavior based on default and explicit prop values', () => { function setupTest(props: FocusTrapZoneProps) { // data-is-visible is embedded in buttons here for testing focus behavior on initial render. // Components have to be marked visible before setupElement has a chance to apply the data-is-visible attribute. // const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( const { testContainer, removeTestContainer } = createTestContainer(); ReactTestUtils.act(() => { ReactDOM.render( <div> <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone data-is-visible={true} {...props} className={ftzClassname}> <button className={'a'} data-is-visible={true}> a </button> <button className={'b'} data-is-visible={true}> b </button> <button className={'c'} data-is-visible={true}> c </button> </FocusTrapZone> <button className={'z2'}>z2</button> </div> </div>, testContainer, ); }); // const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( // <div> // <div onFocusCapture={_onFocus}> // <button className={'z1'}>z1</button> // <FocusTrapZone data-is-visible={true} {...props} className={ftzClassname}> // <button className={'a'} data-is-visible={true}> // a // </button> // <button className={'b'} data-is-visible={true}> // b // </button> // <button className={'c'} data-is-visible={true}> // c // </button> // </FocusTrapZone> // <button className={'z2'}>z2</button> // </div> // </div>, // ) as HTMLElement; const buttonZ1 = testContainer.querySelector('.z1') as HTMLElement; const buttonA = testContainer.querySelector('.a') as HTMLElement; const buttonB = testContainer.querySelector('.b') as HTMLElement; const buttonC = testContainer.querySelector('.c') as HTMLElement; const buttonZ2 = testContainer.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(testContainer); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonC, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonZ2, { clientRect: { top: 40, bottom: 50, left: 0, right: 10 } }); return { buttonZ1, buttonA, buttonB, buttonC, buttonZ2, firstBumper, lastBumper, removeTestContainer }; } function setupTestOld(props: FocusTrapZoneProps) { const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div> <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone data-is-visible={true} {...props} className={ftzClassname}> <button className={'a'} data-is-visible={true}> a </button> <button className={'b'} data-is-visible={true}> b </button> <button className={'c'} data-is-visible={true}> c </button> </FocusTrapZone> <button className={'z2'}>z2</button> </div> </div>, ) as HTMLElement; const buttonZ1 = topLevelDiv.querySelector('.z1') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonZ2 = topLevelDiv.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonC, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonZ2, { clientRect: { top: 40, bottom: 50, left: 0, right: 10 } }); return { buttonZ1, buttonA, buttonB, buttonC, buttonZ2, firstBumper, lastBumper }; } it('Focuses first element when FTZ does not have focus and first bumper receives focus', async () => { expect.assertions(2); const { buttonA, buttonZ1, firstBumper } = setupTestOld({ isClickableOutsideFocusTrap: true }); ReactTestUtils.Simulate.focus(buttonZ1); expect(lastFocusedElement).toBe(buttonZ1); ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonA); }); it('Focuses last element when FTZ does not have focus and last bumper receives focus', async () => { expect.assertions(2); const { buttonC, buttonZ2, lastBumper } = setupTestOld({ isClickableOutsideFocusTrap: true }); ReactTestUtils.Simulate.focus(buttonZ2); expect(lastFocusedElement).toBe(buttonZ2); ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonC); }); it('Focuses first on mount', async () => { expect.assertions(1); const { removeTestContainer, buttonA } = setupTest({}); expect(document.activeElement).toBe(buttonA); removeTestContainer(); }); it('Does not focus first on mount with disableFirstFocus', async () => { expect.assertions(1); const activeElement = document.activeElement; const { removeTestContainer } = setupTest({ disableFirstFocus: true }); // document.activeElement can be used to detect activeElement after component mount, but it does not // update based on focus events due to limitations of ReactDOM. // Make sure activeElement didn't change. expect(document.activeElement).toBe(activeElement); removeTestContainer(); }); it('Does not focus first on mount while disabled', async () => { expect.assertions(1); const activeElement = document.activeElement; const { removeTestContainer } = setupTest({ disabled: true }); // document.activeElement can be used to detect activeElement after component mount, but it does not // update based on focus events due to limitations of ReactDOM. // Make sure activeElement didn't change. expect(document.activeElement).toBe(activeElement); removeTestContainer(); }); it('Focuses on firstFocusableSelector on mount', async () => { expect.assertions(1); const { removeTestContainer, buttonC } = setupTest({ firstFocusableSelector: '.c' }); expect(document.activeElement).toBe(buttonC); removeTestContainer(); }); it('Does not focus on firstFocusableSelector on mount while disabled', async () => { expect.assertions(1); const activeElement = document.activeElement; const { removeTestContainer } = setupTest({ firstFocusableSelector: '.c', disabled: true }); expect(document.activeElement).toBe(activeElement); removeTestContainer(); }); it('Falls back to first focusable element with invalid firstFocusableSelector', async () => { const { buttonA, removeTestContainer } = setupTest({ firstFocusableSelector: '.invalidSelector' }); expect(document.activeElement).toBe(buttonA); removeTestContainer(); }); }); describe('Focusing the FTZ', () => { function setupTest(focusPreviouslyFocusedInnerElement: boolean) { let focusTrapZoneRef: FocusTrapZone | null = null; const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} focusPreviouslyFocusedInnerElement={focusPreviouslyFocusedInnerElement} data-is-focusable={true} ref={ftz => { focusTrapZoneRef = ftz; }} > <button className={'f'}>f</button> <FocusZone> <button className={'a'}>a</button> <button className={'b'}>b</button> </FocusZone> </FocusTrapZone> <button className={'z'}>z</button> </div>, ) as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonZ = topLevelDiv.querySelector('.z') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonF, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonZ, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); return { focusTrapZone: focusTrapZoneRef, buttonF, buttonA, buttonB, buttonZ }; } it('goes to previously focused element when focusing the FTZ', async () => { expect.assertions(4); const { focusTrapZone, buttonF, buttonB, buttonZ } = setupTest(true /* focusPreviouslyFocusedInnerElement */); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonF); // Focus inside the trap zone, not the first element. ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Focus outside the trap zone ReactTestUtils.Simulate.focus(buttonZ); expect(lastFocusedElement).toBe(buttonZ); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // FTZ should return to originally focused inner element. // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonB); }); it('goes to first focusable element when focusing the FTZ', async () => { expect.assertions(4); const { focusTrapZone, buttonF, buttonB, buttonZ } = setupTest(false /* focusPreviouslyFocusedInnerElement */); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // Focus within should go to 1st focusable inner element. // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonF); // Focus inside the trap zone, not the first element. ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Focus outside the trap zone ReactTestUtils.Simulate.focus(buttonZ); expect(lastFocusedElement).toBe(buttonZ); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // Focus should go to the first focusable element // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonF); }); }); describe('Nested FocusTrapZones Stack Behavior', () => { const getFocusStack = (): FocusTrapZone[] => (FocusTrapZone as any)._focusStack; // beforeAll(() => (getFocusStack().length = 0)); beforeAll(() => { FocusTrapZone._focusStack = []; }); it.skip('FocusTrapZone maintains a proper stack of FocusTrapZones as more are mounted/unmounted.', async () => { const { removeTestContainer, testContainer } = createTestContainer(); // let focusTrapZoneFocusStack: FocusTrapZone[] = getFocusStack(); // const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( ReactTestUtils.act(() => { ReactDOM.render( <div> <FocusTrapZoneTestComponent /> </div>, testContainer, ) /* as HTMLElement */; }); const topLevelDiv = testContainer; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; expect(FocusTrapZone._focusStack.length).toBe(2); const baseFocusTrapZone = FocusTrapZone._focusStack[0]; expect(baseFocusTrapZone.props.forceFocusInsideTrapOnOutsideFocus).toBe(true); expect(baseFocusTrapZone.props.isClickableOutsideFocusTrap).toBe(false); const firstFocusTrapZone = FocusTrapZone._focusStack[1]; expect(firstFocusTrapZone.props.forceFocusInsideTrapOnOutsideFocus).toBe(false); expect(firstFocusTrapZone.props.isClickableOutsideFocusTrap).toBe(false); // There should be now 3 focus trap zones (base/first/second) ReactTestUtils.Simulate.click(buttonB); expect(FocusTrapZone._focusStack.length).toBe(3); expect(FocusTrapZone._focusStack[0]).toBe(baseFocusTrapZone); expect(FocusTrapZone._focusStack[1]).toBe(firstFocusTrapZone); const secondFocusTrapZone = FocusTrapZone._focusStack[2]; expect(secondFocusTrapZone.props.forceFocusInsideTrapOnOutsideFocus).toBe(false); expect(secondFocusTrapZone.props.isClickableOutsideFocusTrap).toBe(true); // we remove the middle one // unmounting a focus trap zone should remove it from the focus stack. // but we also check that it removes the right focustrapzone (the middle one) ReactTestUtils.Simulate.click(buttonA); FocusTrapZone._focusStack = getFocusStack(); expect(FocusTrapZone._focusStack.length).toBe(2); expect(FocusTrapZone._focusStack[0]).toBe(baseFocusTrapZone); expect(FocusTrapZone._focusStack[1]).toBe(secondFocusTrapZone); ReactTestUtils.act(() => { // finally remove the last focus trap zone. ReactTestUtils.Simulate.click(buttonB); FocusTrapZone._focusStack = getFocusStack(); expect(FocusTrapZone._focusStack.length).toBe(1); expect(FocusTrapZone._focusStack[0]).toBe(baseFocusTrapZone); }); removeTestContainer(); }); }); describe('multiple FocusZone mount/unmount', () => { it('remove aria-hidden from the 1st focusZone when the 2nd focusZone unmount', () => { const { testContainer, removeTestContainer } = createTestContainer(); const TestComponent = () => { const [open, setOpen] = React.useState(true); return ( <> {ReactDOM.createPortal( <> {open && ( <FocusTrapZone id="zone2"> <button>zone2 button</button> </FocusTrapZone> )} </>, document.body, )} {ReactDOM.createPortal( <div id="zone1-wrapper"> <FocusTrapZone id="zone1"> <button>zone1 button</button> </FocusTrapZone> </div>, document.body, )} <button id="unmount-zone2-button" onClick={() => setOpen(false)}> button </button> </> ); }; ReactTestUtils.act(() => { ReactDOM.render(<TestComponent />, testContainer); }); // initially both focusZone are mounted let zone1Wrapper = document.body.querySelector('#zone1-wrapper') as HTMLElement; expect(zone1Wrapper).toBeDefined(); expect(zone1Wrapper.getAttribute('aria-hidden')).toBe('true'); const zone2 = document.body.querySelector('#zone2') as HTMLElement; expect(zone2).toBeDefined(); expect(zone2.getAttribute('aria-hidden')).toBe('true'); // unmount zone2 const unmountButton = testContainer.querySelector('#unmount-zone2-button') as HTMLElement; expect(unmountButton).toBeDefined(); ReactTestUtils.Simulate.click(unmountButton); // expect zone1 is mounted, but it's wrapper's aria-hidden attribute is removed zone1Wrapper = document.body.querySelector('#zone1-wrapper') as HTMLElement; expect(zone1Wrapper).toBeDefined(); expect(zone1Wrapper.getAttribute('aria-hidden')).toBeFalsy(); removeTestContainer(); }); }); describe('Restore focus on unmounting FTZ', () => { const TestComponent = ({ ftzProps }: { ftzProps?: FocusTrapZoneProps }) => { const [open, setOpen] = React.useState(true); return ( <> {ReactDOM.createPortal( <> {open && ( <FocusTrapZone id="zone" {...ftzProps}> <button>zone button</button> </FocusTrapZone> )} </>, document.body, )} <button id="unmount-zone-button" onClick={() => setOpen(false)}> button </button> </> ); }; it.each` ftzProps | preventScroll ${undefined} | ${undefined} ${{ preventScrollOnRestoreFocus: true }} | ${true} `('focus on previously focused element after unmounting the FTZ', async ({ ftzProps, preventScroll }) => { const { testContainer, removeTestContainer } = createTestContainer(); const focusAsyncSpy = jest.spyOn(FocusUtilities, 'focusAsync'); ReactTestUtils.act(() => { ReactDOM.render(<TestComponent ftzProps={ftzProps} />, testContainer); }); // initially FTZ is mounted expect(document.body.querySelector('#zone') as HTMLElement).not.toBeNull(); // unmount FTZ const unmountButton = testContainer.querySelector('#unmount-zone-button') as HTMLElement; expect(unmountButton).not.toBeNull(); ReactTestUtils.Simulate.click(unmountButton); // expect zone not is mounted, focus goes to button expect(document.body.querySelector('#zone') as HTMLElement).toBeNull(); expect(focusAsyncSpy).toHaveBeenCalledWith(expect.any(HTMLElement), { preventScroll }); removeTestContainer(); }); }); });
9,994
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/FocusZone/FocusZone-EventHandler-test.tsx
import * as _ from 'lodash'; import * as ReactDOM from 'react-dom'; import * as React from 'react'; import { FocusZone } from '@fluentui/react-bindings'; type EventHandler = { listener: EventListenerOrEventListenerObject; options?: boolean | AddEventListenerOptions; }; function handlersEqual(a: EventHandler, b: EventHandler) { return a.listener === b.listener && _.isEqual(a.options, b.options); } // HEADS UP: this test is intentionally in a separate file aside from the rest of FocusZone tests // As it is testing ref counting on a global `window` object it would interfere with other FocusZone tests // which use ReactTestUtils.renderIntoDocument() which renders FocusZone into a detached DOM node and never unmounts. describe('FocusZone keydown event handler', () => { let host: HTMLElement; let keydownEventHandlers: EventHandler[]; beforeEach(() => { host = document.createElement('div'); keydownEventHandlers = []; window.addEventListener = jest.fn((type, listener, options) => { if (type === 'keydown') { const eventListener = { listener, options }; if (!keydownEventHandlers.some(item => handlersEqual(item, eventListener))) { keydownEventHandlers.push(eventListener); } } }); window.removeEventListener = jest.fn((type, listener, options) => { if (type === 'keydown') { const eventListener = { listener, options }; const index = keydownEventHandlers.findIndex(item => handlersEqual(item, eventListener)); if (index >= 0) { keydownEventHandlers.splice(index, 1); } } }); }); it('is added on mount/removed on unmount', () => { ReactDOM.render(<FocusZone />, host); expect(keydownEventHandlers.length).toBe(1); ReactDOM.unmountComponentAtNode(host); expect(keydownEventHandlers.length).toBe(0); }); it('is added only once for nested focus zones', () => { ReactDOM.render( <div> <FocusZone> <FocusZone /> </FocusZone> </div>, host, ); expect(keydownEventHandlers.length).toBe(1); ReactDOM.unmountComponentAtNode(host); expect(keydownEventHandlers.length).toBe(0); }); it('is added only once for sibling focus zones', () => { ReactDOM.render( <div> <FocusZone /> <FocusZone /> </div>, host, ); expect(keydownEventHandlers.length).toBe(1); ReactDOM.unmountComponentAtNode(host); expect(keydownEventHandlers.length).toBe(0); }); });
9,995
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/FocusZone/FocusZone-test.tsx
import { FocusZoneDirection, FocusZoneTabbableElements, IS_FOCUSABLE_ATTRIBUTE, getCode, keyboardKey, } from '@fluentui/accessibility'; import { FocusZone } from '@fluentui/react-bindings'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as ReactTestUtils from 'react-dom/test-utils'; import { createTestContainer } from './test-utils'; describe('FocusZone', () => { let lastFocusedElement: HTMLElement | undefined; let host: HTMLElement; function onFocus(ev: any): void { lastFocusedElement = ev.target; } function setupElement( element: HTMLElement, { clientRect, isVisible = true, }: { clientRect: { top: number; left: number; bottom: number; right: number; }; isVisible?: boolean; }, ): void { // @ts-ignore element.getBoundingClientRect = () => ({ top: clientRect.top, left: clientRect.left, bottom: clientRect.bottom, right: clientRect.right, width: clientRect.right - clientRect.left, height: clientRect.bottom - clientRect.top, }); element.setAttribute('data-is-visible', String(isVisible)); element.focus = () => ReactTestUtils.Simulate.focus(element); } beforeEach(() => { lastFocusedElement = undefined; }); afterEach(() => { if (host) { ReactDOM.unmountComponentAtNode(host); (host as any) = undefined; } }); it('can use arrows vertically', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.vertical}> <button id="a">a</button> <button id="b">b</button> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 100, }, }); setupElement(buttonB, { clientRect: { top: 30, bottom: 60, left: 0, right: 100, }, }); setupElement(buttonC, { clientRect: { top: 60, bottom: 90, left: 0, right: 100, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing down should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonB); // Pressing down should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); // Pressing down should stay on c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); // Pressing up should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonB); // Pressing up should go to a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonA); // Pressing up should stay on a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonA); // Click on c to focus it. ReactTestUtils.Simulate.focus(buttonC); expect(lastFocusedElement).toBe(buttonC); // Pressing up should move to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonB); // Test that pressing horizontal buttons don't move focus. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonB); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Press home should go to the first target. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Home }); expect(lastFocusedElement).toBe(buttonA); // Press end should go to the last target. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.End }); expect(lastFocusedElement).toBe(buttonC); }); it('can ignore arrowing if default is prevented', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.vertical}> <button id="a">a</button> <button id="b">b</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 100, }, }); setupElement(buttonB, { clientRect: { top: 30, bottom: 60, left: 0, right: 100, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing down should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown, isDefaultPrevented: () => true, } as any); expect(lastFocusedElement).toBe(buttonA); }); it('can use arrows horizontally', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.horizontal}> <button id="a">a</button> <button id="b">b</button> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonA, { clientRect: { top: 0, bottom: 100, left: 0, right: 30, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 100, left: 30, right: 60, }, }); setupElement(buttonC, { clientRect: { top: 0, bottom: 100, left: 60, right: 90, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing right should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Pressing right should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); // Pressing right should stay on c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); // Pressing left should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonB); // Pressing left should go to a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonA); // Pressing left should stay on a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonA); // Click on c to focus it. ReactTestUtils.Simulate.focus(buttonC); expect(lastFocusedElement).toBe(buttonC); // Pressing left should move to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonB); // Test that pressing vertical buttons don't move focus. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonB); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonB); // Press home should go to the first target. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Home }); expect(lastFocusedElement).toBe(buttonA); // // Press end should go to the last target. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.End }); expect(lastFocusedElement).toBe(buttonC); }); it('can use arrows bidirectionally', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone> <button id="a">a</button> <button id="b">b</button> <button id="c">c</button> <button id="hidden">hidden</button> <button id="d">d</button> <button id="e">e</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; const hiddenButton = focusZone.querySelector('#hidden') as HTMLElement; const buttonD = focusZone.querySelector('#d') as HTMLElement; const buttonE = focusZone.querySelector('#e') as HTMLElement; // Set up a grid like so: // A B // C hiddenButton // D E // // We will iterate from A to B, press down to skip hidden and go to C, // down again to E, left to D, then back up to A. setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 30, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonC, { clientRect: { top: 20, bottom: 40, left: 0, right: 20, }, }); // hidden button should be ignored. setupElement(hiddenButton, { clientRect: { top: 20, bottom: 40, left: 2, right: 40, }, isVisible: false, }); setupElement(buttonD, { clientRect: { top: 40, bottom: 60, left: 0, right: 20, }, }); setupElement(buttonE, { clientRect: { top: 40, bottom: 60, left: 20, right: 40, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing right should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Pressing down should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); // Pressing left should go to d. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonD); // Pressing down should go to e. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonE); // Pressing up should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonC); // Pressing up should go to a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonA); }); it('can use arrows bidirectionally by following DOM order', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.bidirectionalDomOrder}> <button id="a">a</button> <button id="b">b</button> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 100, }, }); setupElement(buttonB, { clientRect: { top: 30, bottom: 60, left: 0, right: 100, }, }); setupElement(buttonC, { clientRect: { top: 60, bottom: 90, left: 0, right: 100, }, }); // Pressing down/right arrow keys moves focus to the next focusable item. // Pressing up/left arrow keys moves focus to the previous focusable item. // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing down should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonB); // Pressing right should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); // Pressing down should stay on c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); // Pressing up should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonB); // Pressing left should go to a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonA); // Pressing left should stay on a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonA); // Click on c to focus it. ReactTestUtils.Simulate.focus(buttonC); expect(lastFocusedElement).toBe(buttonC); // Pressing up should move to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonB); // Pressing left should move to a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonA); // Pressing right should move to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Press home should go to the first target. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Home }); expect(lastFocusedElement).toBe(buttonA); // Press end should go to the last target. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.End }); expect(lastFocusedElement).toBe(buttonC); }); it('can reset alignment on mouse down', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone> <button id="a">a</button> <button id="b">b</button> <button id="c">c</button> <button id="d">d</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; const buttonD = focusZone.querySelector('#d') as HTMLElement; // Set up a grid like so: // A B // C D setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonC, { clientRect: { top: 20, bottom: 40, left: 0, right: 20, }, }); setupElement(buttonD, { clientRect: { top: 20, bottom: 40, left: 20, right: 40, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing up should stay on a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonA); // Pressing left should stay on a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonA); // Pressing right should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Pressing down should go to d. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonD); // Mousing down on a should reset alignment to a. ReactTestUtils.Simulate.mouseDown(focusZone, { target: buttonA }); // Pressing down should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); }); it('correctly skips data-not-focusable elements', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone> <button id="a">a</button> <button id="b" data-not-focusable={false}> b </button> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; // Set up a grid like so: // A B // C hiddenButton // D E // // We will iterate from A to B, press down to skip hidden and go to C, // down again to E, left to D, then back up to A. setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonC, { clientRect: { top: 20, bottom: 40, left: 0, right: 20, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing right should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); // Pressing down should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonA); }); it('skips subzone elements until manually entered', () => { const shouldEnterInnerZone = (e: React.KeyboardEvent<HTMLElement>): boolean => getCode(e) === keyboardKey.Enter; const isFocusableProperty = { [IS_FOCUSABLE_ATTRIBUTE]: true }; const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.horizontal} shouldEnterInnerZone={shouldEnterInnerZone}> <button id="a">a</button> <div id="b" data-is-sub-focuszone={true} {...isFocusableProperty}> <button id="bsub">bsub</button> </div> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const divB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; const buttonB = focusZone.querySelector('#bsub') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(divB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonB, { clientRect: { top: 5, bottom: 15, left: 25, right: 35, }, }); setupElement(buttonC, { clientRect: { top: 0, bottom: 20, left: 40, right: 60, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(divB); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(divB); ReactTestUtils.Simulate.keyDown(divB, { which: keyboardKey.Enter }); expect(lastFocusedElement).toBe(buttonB); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(divB); }); it('skips child focusZone elements until manually entered', () => { const shouldEnterInnerZone = (e: React.KeyboardEvent<HTMLElement>): boolean => getCode(e) === keyboardKey.Enter; const isFocusableProperty = { [IS_FOCUSABLE_ATTRIBUTE]: true }; const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.horizontal} shouldEnterInnerZone={shouldEnterInnerZone}> <button id="a">a</button> <FocusZone direction={FocusZoneDirection.horizontal} id="b" {...isFocusableProperty}> <button id="bsub">bsub</button> </FocusZone> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const divB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; const buttonB = focusZone.querySelector('#bsub') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(divB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonB, { clientRect: { top: 5, bottom: 15, left: 25, right: 35, }, }); setupElement(buttonC, { clientRect: { top: 0, bottom: 20, left: 40, right: 60, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(divB); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(divB); ReactTestUtils.Simulate.keyDown(divB, { which: keyboardKey.Enter }); expect(lastFocusedElement).toBe(buttonB); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonC); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(divB); }); it('Focus first tabbable element, when active element is dynamically disabled', () => { let focusZone: FocusZone | null = null; let buttonA: any; let buttonB: any; const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <textarea id="t" /> <FocusZone ref={focus => { focusZone = focus; }} > <button id="a" ref={button => { buttonA = button; }} > a </button> <button id="b" ref={button => { buttonB = button; }} > b </button> </FocusZone> </div>, ); const rootNode = ReactDOM.findDOMNode(component) as Element; const textArea = rootNode.children[0]; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); // ButtonA should be focussed. focusZone!.focus(); expect(lastFocusedElement).toBe(buttonA); buttonA.disabled = true; // Focus the text area, outside focus zone. ReactTestUtils.Simulate.focus(textArea); expect(lastFocusedElement).toBe(textArea); // ButtonB should be focussed. focusZone!.focus(); expect(lastFocusedElement).toBe(buttonB); }); it('removes tab-index of previous element when another one is selected (mouse & keyboard)', () => { let focusZone: FocusZone | null = null; let buttonA: HTMLButtonElement | null = null; let buttonB: HTMLButtonElement | null = null; const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone ref={focus => { focusZone = focus; }} > <button id="a" ref={button => { buttonA = button; }} > a </button> <button id="b" ref={button => { buttonB = button; }} > b </button> </FocusZone> </div>, ); const focusZoneElement = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonAElement = focusZoneElement.querySelector('#a') as HTMLElement; // HACK declare that elements are not null at this point. // Type narrowing doesn't work because TypeScript is not considering the assignments inside `ref` lambdas. focusZone = focusZone!; buttonA = buttonA!; buttonB = buttonB!; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); // ButtonA should be focussed. focusZone.focus(); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); // Pressing right should go to b. ReactTestUtils.Simulate.keyDown(focusZoneElement, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); expect(buttonA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(0); // Clicking on A should enable its tab-index and disable others. // But it doesn't set focus (browser will do it in the default event handler) ReactTestUtils.Simulate.mouseDown(buttonAElement); expect(lastFocusedElement).toBe(buttonB); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); }); it('Changes our focus to the next button when we hit tab when focus zone allow tabbing', () => { const tabDownListener = jest.fn(); const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus, onKeyDown: tabDownListener }}> <FocusZone {...{ handleTabKey: FocusZoneTabbableElements.all, isCircularNavigation: true }}> <button id="a">a</button> <button id="b">b</button> <button id="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; const buttonC = focusZone.querySelector('#c') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonC, { clientRect: { top: 0, bottom: 20, left: 40, right: 60, }, }); // ButtonA should be focussed. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(-1); // Pressing tab will shift focus to button B ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Tab }); expect(lastFocusedElement).toBe(buttonB); expect(buttonA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(0); expect(buttonC.tabIndex).toBe(-1); // Pressing tab will shift focus to button C ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Tab }); expect(lastFocusedElement).toBe(buttonC); expect(buttonA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(0); // Pressing tab on our final element will shift focus back to our first element A ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Tab }); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(-1); // FocusZone stops propagation of our tab when we enable tab handling expect(tabDownListener.mock.calls.length).toBe(0); }); it('detects tab when our focus zone does not allow tabbing', () => { const tabDownListener = jest.fn(); const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus, onKeyDown: tabDownListener }}> <FocusZone> <button id="a">a</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); // ButtonA should be focussed. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); // Pressing tab when our focus zone doesn't allow tabbing will allow us to propagate our tab to our key down event handler ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Tab }); expect(tabDownListener.mock.calls.length).toBe(1); const onKeyDownEvent = tabDownListener.mock.calls[0][0]; expect(getCode(onKeyDownEvent)).toBe(keyboardKey.Tab); }); it('should stay in input box with arrow keys and exit with tab', () => { const tabDownListener = jest.fn(); const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus, onKeyDown: tabDownListener }}> <FocusZone {...{ handleTabKey: FocusZoneTabbableElements.inputOnly, isCircularNavigation: false }}> <input type="text" id="a" /> <button id="b">b</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const inputA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; setupElement(inputA, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); // InputA should be focused. inputA.focus(); expect(lastFocusedElement).toBe(inputA); // When we hit right/left on the arrow key, we don't want to be able to leave focus on an input ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(inputA); expect(inputA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); // Pressing tab will be the only way for us to exit the focus zone ReactTestUtils.Simulate.keyDown(inputA, { which: keyboardKey.Tab }); expect(lastFocusedElement).toBe(buttonB); expect(inputA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(0); }); it('focus should leave input box when arrow keys are pressed when tabbing is supported but shouldInputLoseFocusOnArrowKey callback method return true', () => { const tabDownListener = jest.fn(); const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus, onKeyDown: tabDownListener }}> <FocusZone {...{ handleTabKey: FocusZoneTabbableElements.all, isCircularNavigation: false, shouldInputLoseFocusOnArrowKey: () => { return true; }, }} > <input type="text" id="a" /> <button id="b">b</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const inputA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; setupElement(inputA, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); // InputA should be focused. inputA.focus(); expect(lastFocusedElement).toBe(inputA); // Pressing arrow down, input should loose the focus and the button should get the focus ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonB); expect(inputA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(0); }); it('should force focus to first focusable element when FocusZone container receives focus and shouldFocusInnerElementWhenReceivedFocus is set to "true"', () => { const shouldEnterInnerZone = (e: React.KeyboardEvent<HTMLElement>): boolean => getCode(e) === keyboardKey.Enter; const isFocusableProperty = { [IS_FOCUSABLE_ATTRIBUTE]: true }; const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone direction={FocusZoneDirection.horizontal} shouldEnterInnerZone={shouldEnterInnerZone}> <button id="a">a</button> <FocusZone direction={FocusZoneDirection.horizontal} id="b" shouldFocusInnerElementWhenReceivedFocus={true} {...isFocusableProperty} > <button id="bsub">bsub</button> </FocusZone> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const divB = focusZone.querySelector('#b') as HTMLElement; const buttonB = focusZone.querySelector('#bsub') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(divB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonB, { clientRect: { top: 5, bottom: 15, left: 25, right: 35, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowRight }); // Focus goes to FocusZone container, which forces focus to first focusable element - buttonB expect(lastFocusedElement).toBe(buttonB); }); it('can use arrows bidirectionally in RTL', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone isRtl={true}> <button className="a">a</button> <button className="b">b</button> <button className="c">c</button> <button className="hidden">hidden</button> <button className="d">d</button> <button className="e">e</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('.a') as HTMLElement; const buttonB = focusZone.querySelector('.b') as HTMLElement; const buttonC = focusZone.querySelector('.c') as HTMLElement; const hiddenButton = focusZone.querySelector('.hidden') as HTMLElement; const buttonD = focusZone.querySelector('.d') as HTMLElement; const buttonE = focusZone.querySelector('.e') as HTMLElement; // Set up a grid like so: // B A // hiddenButton C // E D // // We will iterate from A to B, press down to skip hidden and go to C, // down again to E, right to D, up to C, then back up to A. setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 30, right: 0, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 60, right: 30, }, }); setupElement(buttonC, { clientRect: { top: 20, bottom: 40, left: 20, right: 0, }, }); // hidden button should be ignored. setupElement(hiddenButton, { clientRect: { top: 20, bottom: 40, left: 30, right: 20, }, isVisible: false, }); setupElement(buttonD, { clientRect: { top: 40, bottom: 60, left: 25, right: 0, }, }); setupElement(buttonE, { clientRect: { top: 40, bottom: 60, left: 40, right: 25, }, }); // Focus the first button. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Pressing left should go to b. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonB); // Pressing down should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonC); // Pressing right should go to d. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowDown }); expect(lastFocusedElement).toBe(buttonD); // Pressing down should go to e. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowLeft }); expect(lastFocusedElement).toBe(buttonE); // Pressing up should go to c. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonC); // Pressing up should go to a. ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.ArrowUp }); expect(lastFocusedElement).toBe(buttonA); }); it('updates tabindexes when element is focused programaticaly', () => { const tabDownListener = jest.fn(); const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus, onKeyDown: tabDownListener }}> <FocusZone> <button id="a">a</button> <button id="b">b</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); // ButtonA should be focussed. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); // ButtonB should be focussed and tabindex=0 ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); expect(buttonB.tabIndex).toBe(0); expect(buttonA.tabIndex).toBe(-1); }); it('remains focus in element with "contenteditable=true" attribute on Home/End keys', () => { const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone> <div contentEditable={true} id="a" /> <button id="b">b</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const contentEditableA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; setupElement(contentEditableA, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); // contentEditableA should be focused. contentEditableA.focus(); expect(lastFocusedElement).toBe(contentEditableA); ReactTestUtils.Simulate.keyDown(contentEditableA, { which: keyboardKey.Home }); expect(lastFocusedElement).toBe(contentEditableA); ReactTestUtils.Simulate.keyDown(contentEditableA, { which: keyboardKey.End }); expect(lastFocusedElement).toBe(contentEditableA); // change focus to buttonB buttonB.focus(); expect(lastFocusedElement).toBe(buttonB); }); it('should call onKeyDown handler even within another FocusZone', () => { const keyDownHandler = jest.fn(); const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <div {...{ onFocusCapture: onFocus }}> <FocusZone> <FocusZone className="innerFocusZone" onKeyDown={keyDownHandler} data-is-focusable={true}> Inner Focus Zone </FocusZone> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const innerFocusZone = focusZone.querySelector('.innerFocusZone') as HTMLElement; ReactTestUtils.Simulate.keyDown(innerFocusZone, { which: keyboardKey.Enter }); expect(keyDownHandler).toBeCalled(); }); it('can call onActiveItemChanged when the active item is changed', () => { let called = false; const component = ReactTestUtils.renderIntoDocument<{}, React.Component>( <FocusZone onActiveElementChanged={() => (called = true)}> <button key="a" id="a" data-is-visible="true"> button a </button> <button key="b" id="b" data-is-visible="true"> button b </button> </FocusZone>, ); const focusZone = ReactDOM.findDOMNode(component)!.firstChild as Element; const buttonA = focusZone.querySelector('#a') as HTMLElement; const buttonB = focusZone.querySelector('#b') as HTMLElement; ReactTestUtils.Simulate.mouseDown(focusZone, { target: buttonA }); ReactTestUtils.Simulate.focus(focusZone, { target: buttonA }); expect(called).toEqual(true); called = false; ReactTestUtils.Simulate.mouseDown(focusZone, { target: buttonB }); ReactTestUtils.Simulate.focus(focusZone, { target: buttonB }); expect(called).toEqual(true); called = false; }); it('only adds outerzones to be updated for tab changes', () => { const activeZones = FocusZone.outerZones.getOutZone(window)?.size || 0; host = document.createElement('div'); // Render component without button A. ReactDOM.render( <FocusZone> <FocusZone> <button>ok</button> </FocusZone> </FocusZone>, host, ); expect(FocusZone.outerZones.getOutZone(window)?.size).toEqual(activeZones + 1); ReactDOM.unmountComponentAtNode(host); expect(FocusZone.outerZones.getOutZone(window)?.size).toEqual(activeZones); }); describe('restores focus', () => { it('to the following item when item removed', () => { const { testContainer, removeTestContainer } = createTestContainer(); ReactDOM.render( <FocusZone> <button key="a" id="a" data-is-visible="true"> button a </button> <button key="b" id="b" data-is-visible="true"> button b </button> <button key="c" id="c" data-is-visible="true"> button c </button> </FocusZone>, testContainer, ); const buttonB = testContainer.querySelector('#b') as HTMLElement; buttonB.focus(); // Render component without button B. ReactDOM.render( <FocusZone> <button key="a" id="a" data-is-visible="true"> button a </button> <button key="c" id="c" data-is-visible="true"> button c </button> </FocusZone>, testContainer, ); expect(document.activeElement).toBe(testContainer.querySelector('#c')); removeTestContainer(); }); it('can restore focus to the previous item when end item removed', () => { const { testContainer, removeTestContainer } = createTestContainer(); ReactDOM.render( <FocusZone> <button key="a" id="a" data-is-visible="true"> button a </button> <button key="b" id="b" data-is-visible="true"> button b </button> <button key="c" id="c" data-is-visible="true"> button c </button> </FocusZone>, testContainer, ); const buttonC = testContainer.querySelector('#c') as HTMLElement; buttonC.focus(); // Render component without button C. ReactDOM.render( <FocusZone> <button key="a" id="a" data-is-visible="true"> button a </button> <button key="b" id="b" data-is-visible="true"> button b </button> </FocusZone>, testContainer, ); expect(document.activeElement).toBe(testContainer.querySelector('#b')); removeTestContainer(); }); }); describe('parking and unparking', () => { let buttonA: HTMLElement; function setup() { const { testContainer, removeTestContainer } = createTestContainer(); ReactDOM.render( <div> <button key="z" id="z" data-is-visible="true" /> <FocusZone id="fz"> <button key="a" id="a" data-is-visible="true"> button a </button> </FocusZone> </div>, testContainer, ); buttonA = testContainer.querySelector('#a') as HTMLElement; buttonA.focus(); // Render component without button A. ReactDOM.render( <div> <button key="z" id="z" data-is-visible="true" /> <FocusZone id="fz" /> </div>, testContainer, ); return { testContainer, removeTestContainer }; } // beforeEach(() => { // host = document.createElement('div'); // }); it('can move focus to container when last item removed', () => { const { removeTestContainer, testContainer } = setup(); expect(document.activeElement).toBe(testContainer.querySelector('#fz')); removeTestContainer(); }); it('can move focus from container to first item when added', () => { const { removeTestContainer, testContainer } = setup(); ReactDOM.render( <div> <button key="z" id="z" /> <FocusZone id="fz"> <button key="a" id="a" data-is-visible="true"> button a </button> </FocusZone> </div>, testContainer, ); expect(document.activeElement).toBe(testContainer.querySelector('#a')); removeTestContainer(); }); it('removes focusability when moving from focused container', () => { const { removeTestContainer, testContainer } = setup(); expect(testContainer.querySelector('#fz')!.getAttribute('tabindex')).toEqual('-1'); (testContainer.querySelector('#z') as HTMLElement).focus(); expect(testContainer.querySelector('#fz')!.getAttribute('tabindex')).toBeNull(); removeTestContainer(); }); it('does not move focus when items added without container focus', () => { const { removeTestContainer, testContainer } = setup(); expect(testContainer.querySelector('#fz')!.getAttribute('tabindex')).toEqual('-1'); (testContainer.querySelector('#z') as HTMLElement).focus(); ReactDOM.render( <div> <button key="z" id="z" /> <FocusZone id="fz"> <button key="a" id="a" data-is-visible="true"> button a </button> </FocusZone> </div>, testContainer, ); expect(document.activeElement).toBe(testContainer.querySelector('#z')); removeTestContainer(); }); }); it('Handles focus moving to different targets in focus zone following DOM order and allowing tabbing', () => { const tabDownListener = jest.fn(); const component = ReactTestUtils.renderIntoDocument( <div {...{ onFocusCapture: onFocus, onKeyDown: tabDownListener }}> <FocusZone direction={FocusZoneDirection.bidirectionalDomOrder} handleTabKey={FocusZoneTabbableElements.all}> <button className="a">a</button> <button className="b">b</button> <button className="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component as unknown as React.ReactInstance)!.firstChild as Element; const buttonA = focusZone.querySelector('.a') as HTMLElement; const buttonB = focusZone.querySelector('.b') as HTMLElement; const buttonC = focusZone.querySelector('.c') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonC, { clientRect: { top: 0, bottom: 20, left: 40, right: 60, }, }); // ButtonA should be focussed. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(-1); // Pressing tab will shift focus to button B ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Tab }); expect(lastFocusedElement).toBe(buttonB); expect(buttonA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(0); expect(buttonC.tabIndex).toBe(-1); // Pressing tab will shift focus to button C ReactTestUtils.Simulate.keyDown(focusZone, { which: keyboardKey.Tab }); expect(lastFocusedElement).toBe(buttonC); expect(buttonA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(0); // FocusZone stops propagation of our tab when we enable tab handling expect(tabDownListener.mock.calls.length).toBe(0); }); it('Focuses the last element in the FocusZone when the imperative focusLast method is used', () => { const focusZoneRef = React.createRef<FocusZone>(); const component = ReactTestUtils.renderIntoDocument( <div {...{ onFocusCapture: onFocus }}> <FocusZone ref={focusZoneRef} direction={FocusZoneDirection.bidirectionalDomOrder} handleTabKey={FocusZoneTabbableElements.all} > <button className="a">a</button> <button className="b">b</button> <button className="c">c</button> </FocusZone> </div>, ); const focusZone = ReactDOM.findDOMNode(component as unknown as React.ReactInstance)!.firstChild as Element; const buttonA = focusZone.querySelector('.a') as HTMLElement; const buttonB = focusZone.querySelector('.b') as HTMLElement; const buttonC = focusZone.querySelector('.c') as HTMLElement; setupElement(buttonA, { clientRect: { top: 0, bottom: 20, left: 0, right: 20, }, }); setupElement(buttonB, { clientRect: { top: 0, bottom: 20, left: 20, right: 40, }, }); setupElement(buttonC, { clientRect: { top: 0, bottom: 20, left: 40, right: 60, }, }); // ButtonA should be focussed. ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); expect(buttonA.tabIndex).toBe(0); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(-1); // ButtonC should be focused expect(focusZoneRef).not.toBeUndefined(); focusZoneRef.current!.focusLast(); expect(buttonA.tabIndex).toBe(-1); expect(buttonB.tabIndex).toBe(-1); expect(buttonC.tabIndex).toBe(0); }); it('Update tabIndex when FocusZone is changed before focused', () => { const { testContainer, removeTestContainer } = createTestContainer(); // Prepare test component // The test component is a 'Add' button + FocusZone. // Initially there're 2 buttons in FocusZone. Click on the 'Add' button adds a 3rd button in focusZone. // context and memo is used to make sure FocusZone component does not re-render during the process. const ShowButton3Context = React.createContext(false); const Button3 = () => { const showButton3 = React.useContext(ShowButton3Context); return showButton3 ? ( <button className="button-in-zone" id="button-3"> added button 3 </button> ) : null; }; const getDefaultTabbableElement = () => { const buttons = document.body.getElementsByClassName('button-in-zone'); return buttons[buttons.length - 1] as HTMLElement; }; const FocusZoneMemo = React.memo(() => ( <FocusZone shouldResetActiveElementWhenTabFromZone defaultTabbableElement={getDefaultTabbableElement}> <button className="button-in-zone">button 1</button> <button className="button-in-zone">button 2</button> <Button3 /> </FocusZone> )); const TestComponent = () => { const [showButton3, setShowButton3] = React.useState(false); return ( <ShowButton3Context.Provider value={showButton3}> <button id="add-button" onClick={() => setShowButton3(true)}> Add </button> <FocusZoneMemo /> </ShowButton3Context.Provider> ); }; ReactTestUtils.act(() => { ReactDOM.render(<TestComponent />, testContainer); }); // Start test const addButton = document.getElementById('add-button') as HTMLElement; expect(addButton).toBeTruthy(); ReactTestUtils.Simulate.click(addButton); const button3 = document.getElementById('button-3') as HTMLElement; expect(button3).toBeTruthy(); // expect tabIndex is recalculated on keydown, button3 now is the default focusable item in FocusZone // (I used dispatchEvent instead of ReactTestUtils.Simulate.keydown because ReactTestUtils doesn't trigger _onKeyDownCapture in focusZone) addButton.dispatchEvent(new KeyboardEvent('keydown', { which: keyboardKey.Tab } as KeyboardEventInit)); expect(button3.getAttribute('tabindex')).toBe('0'); removeTestContainer(); }); });
9,997
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/accesibility/getKeyDownHandlers-test.ts
import { getKeyDownHandlers } from '../../src/accessibility/getKeyDownHandlers'; import { KeyActions, keyboardKey } from '@fluentui/accessibility'; const testKeyCode = keyboardKey.ArrowRight; const partElementName = 'anchor'; let actionsDefinition: KeyActions; const eventArg = (keyCodeValue: number): any => ({ keyCode: keyCodeValue, altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, }); describe('getKeyDownHandlers', () => { beforeEach(() => { actionsDefinition = { [partElementName]: { testAction: { keyCombinations: [{ keyCode: testKeyCode }], }, }, }; }); describe('should attach onKeyDown handler', () => { test('when there are common actions and actions definition', () => { const actions = { testAction: () => {}, }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); expect(keyHandlers.hasOwnProperty(partElementName)).toBeTruthy(); expect(keyHandlers[partElementName]?.hasOwnProperty('onKeyDown')).toBeTruthy(); }); test('for few component elements', () => { const actions = { testAction: () => {}, someOtherTestAction: () => {}, }; const anotherPartName = 'root'; actionsDefinition[anotherPartName] = { someOtherTestAction: { keyCombinations: [{ keyCode: testKeyCode }], }, }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); expect(keyHandlers.hasOwnProperty(partElementName)).toBeTruthy(); expect(keyHandlers.hasOwnProperty(anotherPartName)).toBeTruthy(); expect(keyHandlers[partElementName]?.hasOwnProperty('onKeyDown')).toBeTruthy(); expect(keyHandlers[anotherPartName]?.hasOwnProperty('onKeyDown')).toBeTruthy(); }); test('when there is 1 common action and few others that are not common', () => { const actions = { uncommonAction: () => {}, testAction: () => {}, }; actionsDefinition[partElementName].doSomething = { keyCombinations: [{ keyCode: testKeyCode }], }; actionsDefinition[partElementName].doSomethingElse = { keyCombinations: [{ keyCode: testKeyCode }], }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); expect(keyHandlers.hasOwnProperty(partElementName)).toBeTruthy(); expect(keyHandlers[partElementName]?.hasOwnProperty('onKeyDown')).toBeTruthy(); }); test('and action should be invoked if keydown event has keycode mapped to that action', () => { const actions = { testAction: jest.fn(), otherAction: jest.fn(), anotherTestAction: jest.fn(), }; actionsDefinition[partElementName].otherAction = { keyCombinations: [{ keyCode: testKeyCode }], }; actionsDefinition[partElementName].anotherTestAction = { keyCombinations: [{ keyCode: 21 }], }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); keyHandlers[partElementName] && // @ts-ignore keyHandlers[partElementName]['onKeyDown'](eventArg(testKeyCode)); expect(actions.testAction).toHaveBeenCalled(); expect(actions.otherAction).toHaveBeenCalled(); expect(actions.anotherTestAction).not.toHaveBeenCalled(); }); test('should ignore actions with no keyCombinations', () => { const actions = { testAction: jest.fn(), actionFalse: jest.fn(), actionNull: jest.fn(), actionEmpty: jest.fn(), }; actionsDefinition[partElementName].actionFalse = { // @ts-ignore keyCombinations: false, }; actionsDefinition[partElementName].actionNull = { // @ts-ignore keyCombinations: null, }; actionsDefinition[partElementName].actionEmpty = { keyCombinations: [], }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); keyHandlers[partElementName] && // @ts-ignore keyHandlers[partElementName]['onKeyDown'](eventArg(testKeyCode)); expect(actions.testAction).toHaveBeenCalled(); expect(actions.actionFalse).not.toHaveBeenCalled(); expect(actions.actionNull).not.toHaveBeenCalled(); expect(actions.actionEmpty).not.toHaveBeenCalled(); }); describe('with respect of RTL', () => { test('swap Right key to Left key', () => { const actions = { actionOnLeftArrow: jest.fn(), actionOnRightArrow: jest.fn(), }; actionsDefinition[partElementName].actionOnLeftArrow = { keyCombinations: [{ keyCode: keyboardKey.ArrowLeft }], }; actionsDefinition[partElementName].actionOnRightArrow = { keyCombinations: [{ keyCode: keyboardKey.ArrowRight }], }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition, /** isRtlEnabled */ true); // @ts-ignore keyHandlers[partElementName]['onKeyDown'](eventArg(keyboardKey.ArrowRight)); expect(actions.actionOnLeftArrow).toHaveBeenCalled(); expect(actions.actionOnRightArrow).not.toHaveBeenCalled(); }); test('swap Left key to Right key', () => { const actions = { actionOnLeftArrow: jest.fn(), actionOnRightArrow: jest.fn(), }; actionsDefinition[partElementName].actionOnLeftArrow = { keyCombinations: [{ keyCode: keyboardKey.ArrowLeft }], }; actionsDefinition[partElementName].actionOnRightArrow = { keyCombinations: [{ keyCode: keyboardKey.ArrowRight }], }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition, /** isRtlEnabled */ true); // @ts-ignore keyHandlers[partElementName]['onKeyDown'](eventArg(keyboardKey.ArrowLeft)); expect(actions.actionOnLeftArrow).not.toHaveBeenCalled(); expect(actions.actionOnRightArrow).toHaveBeenCalled(); }); test('should ignore actions with no keyCombinations', () => { const actions = { actionOnRightArrow: jest.fn(), actionFalse: jest.fn(), actionNull: jest.fn(), actionEmpty: jest.fn(), }; actionsDefinition[partElementName].actionOnRightArrow = { keyCombinations: [{ keyCode: keyboardKey.ArrowRight }], }; actionsDefinition[partElementName].actionFalse = { // @ts-ignore keyCombinations: false, }; actionsDefinition[partElementName].actionNull = { // @ts-ignore keyCombinations: null, }; actionsDefinition[partElementName].actionEmpty = { keyCombinations: [], }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition, true); keyHandlers[partElementName] && // @ts-ignore keyHandlers[partElementName]['onKeyDown'](eventArg(keyboardKey.ArrowLeft)); expect(actions.actionOnRightArrow).toHaveBeenCalled(); expect(actions.actionFalse).not.toHaveBeenCalled(); expect(actions.actionNull).not.toHaveBeenCalled(); expect(actions.actionEmpty).not.toHaveBeenCalled(); }); }); }); describe('should not attach onKeyDown handler', () => { test('when actions are null', () => { const actions = null; // @ts-ignore const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); expect(keyHandlers.hasOwnProperty(partElementName)).toBeFalsy(); }); test("when accessibility's actionsDefinition is null", () => { const actions = { otherAction: () => {} }; // @ts-ignore const keyHandlers = getKeyDownHandlers(actions, null); expect(keyHandlers.hasOwnProperty(partElementName)).toBeFalsy(); }); test('there are not common actions and actions definition', () => { const actions = { otherAction: () => {} }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); expect(keyHandlers.hasOwnProperty(partElementName)).toBeFalsy(); }); test('when action definition has no keyCombinations', () => { const actions = { testAction: () => {}, actionFalse: () => {}, actionNull: () => {}, actionEmpty: () => {}, }; actionsDefinition.anotherPart = { actionFalse: { // @ts-ignore keyCombinations: false, }, actionNull: { // @ts-ignore keyCombinations: null, }, actionEmpty: { keyCombinations: [], }, }; const keyHandlers = getKeyDownHandlers(actions, actionsDefinition); expect(keyHandlers.hasOwnProperty('anotherPart')).toBeFalsy(); }); }); });
9,998
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/accesibility/shouldHandleOnKeys-test.ts
import { shouldHandleOnKeys } from '../../src/accessibility/shouldHandleOnKeys'; const getEventArg = ( keyCode: number, altKey?: boolean, ctrlKey?: boolean, metaKey?: boolean, shiftKey?: boolean, ): any => { return { keyCode, altKey, ctrlKey, metaKey, shiftKey, }; }; describe('shouldHandleOnKeys', () => { test('should return `true`', () => { // keys mapping defined for actions const keyCombinations = [ { keyCode: 27 }, { keyCode: 28, altKey: true }, { keyCode: 32, shiftKey: true, metaKey: true }, { keyCode: 39, ctrlKey: true }, { keyCode: 42, altKey: true, ctrlKey: true, shiftKey: true, metaKey: true }, ]; const events = [...keyCombinations, { keyCode: 27, altKey: true }, { keyCode: 27, altKey: false }].map( keyCombination => getEventArg( keyCombination.keyCode, keyCombination.altKey, keyCombination.ctrlKey, keyCombination.metaKey, keyCombination.shiftKey, ), ); events.forEach(event => { expect(shouldHandleOnKeys(event, keyCombinations)).toBe(true); }); }); test('should return `false`', () => { // keys mapping defined for actions const keyCombinations = [ { keyCode: 27, ctrlKey: true }, { keyCode: 32 }, { keyCode: 32, altKey: true }, { keyCode: 39, shiftKey: true, metaKey: true }, { keyCode: 41, shiftKey: false }, ]; // other keys mapping, that will be passed as keydown event const events = [ { keyCode: 27, ctrlKey: false }, { keyCode: 31, altKey: true }, { keyCode: 39, shiftKey: false, metaKey: false }, { keyCode: 41, shiftKey: true }, ].map(keyCombination => getEventArg( keyCombination.keyCode, keyCombination.altKey, keyCombination.ctrlKey, keyCombination.metaKey, keyCombination.shiftKey, ), ); events.forEach(event => { expect(shouldHandleOnKeys(event, keyCombinations)).toBe(false); }); }); });
9,999
0
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test
petrpan-code/microsoft/fluentui/packages/fluentui/react-bindings/test/compose/compose-test.tsx
import * as React from 'react'; import { mount, shallow } from 'enzyme'; import { compose, mergeProps, ComposePreparedOptions } from '@fluentui/react-bindings'; describe('compose', () => { interface ToggleProps extends React.AllHTMLAttributes<{}> { as?: string; defaultChecked?: boolean; checked?: boolean; } const useToggle = (props: ToggleProps) => props; const Toggle = compose<'div', ToggleProps, {}, {}, {}>( (_props: React.HTMLAttributes<HTMLDivElement>, ref: React.Ref<HTMLDivElement>, options: ComposePreparedOptions) => { const { state } = options; const { slots, slotProps } = mergeProps(state, options); return <slots.root ref={ref} {...slotProps.root} />; }, { slots: {}, state: useToggle, handledProps: ['checked'], displayName: 'Toggle', }, ); it('can compose a component', () => { const wrapper = mount(<Toggle id="foo" checked />); expect(wrapper.html()).toMatch('<div id="foo"></div>'); expect(Toggle.displayName).toEqual('Toggle'); }); it('can recompose a component', () => { const NewToggle = compose<'div', ToggleProps, {}, {}, {}>(Toggle, { displayName: 'NewToggle' }); const wrapper = mount(<NewToggle id="foo" />); expect(wrapper.html()).toMatch('<div id="foo"></div>'); expect(NewToggle.displayName).toEqual('NewToggle'); }); it('can pass shorthandConfig via composeOptions', () => { const BaseComponent = compose<'div', { content?: string }, {}, {}, {}>( (_props, _ref, composeOptions) => { return ( <div data-mapped-prop={composeOptions.shorthandConfig.mappedProp} data-allows-jsx={composeOptions.shorthandConfig.allowsJSX} /> ); }, { shorthandConfig: { allowsJSX: false, mappedProp: 'content', }, }, ); const ComposedComponent = compose<'div', { slot?: string }, {}, {}, {}>(BaseComponent, { shorthandConfig: { mappedProp: 'slot', }, }); const wrapper = shallow(<BaseComponent />); const composedWrapper = shallow(<ComposedComponent />); expect(wrapper.prop('data-mapped-prop')).toEqual('content'); expect(wrapper.prop('data-allows-jsx')).toEqual(false); expect(composedWrapper.prop('data-mapped-prop')).toEqual('slot'); expect(composedWrapper.prop('data-allows-jsx')).toEqual(false); }); it('can recompose the state of a component', () => { const useNewToggle = (props: ToggleProps) => { return { ...props, 'data-new-state': 'NewToggle' }; }; const NewToggle = compose<'div', ToggleProps, {}, {}, {}>(Toggle, { displayName: 'NewToggle', state: useNewToggle, }); const wrapper = mount(<NewToggle id="foo" />); expect(wrapper.html()).toMatch('<div id="foo" data-new-state="NewToggle"></div>'); expect(NewToggle.displayName).toEqual('NewToggle'); }); });
632
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/channel_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { searchMoreChannels, addUsersToChannel, openDirectChannelToUserId, openGroupChannelToUserIds, loadChannelsForCurrentUser, } from 'actions/channel_actions'; import {loadProfilesForSidebar} from 'actions/user_actions'; import mockStore from 'tests/test_store'; const initialState = { entities: { channels: { currentChannelId: 'current_channel_id', myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, }, }, channels: { current_channel_id: { id: 'current_channel_id', name: 'default-name', display_name: 'Default', delete_at: 0, type: 'O', team_id: 'team_id', }, current_user_id__existingId: { id: 'current_user_id__existingId', name: 'current_user_id__existingId', display_name: 'Default', delete_at: 0, type: '0', team_id: 'team_id', }, }, channelsInTeam: { 'team-id': ['current_channel_id'], }, messageCounts: { current_channel_id: {total: 10}, current_user_id__existingId: {total: 0}, }, }, teams: { currentTeamId: 'team-id', teams: { 'team-id': { id: 'team_id', name: 'team-1', displayName: 'Team 1', }, }, myMembers: { 'team-id': {roles: 'team_role'}, }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: {roles: 'system_role'}, }, }, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, }, }, roles: { roles: { system_role: { permissions: [], }, team_role: { permissions: [], }, channel_role: { permissions: [], }, }, }, general: { license: {IsLicensed: 'false'}, serverVersion: '5.4.0', config: {PostEditTimeLimit: -1}, }, }, }; const realDateNow = Date.now; jest.mock('mattermost-redux/actions/channels', () => ({ fetchChannelsAndMembers: (...args: any) => ({type: 'MOCK_FETCH_CHANNELS_AND_MEMBERS', args}), searchChannels: () => { return { type: 'MOCK_SEARCH_CHANNELS', data: [{ id: 'channel-id', name: 'channel-name', display_name: 'Channel', delete_at: 0, type: 'O', }], }; }, addChannelMember: (...args: any) => ({type: 'MOCK_ADD_CHANNEL_MEMBER', args}), createDirectChannel: (...args: any) => ({type: 'MOCK_CREATE_DIRECT_CHANNEL', args}), createGroupChannel: (...args: any) => ({type: 'MOCK_CREATE_GROUP_CHANNEL', args}), })); jest.mock('actions/user_actions', () => ({ loadNewDMIfNeeded: jest.fn(), loadNewGMIfNeeded: jest.fn(), loadProfilesForSidebar: jest.fn(), })); describe('Actions.Channel', () => { test('loadChannelsForCurrentUser', async () => { const testStore = await mockStore(initialState); const expectedActions = [{ type: 'MOCK_FETCH_CHANNELS_AND_MEMBERS', args: ['team-id'], }]; await testStore.dispatch(loadChannelsForCurrentUser()); expect(testStore.getActions()).toEqual(expectedActions); expect(loadProfilesForSidebar).toHaveBeenCalledTimes(1); }); test('searchMoreChannels', async () => { const testStore = await mockStore(initialState); const expectedActions = [{ type: 'MOCK_SEARCH_CHANNELS', data: [{ id: 'channel-id', name: 'channel-name', display_name: 'Channel', delete_at: 0, type: 'O', }], }]; await testStore.dispatch(searchMoreChannels('', false, true)); expect(testStore.getActions()).toEqual(expectedActions); }); test('addUsersToChannel', async () => { const testStore = await mockStore(initialState); const expectedActions = [{ type: 'MOCK_ADD_CHANNEL_MEMBER', args: ['testid', 'testuserid'], }]; const fakeData = { channel: 'testid', userIds: ['testuserid'], }; await testStore.dispatch(addUsersToChannel(fakeData.channel, fakeData.userIds)); expect(testStore.getActions()).toEqual(expectedActions); }); test('openDirectChannelToUserId Not Existing', async () => { const testStore = await mockStore(initialState); const expectedActions = [{ type: 'MOCK_CREATE_DIRECT_CHANNEL', args: ['current_user_id', 'testid'], }]; const fakeData = { userId: 'testid', }; await testStore.dispatch(openDirectChannelToUserId(fakeData.userId)); expect(testStore.getActions()).toEqual(expectedActions); }); test('openDirectChannelToUserId Existing', async () => { Date.now = () => new Date(0).getMilliseconds(); const testStore = await mockStore(initialState); const expectedActions = [ { meta: { batch: true, }, payload: [ { data: [ { category: 'direct_channel_show', name: 'existingId', value: 'true', }, ], type: 'RECEIVED_PREFERENCES', }, { data: [ { category: 'channel_open_time', name: 'current_user_id__existingId', value: '0', }, ], type: 'RECEIVED_PREFERENCES', }, ], type: 'BATCHING_REDUCER.BATCH', }, { data: [ { category: 'direct_channel_show', name: 'existingId', user_id: 'current_user_id', value: 'true', }, { category: 'channel_open_time', name: 'current_user_id__existingId', user_id: 'current_user_id', value: '0', }, ], type: 'RECEIVED_PREFERENCES', }, ]; const fakeData = { userId: 'existingId', }; await testStore.dispatch(openDirectChannelToUserId(fakeData.userId)); const doneActions = testStore.getActions(); expect(doneActions).toEqual(expectedActions); Date.now = realDateNow; }); test('openGroupChannelToUserIds', async () => { const testStore = await mockStore(initialState); const expectedActions = [{ type: 'MOCK_CREATE_GROUP_CHANNEL', args: [['testuserid1', 'testuserid2']], }]; const fakeData = { userIds: ['testuserid1', 'testuserid2'], }; await testStore.dispatch(openGroupChannelToUserIds(fakeData.userIds)); expect(testStore.getActions()).toEqual(expectedActions); }); });
639
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/emoji_actions_load_recent.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import {BATCH} from 'redux-batched-actions'; import type {DeepPartial} from '@mattermost/types/utilities'; import {EmojiTypes} from 'mattermost-redux/action_types'; import {setSystemEmojis} from 'mattermost-redux/actions/emojis'; import {Client4} from 'mattermost-redux/client'; import * as Actions from 'actions/emoji_actions'; import mergeObjects from 'packages/mattermost-redux/test/merge_objects'; import mockStore from 'tests/test_store'; import {Preferences} from 'utils/constants'; import {EmojiIndicesByAlias} from 'utils/emoji'; import {TestHelper} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; Client4.setUrl('http://localhost:8065'); describe('loadRecentlyUsedCustomEmojis', () => { const currentUserId = 'currentUserId'; const emoji1 = TestHelper.getCustomEmojiMock({name: 'emoji1', id: 'emojiId1'}); const emoji2 = TestHelper.getCustomEmojiMock({name: 'emoji2', id: 'emojiId2'}); const loadedEmoji = TestHelper.getCustomEmojiMock({name: 'loaded', id: 'loadedId'}); const initialState: DeepPartial<GlobalState> = { entities: { emojis: { customEmoji: { [loadedEmoji.id]: loadedEmoji, }, nonExistentEmoji: new Set(), }, general: { config: { EnableCustomEmoji: 'true', }, }, users: { currentUserId, }, }, }; setSystemEmojis(new Set(EmojiIndicesByAlias.keys())); test('should get requested emojis', async () => { const state = mergeObjects(initialState, { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ { category: Preferences.RECENT_EMOJIS, name: currentUserId, value: JSON.stringify([ {name: emoji1.name, usageCount: 3}, {name: emoji2.name, usageCount: 5}, ]), }, ]), }, }, }); const store = mockStore(state); nock(Client4.getBaseRoute()). post('/emoji/names', ['emoji1', 'emoji2']). reply(200, [emoji1, emoji2]); await store.dispatch(Actions.loadRecentlyUsedCustomEmojis()); expect(store.getActions()).toEqual([ { type: EmojiTypes.RECEIVED_CUSTOM_EMOJIS, data: [emoji1, emoji2], }, ]); }); test('should not request emojis which are already loaded', async () => { const state = mergeObjects(initialState, { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ { category: Preferences.RECENT_EMOJIS, name: currentUserId, value: JSON.stringify([ {name: emoji1.name, usageCount: 3}, {name: loadedEmoji.name, usageCount: 5}, ]), }, ]), }, }, }); const store = mockStore(state); nock(Client4.getBaseRoute()). post('/emoji/names', ['emoji1']). reply(200, [emoji1]); await store.dispatch(Actions.loadRecentlyUsedCustomEmojis()); expect(store.getActions()).toEqual([ { type: EmojiTypes.RECEIVED_CUSTOM_EMOJIS, data: [emoji1], }, ]); }); test('should not make a request if all recentl emojis are loaded', async () => { const state = mergeObjects(initialState, { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ { category: Preferences.RECENT_EMOJIS, name: currentUserId, value: JSON.stringify([ {name: loadedEmoji.name, usageCount: 5}, ]), }, ]), }, }, }); const store = mockStore(state); await store.dispatch(Actions.loadRecentlyUsedCustomEmojis()); expect(store.getActions()).toEqual([]); }); test('should properly store any names of nonexistent emojis', async () => { const fakeEmojiName = 'fake-emoji-name'; const state = mergeObjects(initialState, { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ { category: Preferences.RECENT_EMOJIS, name: currentUserId, value: JSON.stringify([ {name: emoji1.name, usageCount: 3}, {name: fakeEmojiName, usageCount: 5}, ]), }, ]), }, }, }); const store = mockStore(state); nock(Client4.getBaseRoute()). post('/emoji/names', ['emoji1', fakeEmojiName]). reply(200, [emoji1]); await store.dispatch(Actions.loadRecentlyUsedCustomEmojis()); expect(store.getActions()).toEqual([ { type: BATCH, meta: { batch: true, }, payload: [ { type: EmojiTypes.RECEIVED_CUSTOM_EMOJIS, data: [emoji1], }, { type: EmojiTypes.CUSTOM_EMOJI_DOES_NOT_EXIST, data: fakeEmojiName, }, ], }, ]); }); test('should not request an emoji that we know does not exist', async () => { const fakeEmojiName = 'fake-emoji-name'; // Add nonExistentEmoji separately because mergeObjects only works with plain objects const state = mergeObjects(initialState, { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ { category: Preferences.RECENT_EMOJIS, name: currentUserId, value: JSON.stringify([ {name: emoji1.name, usageCount: 3}, {name: fakeEmojiName, usageCount: 5}, ]), }, ]), }, }, }); state.entities.emojis.nonExistentEmoji = new Set([fakeEmojiName]); const store = mockStore(state); nock(Client4.getBaseRoute()). post('/emoji/names', ['emoji1']). reply(200, [emoji1]); await store.dispatch(Actions.loadRecentlyUsedCustomEmojis()); expect(store.getActions()).toEqual([ { type: EmojiTypes.RECEIVED_CUSTOM_EMOJIS, data: [emoji1], }, ]); }); test('should not request a system emoji', async () => { const state = mergeObjects(initialState, { entities: { preferences: { myPreferences: TestHelper.getPreferencesMock([ { category: Preferences.RECENT_EMOJIS, name: currentUserId, value: JSON.stringify([ {name: emoji1.name, usageCount: 3}, {name: 'taco', usageCount: 5}, ]), }, ]), }, }, }); const store = mockStore(state); nock(Client4.getBaseRoute()). post('/emoji/names', ['emoji1']). reply(200, [emoji1]); await store.dispatch(Actions.loadRecentlyUsedCustomEmojis()); expect(store.getActions()).toEqual([ { type: EmojiTypes.RECEIVED_CUSTOM_EMOJIS, data: [emoji1], }, ]); }); });
641
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/global_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Team} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {redirectUserToDefaultTeam, toggleSideBarRightMenuAction, getTeamRedirectChannelIfIsAccesible} from 'actions/global_actions'; import {close as closeLhs} from 'actions/views/lhs'; import {closeRightHandSide, closeMenu as closeRhsMenu} from 'actions/views/rhs'; import LocalStorageStore from 'stores/local_storage_store'; import reduxStore from 'stores/redux_store'; import mockStore from 'tests/test_store'; import {getHistory} from 'utils/browser_history'; jest.mock('actions/views/rhs', () => ({ closeMenu: jest.fn(), closeRightHandSide: jest.fn(), })); jest.mock('actions/views/lhs', () => ({ close: jest.fn(), })); jest.mock('mattermost-redux/actions/users', () => ({ loadMe: () => ({type: 'MOCK_RECEIVED_ME'}), })); jest.mock('stores/redux_store', () => { return { dispatch: jest.fn(), getState: jest.fn(), }; }); describe('actions/global_actions', () => { describe('redirectUserToDefaultTeam', () => { it('should redirect to /select_team when no team is available', async () => { const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, }, teams: { teams: {}, myMembers: {}, }, channels: { myMembers: {}, channels: {}, channelsInTeam: {}, }, users: { currentUserId: 'user1', profiles: { user1: { id: 'user1', roles: '', }, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); await redirectUserToDefaultTeam(); expect(getHistory().push).toHaveBeenCalledWith('/select_team'); }); it('should redirect to last viewed channel in the last viewed team when the user have access to that team', async () => { const userId = 'user1'; LocalStorageStore.setPreviousTeamId(userId, 'team2'); LocalStorageStore.setPreviousChannelName(userId, 'team1', 'channel-in-team-1'); LocalStorageStore.setPreviousChannelName(userId, 'team2', 'channel-in-team-2'); const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, serverVersion: '5.16.0', }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, channels: { myMembers: { 'channel-in-team-1': {}, 'channel-in-team-2': {}, }, channels: { 'channel-in-team-1': { id: 'channel-in-team-1', team_id: 'team1', name: 'channel-in-team-1', }, 'channel-in-team-2': { id: 'channel-in-team-2', team_id: 'team2', name: 'channel-in-team-2', }, }, channelsInTeam: { team1: ['channel-in-team-1'], team2: ['channel-in-team-2'], }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, roles: 'system_guest'}, }, }, roles: { roles: { system_guest: { permissions: [], }, team_guest: { permissions: [], }, channel_guest: { permissions: [], }, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); await redirectUserToDefaultTeam(); expect(getHistory().push).toHaveBeenCalledWith('/team2/channels/channel-in-team-2'); }); it('should redirect to last channel on first team with channels when the user have no channels in the current team', async () => { const userId = 'user1'; LocalStorageStore.setPreviousTeamId(userId, 'team1'); LocalStorageStore.setPreviousChannelName(userId, 'team1', 'channel-in-team-1'); LocalStorageStore.setPreviousChannelName(userId, 'team2', 'channel-in-team-2'); const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, serverVersion: '5.16.0', }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, channels: { myMembers: { 'channel-in-team-2': {}, }, channels: { 'channel-in-team-1': { id: 'channel-in-team-1', team_id: 'team1', name: 'channel-in-team-1', }, 'channel-in-team-2': { id: 'channel-in-team-2', team_id: 'team2', name: 'channel-in-team-2', }, }, channelsInTeam: { team1: ['channel-in-team-1'], team2: ['channel-in-team-2'], }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, roles: 'system_guest'}, }, }, roles: { roles: { system_guest: { permissions: [], }, team_guest: { permissions: [], }, channel_guest: { permissions: [], }, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); await redirectUserToDefaultTeam(); expect(getHistory().push).toHaveBeenCalledWith('/team2/channels/channel-in-team-2'); }); it('should redirect to /select_team when the user have no channels in the any of his teams', async () => { const userId = 'user1'; LocalStorageStore.setPreviousTeamId(userId, 'team1'); LocalStorageStore.setPreviousChannelName(userId, 'team1', 'channel-in-team-1'); LocalStorageStore.setPreviousChannelName(userId, 'team2', 'channel-in-team-2'); const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, serverVersion: '5.16.0', }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, channels: { myMembers: { }, channels: { 'channel-in-team-1': { id: 'channel-in-team-1', team_id: 'team1', name: 'channel-in-team-1', }, 'channel-in-team-2': { id: 'channel-in-team-2', team_id: 'team2', name: 'channel-in-team-2', }, }, channelsInTeam: { team1: ['channel-in-team-1'], team2: ['channel-in-team-2'], }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, roles: 'system_guest'}, }, }, roles: { roles: { system_guest: { permissions: [], }, team_guest: { permissions: [], }, channel_guest: { permissions: [], }, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); await redirectUserToDefaultTeam(); expect(getHistory().push).toHaveBeenCalledWith('/select_team'); }); it('should do nothing if there is not current user', async () => { const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, users: { profiles: { user1: {id: 'user1', roles: 'system_guest'}, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); await redirectUserToDefaultTeam(); expect(getHistory().push).not.toHaveBeenCalled(); }); it('should redirect to direct message if that\'s the most recently used', async () => { const userId = 'user1'; const teamId = 'team1'; const user2 = 'user2'; const directChannelId = `${userId}__${user2}`; const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', TeammateNameDisplay: 'username', }, serverVersion: '5.16.0', }, preferences: { myPreferences: {}, }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, channels: { myMembers: { 'channel-in-team-1': {}, 'channel-in-team-2': {}, [directChannelId]: {}, }, channels: { 'channel-in-team-1': { id: 'channel-in-team-1', team_id: 'team1', name: 'channel-in-team-1', type: 'O', }, 'channel-in-team-2': { id: 'channel-in-team-2', team_id: 'team2', name: 'channel-in-team-2', type: 'O', }, [directChannelId]: { id: directChannelId, team_id: '', name: directChannelId, type: 'D', teammate_id: 'user2', }, 'group-channel': { id: 'group-channel', name: 'group-channel', team_id: 'team1', type: 'G', }, }, channelsInTeam: { team1: ['channel-in-team-1', directChannelId], team2: ['channel-in-team-2'], }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: userId, roles: 'system_guest'}, [user2]: {id: user2, username: user2, roles: 'system_guest'}, }, }, roles: { roles: { system_guest: { permissions: [], }, team_guest: { permissions: [], }, channel_guest: { permissions: [], }, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); LocalStorageStore.setPreviousTeamId(userId, teamId); LocalStorageStore.setPreviousChannelName(userId, teamId, directChannelId); const result = await getTeamRedirectChannelIfIsAccesible({id: userId} as UserProfile, {id: teamId} as Team); expect(result?.id).toBe(directChannelId); }); it('should redirect to group message if that\'s the most recently used', async () => { const userId = 'user1'; const teamId = 'team1'; const user2 = 'user2'; const directChannelId = `${userId}__${user2}`; const groupChannelId = 'group-channel'; const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', TeammateNameDisplay: 'username', }, serverVersion: '5.16.0', }, preferences: { myPreferences: {}, }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, channels: { myMembers: { 'channel-in-team-1': {}, 'channel-in-team-2': {}, [directChannelId]: {}, [groupChannelId]: {}, }, channels: { 'channel-in-team-1': { id: 'channel-in-team-1', team_id: 'team1', name: 'channel-in-team-1', type: 'O', }, 'channel-in-team-2': { id: 'channel-in-team-2', team_id: 'team2', name: 'channel-in-team-2', type: 'O', }, [directChannelId]: { id: directChannelId, team_id: '', name: directChannelId, type: 'D', teammate_id: 'user2', }, [groupChannelId]: { id: groupChannelId, name: groupChannelId, team_id: 'team1', type: 'G', }, }, channelsInTeam: { team1: ['channel-in-team-1', directChannelId, groupChannelId], team2: ['channel-in-team-2'], }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, username: userId, roles: 'system_guest'}, [user2]: {id: user2, username: user2, roles: 'system_guest'}, }, }, roles: { roles: { system_guest: { permissions: [], }, team_guest: { permissions: [], }, channel_guest: { permissions: [], }, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); LocalStorageStore.setPreviousTeamId(userId, teamId); LocalStorageStore.setPreviousChannelName(userId, teamId, groupChannelId); const result = await getTeamRedirectChannelIfIsAccesible({id: userId} as UserProfile, {id: teamId} as Team); expect(result?.id).toBe(groupChannelId); }); it('should redirect to last channel on first team when current team is no longer available', async () => { const userId = 'user1'; LocalStorageStore.setPreviousTeamId(userId, 'non-existent'); LocalStorageStore.setPreviousChannelName(userId, 'team1', 'channel-in-team-1'); LocalStorageStore.setPreviousChannelName(userId, 'team2', 'channel-in-team-2'); const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, }, teams: { teams: { team1: {id: 'team1', display_name: 'Team 1', name: 'team1', delete_at: 0}, team2: {id: 'team2', display_name: 'Team 2', name: 'team2', delete_at: 0}, }, myMembers: { team1: {id: 'team1'}, team2: {id: 'team2'}, }, }, channels: { myMembers: { 'channel-in-team-1': {}, 'channel-in-team-2': {}, }, channels: { 'channel-in-team-1': { id: 'channel-in-team-1', team_id: 'team1', name: 'channel-in-team-1', }, 'channel-in-team-2': { id: 'channel-in-team-2', team_id: 'team2', name: 'channel-in-team-2', }, }, channelsInTeam: { team1: ['channel-in-team-1'], team2: ['channel-in-team-2'], }, }, users: { currentUserId: userId, profiles: { [userId]: {id: userId, roles: ''}, }, }, }, }); reduxStore.getState.mockImplementation(store.getState); await redirectUserToDefaultTeam(); expect(getHistory().push).toHaveBeenCalledWith('/team1/channels/channel-in-team-1'); }); }); test('toggleSideBarRightMenuAction', () => { const dispatchMock = async () => { return {data: true}; }; toggleSideBarRightMenuAction()(dispatchMock); expect(closeRhsMenu).toHaveBeenCalled(); expect(closeRightHandSide).toHaveBeenCalled(); expect(closeLhs).toHaveBeenCalled(); }); });
646
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/integration_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {IncomingWebhook, OutgoingWebhook, Command, OAuthApp} from '@mattermost/types/integrations'; import {getProfilesByIds} from 'mattermost-redux/actions/users'; import * as Actions from 'actions/integration_actions'; import mockStore from 'tests/test_store'; jest.mock('mattermost-redux/actions/users', () => ({ getProfilesByIds: jest.fn(() => { return {type: ''}; }), })); interface CustomMatchers<R = unknown> { arrayContainingExactly(stringArray: string[]): R; } type GreatExpectations = typeof expect & CustomMatchers; describe('actions/integration_actions', () => { const initialState = { entities: { teams: { currentTeamId: 'team_id1', teams: { team_id1: { id: 'team_id1', name: 'team1', }, }, }, users: { currentUserId: 'current_user_id', profiles: {current_user_id: {id: 'current_user_id', username: 'current_user'}, user_id3: {id: 'user_id3', username: 'user3'}, user_id4: {id: 'user_id4', username: 'user4'}}, }, }, }; describe('loadProfilesForIncomingHooks', () => { test('load profiles for hooks including user we already have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForIncomingHooks([{user_id: 'current_user_id'}, {user_id: 'user_id2'}] as IncomingWebhook[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id2'])); }); test('load profiles for hooks including only users we don\'t have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForIncomingHooks([{user_id: 'user_id1'}, {user_id: 'user_id2'}] as IncomingWebhook[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id1', 'user_id2'])); }); test('load profiles for empty hooks', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForIncomingHooks([])); expect(getProfilesByIds).not.toHaveBeenCalled(); }); }); describe('loadProfilesForOutgoingHooks', () => { test('load profiles for hooks including user we already have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForOutgoingHooks([{creator_id: 'current_user_id'}, {creator_id: 'user_id2'}] as OutgoingWebhook[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id2'])); }); test('load profiles for hooks including only users we don\'t have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForOutgoingHooks([{creator_id: 'user_id1'}, {creator_id: 'user_id2'}] as OutgoingWebhook[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id1', 'user_id2'])); }); test('load profiles for empty hooks', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForOutgoingHooks([])); expect(getProfilesByIds).not.toHaveBeenCalled(); }); }); describe('loadProfilesForCommands', () => { test('load profiles for commands including user we already have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForCommands([{creator_id: 'current_user_id'}, {creator_id: 'user_id2'}] as Command[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id2'])); }); test('load profiles for commands including only users we don\'t have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForCommands([{creator_id: 'user_id1'}, {creator_id: 'user_id2'}] as Command[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id1', 'user_id2'])); }); test('load profiles for empty commands', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForCommands([])); expect(getProfilesByIds).not.toHaveBeenCalled(); }); }); describe('loadProfilesForOAuthApps', () => { test('load profiles for apps including user we already have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForOAuthApps([{creator_id: 'current_user_id'}, {creator_id: 'user_id2'}] as OAuthApp[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id2'])); }); test('load profiles for apps including only users we don\'t have', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForOAuthApps([{creator_id: 'user_id1'}, {creator_id: 'user_id2'}] as OAuthApp[])); expect(getProfilesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id1', 'user_id2'])); }); test('load profiles for empty apps', () => { const testStore = mockStore(initialState); testStore.dispatch(Actions.loadProfilesForOAuthApps([])); expect(getProfilesByIds).not.toHaveBeenCalled(); }); }); });
648
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/invite_actions.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 {UserProfile} from '@mattermost/types/users'; import type {DispatchFunc, GetStateFunc} from 'mattermost-redux/types/actions'; import {sendMembersInvites, sendGuestsInvites} from 'actions/invite_actions'; import mockStore from 'tests/test_store'; import {ConsolePages} from 'utils/constants'; jest.mock('actions/team_actions', () => ({ addUsersToTeam: () => ({ // since we are using addUsersToTeamGracefully, this call will always succeed type: 'MOCK_RECEIVED_ME', }), })); jest.mock('mattermost-redux/actions/channels', () => ({ // eslint-disable-next-line @typescript-eslint/no-unused-vars joinChannel: (_userId: string, _teamId: string, channelId: string, _channelName: string) => { if (channelId === 'correct') { return ({type: 'MOCK_RECEIVED_ME'}); } if (channelId === 'correct2') { return ({type: 'MOCK_RECEIVED_ME'}); } throw new Error('ERROR'); }, // eslint-disable-next-line @typescript-eslint/no-unused-vars getChannelMembersByIds: (channelId: string, userIds: string[]) => { return ({type: 'MOCK_RECEIVED_CHANNEL_MEMBERS'}); }, })); jest.mock('mattermost-redux/actions/teams', () => ({ getTeamMembersByIds: () => ({type: 'MOCK_RECEIVED_ME'}), sendEmailInvitesToTeamGracefully: (team: string, emails: string[]) => { if (team === 'incorrect-default-smtp') { return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: {message: 'SMTP is not configured in System Console.', id: 'api.team.invite_members.unable_to_send_email_with_defaults.app_error'}}))}); } else if (emails.length > 21) { // Poor attempt to mock rate limiting. return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: {message: 'Invite emails rate limit exceeded.'}}))}); } else if (team === 'error') { return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: {message: 'Unable to add the user to the team.'}}))}); } // team === 'correct' i.e no error return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: undefined}))}); }, // eslint-disable-next-line @typescript-eslint/no-unused-vars sendEmailGuestInvitesToChannelsGracefully: (teamId: string, _channelIds: string[], emails: string[], _message: string) => { if (teamId === 'incorrect-default-smtp') { return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: {message: 'SMTP is not configured in System Console.', id: 'api.team.invite_members.unable_to_send_email_with_defaults.app_error'}}))}); } else if (emails.length > 21) { // Poor attempt to mock rate limiting. return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: {message: 'Invite emails rate limit exceeded.'}}))}); } else if (teamId === 'error') { return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: {message: 'Unable to add the guest to the channels.'}}))}); } // teamId === 'correct' i.e no error return ({type: 'MOCK_RECEIVED_ME', data: emails.map((email) => ({email, error: undefined}))}); }, })); describe('actions/invite_actions', () => { const store = mockStore({ entities: { general: { config: { DefaultClientLocale: 'en', }, }, teams: { teams: { correct: {id: 'correct'}, error: {id: 'error'}, }, membersInTeam: { correct: { user1: {id: 'user1'}, user2: {id: 'user2'}, guest1: {id: 'guest1'}, guest2: {id: 'guest2'}, guest3: {id: 'guest3'}, }, error: { user1: {id: 'user1'}, user2: {id: 'user2'}, guest1: {id: 'guest1'}, guest2: {id: 'guest2'}, guest3: {id: 'guest3'}, }, }, myMembers: {}, }, channels: { myMembers: {}, channels: {}, membersInChannel: { correct: { guest2: {id: 'guest2'}, guest3: {id: 'guest3'}, }, correct2: { guest2: {id: 'guest2'}, }, error: { guest2: {id: 'guest2'}, guest3: {id: 'guest3'}, }, }, }, users: { currentUserId: 'user1', profiles: { user1: { roles: 'system_admin', }, }, }, }, }); describe('sendMembersInvites', () => { it('should generate and empty list if nothing is passed', async () => { const response = await sendMembersInvites('correct', [], [])(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [], notSent: [], }, }); }); it('should generate list of success for emails', async () => { const emails = ['[email protected]', '[email protected]', '[email protected]']; const response = await sendMembersInvites('correct', [], emails)(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { notSent: [], sent: [ { email: '[email protected]', reason: 'An invitation email has been sent.', }, { email: '[email protected]', reason: 'An invitation email has been sent.', }, { email: '[email protected]', reason: 'An invitation email has been sent.', }, ], }, }); }); it('should generate list of failures for emails on invite fails', async () => { const emails = ['[email protected]', '[email protected]', '[email protected]']; const response = await sendMembersInvites('error', [], emails)(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [], notSent: [ { email: '[email protected]', reason: 'Unable to add the user to the team.', }, { email: '[email protected]', reason: 'Unable to add the user to the team.', }, { email: '[email protected]', reason: 'Unable to add the user to the team.', }, ], }, }); }); it('should generate list of failures and success for regular users and guests', async () => { const users = [ {id: 'user1', roles: 'system_user'}, {id: 'guest1', roles: 'system_guest'}, {id: 'other-user', roles: 'system_user'}, {id: 'other-guest', roles: 'system_guest'}, ] as UserProfile[]; const response = await sendMembersInvites('correct', users, [])(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [ { reason: 'This member has been added to the team.', user: { id: 'other-user', roles: 'system_user', }, }, ], notSent: [ { reason: 'This person is already a team member.', user: { id: 'user1', roles: 'system_user', }, }, { reason: 'Contact your admin to make this guest a full member.', user: { id: 'guest1', roles: 'system_guest', }, }, { reason: 'Contact your admin to make this guest a full member.', user: { id: 'other-guest', roles: 'system_guest', }, }, ], }, }); }); it('should generate a failure for problems adding a user', async () => { const users = [ {id: 'user1', roles: 'system_user'}, {id: 'guest1', roles: 'system_guest'}, {id: 'other-user', roles: 'system_user'}, {id: 'other-guest', roles: 'system_guest'}, ] as UserProfile[]; const response = await sendMembersInvites('error', users, [])(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [{user: {id: 'other-user', roles: 'system_user'}, reason: 'This member has been added to the team.'}], notSent: [ { reason: 'This person is already a team member.', user: { id: 'user1', roles: 'system_user', }, }, { reason: 'Contact your admin to make this guest a full member.', user: { id: 'guest1', roles: 'system_guest', }, }, { reason: 'Contact your admin to make this guest a full member.', user: { id: 'other-guest', roles: 'system_guest', }, }, ], }, }); }); it('should generate a failure for rate limits', async () => { const emails = []; const expectedNotSent = []; for (let i = 0; i < 22; i++) { emails.push('email-' + i + '@example.com'); expectedNotSent.push({ email: 'email-' + i + '@example.com', reason: 'Invite emails rate limit exceeded.', }); } const response = await sendMembersInvites('correct', [], emails)(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { notSent: expectedNotSent, sent: [], }, }); }); it('should generate a failure for smtp config', async () => { const emails = ['[email protected]']; const response = await sendMembersInvites('incorrect-default-smtp', [], emails)(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { notSent: [ { email: '[email protected]', reason: { id: 'admin.environment.smtp.smtpFailure', message: 'SMTP is not configured in System Console. Can be configured <a>here</a>.', }, path: ConsolePages.SMTP, }], sent: [], }, }); }); }); describe('sendGuestsInvites', () => { it('should generate and empty list if nothing is passed', async () => { const response = await sendGuestsInvites('correct', [], [], [], '')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [], notSent: [], }, }); }); it('should generate list of success for emails', async () => { const channels = [{id: 'correct'}] as Channel[]; const emails = ['[email protected]', '[email protected]', '[email protected]']; const response = await sendGuestsInvites('correct', channels, [], emails, 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { notSent: [], sent: [ { email: '[email protected]', reason: 'An invitation email has been sent.', }, { email: '[email protected]', reason: 'An invitation email has been sent.', }, { email: '[email protected]', reason: 'An invitation email has been sent.', }, ], }, }); }); it('should generate list of failures for emails on invite fails', async () => { const channels = [{id: 'correct'}] as Channel[]; const emails = ['[email protected]', '[email protected]', '[email protected]']; const response = await sendGuestsInvites('error', channels, [], emails, 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [], notSent: [ { email: '[email protected]', reason: 'Unable to add the guest to the channels.', }, { email: '[email protected]', reason: 'Unable to add the guest to the channels.', }, { email: '[email protected]', reason: 'Unable to add the guest to the channels.', }, ], }, }); }); it('should generate list of failures and success for regular users and guests', async () => { const channels = [{id: 'correct'}] as Channel[]; const users = [ {id: 'user1', roles: 'system_user'}, {id: 'guest1', roles: 'system_guest'}, {id: 'other-user', roles: 'system_user'}, {id: 'other-guest', roles: 'system_guest'}, ] as UserProfile[]; const response = await sendGuestsInvites('correct', channels, users, [], 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [ { reason: { id: 'invite.guests.new-member', message: 'This guest has been added to the team and {count, plural, one {channel} other {channels}}.', values: {count: channels.length}, }, user: { id: 'guest1', roles: 'system_guest', }, }, { reason: { id: 'invite.guests.new-member', message: 'This guest has been added to the team and {count, plural, one {channel} other {channels}}.', values: {count: channels.length}, }, user: { id: 'other-guest', roles: 'system_guest', }, }, ], notSent: [ { reason: 'This person is already a member.', user: { id: 'user1', roles: 'system_user', }, }, { reason: 'This person is already a member.', user: { id: 'other-user', roles: 'system_user', }, }, ], }, }); }); it('should generate a failure for users that are part of all or some of the channels', async () => { const users = [ {id: 'guest2', roles: 'system_guest'}, {id: 'guest3', roles: 'system_guest'}, ] as UserProfile[]; const response = await sendGuestsInvites('correct', [{id: 'correct'}, {id: 'correct2'}] as Channel[], users, [], 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [], notSent: [ { reason: 'This person is already a member of all the channels.', user: { id: 'guest2', roles: 'system_guest', }, }, { reason: 'This person is already a member of some of the channels.', user: { id: 'guest3', roles: 'system_guest', }, }, ], }, }); }); it('should generate a failure for problems adding a user to team', async () => { const users = [ {id: 'user1', roles: 'system_user'}, {id: 'guest1', roles: 'system_guest'}, {id: 'other-user', roles: 'system_user'}, {id: 'other-guest', roles: 'system_guest'}, ] as UserProfile[]; const response = await sendGuestsInvites('error', [{id: 'correct'}] as Channel[], users, [], 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [ { user: { id: 'guest1', roles: 'system_guest', }, reason: { id: 'invite.guests.new-member', message: 'This guest has been added to the team and {count, plural, one {channel} other {channels}}.', values: { count: 1, }, }, }, { user: { id: 'other-guest', roles: 'system_guest', }, reason: { id: 'invite.guests.new-member', message: 'This guest has been added to the team and {count, plural, one {channel} other {channels}}.', values: { count: 1, }, }, }, ], notSent: [ { reason: 'This person is already a member.', user: { id: 'user1', roles: 'system_user', }, }, { reason: 'This person is already a member.', user: { id: 'other-user', roles: 'system_user', }, }, ], }, }); }); it('should generate a failure for problems adding a user to channels', async () => { const users = [ {id: 'user1', roles: 'system_user'}, {id: 'guest1', roles: 'system_guest'}, {id: 'other-user', roles: 'system_user'}, {id: 'other-guest', roles: 'system_guest'}, ] as UserProfile[]; const response = await sendGuestsInvites('correct', [{id: 'error'}] as Channel[], users, [], 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { sent: [], notSent: [ { reason: 'This person is already a member.', user: { id: 'user1', roles: 'system_user', }, }, { reason: 'Unable to add the guest to the channels.', user: { id: 'guest1', roles: 'system_guest', }, }, { reason: 'This person is already a member.', user: { id: 'other-user', roles: 'system_user', }, }, { reason: 'Unable to add the guest to the channels.', user: { id: 'other-guest', roles: 'system_guest', }, }, ], }, }); }); it('should generate a failure for rate limits', async () => { const emails = []; const expectedNotSent = []; for (let i = 0; i < 22; i++) { emails.push('email-' + i + '@example.com'); expectedNotSent.push({ email: 'email-' + i + '@example.com', reason: 'Invite emails rate limit exceeded.', }); } const response = await sendGuestsInvites('correct', [{id: 'correct'}] as Channel[], [], emails, 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { notSent: expectedNotSent, sent: [], }, }); }); it('should generate a failure for smtp config', async () => { const emails = ['[email protected]']; const response = await sendGuestsInvites('incorrect-default-smtp', [{id: 'error'}] as Channel[], [], emails, 'message')(store.dispatch as DispatchFunc, store.getState as GetStateFunc); expect(response).toEqual({ data: { notSent: [ { email: '[email protected]', reason: { id: 'admin.environment.smtp.smtpFailure', message: 'SMTP is not configured in System Console. Can be configured <a>here</a>.', }, path: ConsolePages.SMTP, }], sent: [], }, }); }); }); });
651
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/new_post.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 {GlobalState} from '@mattermost/types/store'; import {ChannelTypes} from 'mattermost-redux/action_types'; import {receivedNewPost} from 'mattermost-redux/actions/posts'; import {Posts} from 'mattermost-redux/constants'; import type {GetStateFunc} from 'mattermost-redux/types/actions'; import * as NewPostActions from 'actions/new_post'; import mockStore from 'tests/test_store'; import {Constants} from 'utils/constants'; jest.mock('mattermost-redux/actions/channels', () => ({ ...jest.requireActual('mattermost-redux/actions/channels'), markChannelAsReadOnServer: (...args: any[]) => ({type: 'MOCK_MARK_CHANNEL_AS_READ_ON_SERVER', args}), markChannelAsViewedOnServer: (...args: any[]) => ({type: 'MOCK_MARK_CHANNEL_AS_VIEWED_ON_SERVER', args}), })); const POST_CREATED_TIME = Date.now(); // This mocks the Date.now() function so it returns a constant value global.Date.now = jest.fn(() => POST_CREATED_TIME); const newPostMessageProps = {} as NewPostActions.NewPostMessageProps; const INCREASED_POST_VISIBILITY = {amount: 1, data: 'current_channel_id', type: 'INCREASE_POST_VISIBILITY'}; describe('actions/new_post', () => { const latestPost = { id: 'latest_post_id', user_id: 'current_user_id', message: 'test msg', channel_id: 'current_channel_id', }; const initialState = { entities: { posts: { posts: { [latestPost.id]: latestPost, }, postsInChannel: { current_channel_id: [ {order: [latestPost.id], recent: true}, ], }, postsInThread: {}, messagesHistory: { index: { [Posts.MESSAGE_TYPES.COMMENT]: 0, }, messages: ['test message'], }, }, channels: { currentChannelId: 'current_channel_id', messageCounts: {}, myMembers: {[latestPost.channel_id]: {channel_id: 'current_channel_id', user_id: 'current_user_id'}}, channels: { current_channel_id: {id: 'current_channel_id'}, }, }, teams: { currentTeamId: 'team-1', teams: { team_id: { id: 'team_id', name: 'team-1', displayName: 'Team 1', }, }, }, users: { currentUserId: 'current_user_id', }, general: { license: {IsLicensed: 'false'}, config: { TeammateNameDisplay: 'username', }, }, preferences: { myPreferences: {}, }, }, views: { posts: { editingPost: {}, }, }, } as unknown as GlobalState; test('completePostReceive', async () => { const testStore = mockStore(initialState); const newPost = {id: 'new_post_id', channel_id: 'current_channel_id', message: 'new message', type: Constants.PostTypes.ADD_TO_CHANNEL, user_id: 'some_user_id', create_at: POST_CREATED_TIME, props: {addedUserId: 'other_user_id'}} as unknown as Post; const websocketProps = {team_id: 'team_id', mentions: ['current_user_id']}; await testStore.dispatch(NewPostActions.completePostReceive(newPost, websocketProps)); expect(testStore.getActions()).toEqual([ { meta: {batch: true}, payload: [ INCREASED_POST_VISIBILITY, receivedNewPost(newPost, false), ], type: 'BATCHING_REDUCER.BATCH', }, ]); }); describe('setChannelReadAndViewed', () => { test('should mark channel as read when viewing channel', () => { const channelId = 'channel'; const currentUserId = 'user'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1000} as Post; const post2 = {id: 'post2', channel_id: channelId, create_at: 2000} as Post; const testStore = mockStore({ entities: { channels: { currentChannelId: channelId, manuallyUnread: {}, messageCounts: { [channelId]: {total: 0}, }, myMembers: { [channelId]: {channel_id: channelId, last_viewed_at: 0, roles: ''}, }, channels: { [channelId]: {id: channelId}, }, }, posts: { posts: { [post1.id]: post1, }, }, users: { currentUserId, }, general: { config: { test: true, }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState); window.isActive = true; const actions = NewPostActions.setChannelReadAndViewed(testStore.dispatch, testStore.getState as GetStateFunc, post2, newPostMessageProps, false); expect(actions).toMatchObject([ { type: ChannelTypes.DECREMENT_UNREAD_MSG_COUNT, data: { channelId, }, }, { type: ChannelTypes.DECREMENT_UNREAD_MENTION_COUNT, data: { channelId, }, }, { type: ChannelTypes.RECEIVED_LAST_VIEWED_AT, data: { channel_id: channelId, }, }, ]); expect(testStore.getActions()).toMatchObject([ { type: 'MOCK_MARK_CHANNEL_AS_VIEWED_ON_SERVER', args: [channelId], }, ]); }); test('should mark channel as unread when not actively viewing channel', () => { const channelId = 'channel'; const currentUserId = 'user'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1000} as Post; const post2 = {id: 'post2', channel_id: channelId, create_at: 2000} as Post; const testStore = mockStore({ entities: { channels: { currentChannelId: channelId, manuallyUnread: {}, messageCounts: { [channelId]: {total: 0}, }, myMembers: { [channelId]: {channel_id: channelId, last_viewed_at: 0, roles: ''}, }, channels: { [channelId]: {id: channelId}, }, }, posts: { posts: { [post1.id]: post1, }, }, users: { currentUserId, }, general: { config: { test: true, }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState); window.isActive = false; const actions = NewPostActions.setChannelReadAndViewed(testStore.dispatch, testStore.getState, post2, newPostMessageProps, false); expect(actions).toMatchObject([ { type: ChannelTypes.INCREMENT_UNREAD_MSG_COUNT, data: { channelId, }, }, { type: ChannelTypes.INCREMENT_TOTAL_MSG_COUNT, data: { channelId, }, }, ]); expect(testStore.getActions()).toEqual([]); }); test('should not mark channel as read when not viewing channel', () => { const channelId = 'channel1'; const otherChannelId = 'channel2'; const currentUserId = 'user'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1000} as Post; const post2 = {id: 'post2', channel_id: channelId, create_at: 2000} as Post; const testStore = mockStore({ entities: { channels: { currentChannelId: otherChannelId, manuallyUnread: {}, messageCounts: { [channelId]: {total: 0}, [otherChannelId]: {total: 0}, }, myMembers: { [channelId]: {channel_id: channelId, last_viewed_at: 500, roles: ''}, [otherChannelId]: {channel_id: otherChannelId, last_viewed_at: 500, roles: ''}, }, channels: { [channelId]: {id: channelId}, [otherChannelId]: {id: otherChannelId}, }, }, posts: { posts: { [post1.id]: post1, }, }, users: { currentUserId, }, general: { config: { test: true, }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState); window.isActive = true; const actions = NewPostActions.setChannelReadAndViewed(testStore.dispatch, testStore.getState, post2, newPostMessageProps, false); expect(actions).toMatchObject([ { type: ChannelTypes.INCREMENT_UNREAD_MSG_COUNT, data: { channelId, }, }, { type: ChannelTypes.INCREMENT_TOTAL_MSG_COUNT, data: { channelId, }, }, ]); expect(testStore.getActions()).toEqual([]); }); test('should mark channel as read when not viewing channel and post is from current user', () => { const channelId = 'channel1'; const otherChannelId = 'channel2'; const currentUserId = 'user'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1000} as Post; const post2 = {id: 'post2', channel_id: channelId, create_at: 2000, user_id: currentUserId} as Post; const testStore = mockStore({ entities: { channels: { currentChannelId: otherChannelId, manuallyUnread: {}, messageCounts: { [channelId]: {total: 0}, [otherChannelId]: {total: 0}, }, myMembers: { [channelId]: {channel_id: channelId, last_viewed_at: 500, roles: ''}, [otherChannelId]: {channel_id: otherChannelId, last_viewed_at: 500, roles: ''}, }, channels: { [channelId]: {id: channelId}, [otherChannelId]: {id: otherChannelId}, }, }, posts: { posts: { [post1.id]: post1, }, }, users: { currentUserId, }, general: { config: { test: true, }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState); const actions = NewPostActions.setChannelReadAndViewed(testStore.dispatch, testStore.getState, post2, {} as NewPostActions.NewPostMessageProps, false); expect(actions).toMatchObject([ { type: ChannelTypes.DECREMENT_UNREAD_MSG_COUNT, data: { channelId, }, }, { type: ChannelTypes.DECREMENT_UNREAD_MENTION_COUNT, data: { channelId, }, }, { type: ChannelTypes.RECEIVED_LAST_VIEWED_AT, data: { channel_id: channelId, }, }, ]); // The post is from the current user, so no request should be made to the server to mark it as read expect(testStore.getActions()).toEqual([]); }); test('should mark channel as unread when not viewing channel and post is from webhook owned by current user', async () => { const channelId = 'channel1'; const otherChannelId = 'channel2'; const currentUserId = 'user'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1000} as Post; const post2 = {id: 'post2', channel_id: channelId, create_at: 2000, props: {from_webhook: 'true'}, user_id: currentUserId} as unknown as Post; const testStore = mockStore({ entities: { channels: { currentChannelId: otherChannelId, manuallyUnread: {}, messageCounts: { [channelId]: {total: 0}, [otherChannelId]: {total: 0}, }, myMembers: { [channelId]: {channel_id: channelId, last_viewed_at: 500, roles: ''}, [otherChannelId]: {channel_id: otherChannelId, last_viewed_at: 500, roles: ''}, }, channels: { [channelId]: {id: channelId}, [otherChannelId]: {id: otherChannelId}, }, }, posts: { posts: { [post1.id]: post1, }, }, users: { currentUserId, }, general: { config: { test: true, }, }, preferences: { myPreferences: {}, }, }, } as unknown as GlobalState); const actions = NewPostActions.setChannelReadAndViewed(testStore.dispatch, testStore.getState, post2, newPostMessageProps, false); expect(actions).toMatchObject([ { type: ChannelTypes.INCREMENT_UNREAD_MSG_COUNT, data: { channelId, }, }, { type: ChannelTypes.INCREMENT_TOTAL_MSG_COUNT, data: { channelId, }, }, ]); expect(testStore.getActions()).toEqual([]); }); test('should not mark channel as read when viewing channel that was marked as unread', () => { const channelId = 'channel1'; const currentUserId = 'user'; const post1 = {id: 'post1', channel_id: channelId, create_at: 1000} as Post; const post2 = {id: 'post2', channel_id: channelId, create_at: 2000} as Post; const testStore = mockStore({ entities: { channels: { currentChannelId: channelId, manuallyUnread: { [channelId]: true, }, messageCounts: { [channelId]: {total: 0}, }, myMembers: { [channelId]: {channel_id: channelId, last_viewed_at: post1.create_at - 1, roles: ''}, }, channels: { [channelId]: {id: channelId}, }, }, posts: { posts: { [post1.id]: post1, }, }, users: { currentUserId, }, }, } as unknown as GlobalState); const actions = NewPostActions.setChannelReadAndViewed(testStore.dispatch, testStore.getState, post2, newPostMessageProps, false); expect(actions).toMatchObject([ { type: ChannelTypes.INCREMENT_UNREAD_MSG_COUNT, data: { channelId, }, }, { type: ChannelTypes.INCREMENT_TOTAL_MSG_COUNT, data: { channelId, }, }, ]); expect(testStore.getActions()).toEqual([]); }); }); });
655
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/post_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {FileInfo} from '@mattermost/types/files'; import type {Post} from '@mattermost/types/posts'; import {ChannelTypes, SearchTypes} from 'mattermost-redux/action_types'; import * as PostActions from 'mattermost-redux/actions/posts'; import {Posts} from 'mattermost-redux/constants'; import * as Actions from 'actions/post_actions'; import mockStore from 'tests/test_store'; import {Constants, ActionTypes, RHSStates} from 'utils/constants'; import * as PostUtils from 'utils/post_utils'; import type {GlobalState} from 'types/store'; jest.mock('mattermost-redux/actions/posts', () => ({ removeReaction: (...args: any[]) => ({type: 'MOCK_REMOVE_REACTION', args}), addReaction: (...args: any[]) => ({type: 'MOCK_ADD_REACTION', args}), createPost: (...args: any[]) => ({type: 'MOCK_CREATE_POST', args}), createPostImmediately: (...args: any[]) => ({type: 'MOCK_CREATE_POST_IMMEDIATELY', args}), flagPost: (...args: any[]) => ({type: 'MOCK_FLAG_POST', args}), unflagPost: (...args: any[]) => ({type: 'MOCK_UNFLAG_POST', args}), pinPost: (...args: any[]) => ({type: 'MOCK_PIN_POST', args}), unpinPost: (...args: any[]) => ({type: 'MOCK_UNPIN_POST', args}), receivedNewPost: (...args: any[]) => ({type: 'MOCK_RECEIVED_NEW_POST', args}), })); jest.mock('actions/emoji_actions', () => ({ addRecentEmoji: (...args: any[]) => ({type: 'MOCK_ADD_RECENT_EMOJI', args}), addRecentEmojis: (...args: any[]) => ({type: 'MOCK_ADD_RECENT_EMOJIS', args}), })); jest.mock('actions/notification_actions', () => ({ sendDesktopNotification: jest.fn().mockReturnValue({type: 'MOCK_SEND_DESKTOP_NOTIFICATION'}), })); jest.mock('actions/storage', () => { const original = jest.requireActual('actions/storage'); return { ...original, setGlobalItem: (...args: any[]) => ({type: 'MOCK_SET_GLOBAL_ITEM', args}), }; }); jest.mock('utils/user_agent', () => ({ isIosClassic: jest.fn().mockReturnValueOnce(true).mockReturnValue(false), isDesktopApp: jest.fn().mockReturnValue(false), })); const mockMakeGetIsReactionAlreadyAddedToPost = jest.spyOn(PostUtils, 'makeGetIsReactionAlreadyAddedToPost'); const POST_CREATED_TIME = Date.now(); // This mocks the Date.now() function so it returns a constant value global.Date.now = jest.fn(() => POST_CREATED_TIME); const INCREASED_POST_VISIBILITY = {amount: 1, data: 'current_channel_id', type: 'INCREASE_POST_VISIBILITY'}; describe('Actions.Posts', () => { const latestPost = { id: 'latest_post_id', user_id: 'current_user_id', message: 'test msg', channel_id: 'current_channel_id', type: 'normal,', }; const initialState = { entities: { posts: { posts: { [latestPost.id]: latestPost, }, postsInChannel: { current_channel_id: [ {order: [latestPost.id], recent: true}, ], }, postsInThread: {}, messagesHistory: { index: { [Posts.MESSAGE_TYPES.COMMENT]: 0, }, messages: ['test message'], }, }, channels: { currentChannelId: 'current_channel_id', myMembers: { [latestPost.channel_id]: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', }, other_channel_id: { channel_id: 'other_channel_id', user_id: 'current_user_id', roles: 'channel_role', }, }, roles: { [latestPost.channel_id]: [ 'current_channel_id', 'current_user_id', 'channel_role', ], other_channel_id: [ 'other_channel_id', 'current_user_id', 'channel_role', ], }, channels: { current_channel_id: {team_a: 'team_a', id: 'current_channel_id'}, }, manuallyUnread: {}, }, preferences: { myPreferences: { 'display_settings--name_format': { category: 'display_settings', name: 'name_format', user_id: 'current_user_id', value: 'username', }, }, }, teams: { currentTeamId: 'team-a', teams: { team_a: { id: 'team_a', name: 'team-a', displayName: 'Team A', }, team_b: { id: 'team_b', name: 'team-a', displayName: 'Team B', }, }, myMembers: { 'team-a': {roles: 'team_role'}, 'team-b': {roles: 'team_role'}, }, }, users: { currentUserId: 'current_user_id', profiles: { current_user_id: { id: 'current_user_id', username: 'current_username', roles: 'system_role', useAutomaticTimezone: true, automaticTimezone: '', manualTimezone: '', }, }, }, general: { license: {IsLicensed: 'false'}, serverVersion: '5.4.0', config: {PostEditTimeLimit: -1}, }, roles: { roles: { system_role: { permissions: ['edit_post'], }, team_role: { permissions: [], }, channel_role: { permissions: [], }, }, }, emojis: {customEmoji: {}}, search: {results: []}, }, views: { posts: { editingPost: {}, }, rhs: { searchTerms: '', filesSearchExtFilter: [], }, }, } as unknown as GlobalState; test('handleNewPost', async () => { const testStore = mockStore(initialState); const newPost = {id: 'new_post_id', channel_id: 'current_channel_id', message: 'new message', type: Constants.PostTypes.ADD_TO_CHANNEL, user_id: 'some_user_id', create_at: POST_CREATED_TIME} as Post; const msg = {data: {team_a: 'team_a', mentions: ['current_user_id']}}; await testStore.dispatch(Actions.handleNewPost(newPost, msg as any)); expect(testStore.getActions()).toEqual([ { meta: {batch: true}, payload: [ INCREASED_POST_VISIBILITY, PostActions.receivedNewPost(newPost, false), ], type: 'BATCHING_REDUCER.BATCH', }, { type: 'MOCK_SEND_DESKTOP_NOTIFICATION', }, ]); }); test('handleNewPostOtherChannel', async () => { const testStore = mockStore(initialState); const newPost = {id: 'other_channel_post_id', channel_id: 'other_channel_id', message: 'new message in other channel', type: '', user_id: 'other_user_id', create_at: POST_CREATED_TIME} as Post; const msg = {data: {team_b: 'team_b', mentions: ['current_user_id']}}; await testStore.dispatch(Actions.handleNewPost(newPost, msg as any)); expect(testStore.getActions()).toEqual([ { meta: {batch: true}, payload: [ PostActions.receivedNewPost(newPost, false), { type: ChannelTypes.INCREMENT_UNREAD_MSG_COUNT, data: { amount: 1, amountRoot: 0, channelId: 'other_channel_id', fetchedChannelMember: false, onlyMentions: undefined, teamId: undefined, }, }, { type: ChannelTypes.INCREMENT_TOTAL_MSG_COUNT, data: { amount: 1, amountRoot: 0, channelId: 'other_channel_id', }, }, { type: ChannelTypes.INCREMENT_UNREAD_MENTION_COUNT, data: { amount: 1, amountRoot: 0, amountUrgent: 0, channelId: 'other_channel_id', fetchedChannelMember: false, teamId: undefined, }, }, ], type: 'BATCHING_REDUCER.BATCH', }, { type: 'MOCK_SEND_DESKTOP_NOTIFICATION', }, ]); }); test('unsetEditingPost', async () => { // should allow to edit and should fire an action const testStore = mockStore({...initialState}); const {data: dataSet} = await testStore.dispatch((Actions.setEditingPost as any)('latest_post_id', 'test', 'title')); expect(dataSet).toEqual(true); // matches the action to set editingPost expect(testStore.getActions()).toEqual( [{data: {isRHS: false, postId: 'latest_post_id', refocusId: 'test', title: 'title', show: true}, type: ActionTypes.TOGGLE_EDITING_POST}], ); // clear actions testStore.clearActions(); // dispatch action to unset the editingPost const {data: dataUnset} = testStore.dispatch(Actions.unsetEditingPost()); expect(dataUnset).toEqual({show: false}); // matches the action to unset editingPost expect(testStore.getActions()).toEqual( [{data: {show: false}, type: ActionTypes.TOGGLE_EDITING_POST}], ); // editingPost value is empty object, as it should expect(testStore.getState().views.posts.editingPost).toEqual({}); }); test('setEditingPost', async () => { // should allow to edit and should fire an action let testStore = mockStore({...initialState}); const {data} = await testStore.dispatch(Actions.setEditingPost('latest_post_id', 'test', 'title')); expect(data).toEqual(true); expect(testStore.getActions()).toEqual( [{data: {isRHS: false, postId: 'latest_post_id', refocusId: 'test', title: 'title', show: true}, type: ActionTypes.TOGGLE_EDITING_POST}], ); const general = { license: {IsLicensed: 'true'}, serverVersion: '5.4.0', config: {PostEditTimeLimit: -1}, } as unknown as GlobalState['entities']['general']; const withLicenseState = {...initialState}; withLicenseState.entities.general = { ...withLicenseState.entities.general, ...general, }; testStore = mockStore(withLicenseState); const {data: withLicenseData} = await testStore.dispatch(Actions.setEditingPost('latest_post_id', 'test', 'title')); expect(withLicenseData).toEqual(true); expect(testStore.getActions()).toEqual( [{data: {isRHS: false, postId: 'latest_post_id', refocusId: 'test', title: 'title', show: true}, type: ActionTypes.TOGGLE_EDITING_POST}], ); // should not allow edit for pending post const newLatestPost = {...latestPost, pending_post_id: latestPost.id} as Post; const withPendingPostState = {...initialState}; withPendingPostState.entities.posts.posts[latestPost.id] = newLatestPost; testStore = mockStore(withPendingPostState); const {data: withPendingPostData} = await testStore.dispatch(Actions.setEditingPost('latest_post_id', 'test', 'title')); expect(withPendingPostData).toEqual(false); expect(testStore.getActions()).toEqual([]); }); test('searchForTerm', async () => { const testStore = mockStore(initialState); await testStore.dispatch(Actions.searchForTerm('hello')); expect(testStore.getActions()).toEqual([ {terms: 'hello', type: 'UPDATE_RHS_SEARCH_TERMS'}, {state: 'search', type: 'UPDATE_RHS_STATE'}, {terms: '', type: 'UPDATE_RHS_SEARCH_RESULTS_TERMS'}, {isGettingMore: false, type: 'SEARCH_POSTS_REQUEST'}, {isGettingMore: false, type: 'SEARCH_FILES_REQUEST'}, ]); }); describe('createPost', () => { test('no emojis', async () => { const testStore = mockStore(initialState); const newPost = {id: 'new_post_id', channel_id: 'current_channel_id', message: 'new message'} as Post; const newReply = {id: 'reply_post_id', channel_id: 'current_channel_id', message: 'new message', root_id: 'new_post_id'} as Post; const files: FileInfo[] = []; const immediateExpectedState = [{ args: [newPost, files], type: 'MOCK_CREATE_POST_IMMEDIATELY', }, { args: ['draft_current_channel_id', null], type: 'MOCK_SET_GLOBAL_ITEM', }]; await testStore.dispatch(Actions.createPost(newPost, files)); expect(testStore.getActions()).toEqual(immediateExpectedState); const finalExpectedState = [ ...immediateExpectedState, { args: [newReply, files], type: 'MOCK_CREATE_POST', }, { args: ['comment_draft_new_post_id', null], type: 'MOCK_SET_GLOBAL_ITEM', }, ]; await testStore.dispatch(Actions.createPost(newReply, files)); expect(testStore.getActions()).toEqual(finalExpectedState); }); test('with single shorthand emoji', async () => { const testStore = mockStore(initialState); const newPost = {id: 'new_post_id', channel_id: 'current_channel_id', message: 'new message :+1:'} as Post; const files: FileInfo[] = []; const immediateExpectedState = [{ args: [['+1']], type: 'MOCK_ADD_RECENT_EMOJIS', }, { args: [newPost, files], type: 'MOCK_CREATE_POST', }, { args: ['draft_current_channel_id', null], type: 'MOCK_SET_GLOBAL_ITEM', }]; await testStore.dispatch(Actions.createPost(newPost, files)); expect(testStore.getActions()).toEqual(immediateExpectedState); }); test('with single named emoji', async () => { const testStore = mockStore(initialState); const newPost = {id: 'new_post_id', channel_id: 'current_channel_id', message: 'new message :cake:'} as Post; const files: FileInfo[] = []; const immediateExpectedState = [{ args: [['cake']], type: 'MOCK_ADD_RECENT_EMOJIS', }, { args: [newPost, files], type: 'MOCK_CREATE_POST', }, { args: ['draft_current_channel_id', null], type: 'MOCK_SET_GLOBAL_ITEM', }]; await testStore.dispatch(Actions.createPost(newPost, files)); expect(testStore.getActions()).toEqual(immediateExpectedState); }); test('with multiple emoji', async () => { const testStore = mockStore(initialState); const newPost = {id: 'new_post_id', channel_id: 'current_channel_id', message: 'new message :cake: :+1:'} as Post; const files: FileInfo[] = []; const immediateExpectedState = [{ args: [['cake', '+1']], type: 'MOCK_ADD_RECENT_EMOJIS', }, { args: [newPost, files], type: 'MOCK_CREATE_POST', }, { args: ['draft_current_channel_id', null], type: 'MOCK_SET_GLOBAL_ITEM', }]; await testStore.dispatch(Actions.createPost(newPost, files)); expect(testStore.getActions()).toEqual(immediateExpectedState); }); }); describe('submitReaction', () => { describe('addReaction', () => { test('should add reaction when the action is + and the reaction is not added', async () => { const testStore = mockStore(initialState); mockMakeGetIsReactionAlreadyAddedToPost.mockReturnValueOnce(() => false); testStore.dispatch(Actions.submitReaction('post_id_1', '+', 'emoji_name_1')); expect(testStore.getActions()).toEqual([ {args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_ADD_REACTION'}, {args: ['emoji_name_1'], type: 'MOCK_ADD_RECENT_EMOJI'}, ]); }); test('should take no action when the action is + and the reaction has already been added', async () => { const testStore = mockStore(initialState); mockMakeGetIsReactionAlreadyAddedToPost.mockReturnValueOnce(() => true); testStore.dispatch(Actions.submitReaction('post_id_1', '+', 'emoji_name_1')); expect(testStore.getActions()).toEqual([]); }); }); describe('removeReaction', () => { test('should remove reaction when the action is - and the reaction has already been added', async () => { const testStore = mockStore(initialState); mockMakeGetIsReactionAlreadyAddedToPost.mockReturnValueOnce(() => true); testStore.dispatch(Actions.submitReaction('post_id_1', '-', 'emoji_name_1')); expect(testStore.getActions()).toEqual([ {args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_REMOVE_REACTION'}, ]); }); test('should take no action when the action is - and the reaction is not added', async () => { const testStore = mockStore(initialState); mockMakeGetIsReactionAlreadyAddedToPost.mockReturnValueOnce(() => false); testStore.dispatch(Actions.submitReaction('post_id_1', '-', 'emoji_name_1')); expect(testStore.getActions()).toEqual([]); }); }); }); describe('toggleReaction', () => { test('should add reaction when the reaction is not added', async () => { const testStore = mockStore(initialState); mockMakeGetIsReactionAlreadyAddedToPost.mockReturnValueOnce(() => false); testStore.dispatch(Actions.toggleReaction('post_id_1', 'emoji_name_1')); expect(testStore.getActions()).toEqual([ {args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_ADD_REACTION'}, {args: ['emoji_name_1'], type: 'MOCK_ADD_RECENT_EMOJI'}, ]); }); test('should remove reaction when the reaction has already been added', async () => { const testStore = mockStore(initialState); mockMakeGetIsReactionAlreadyAddedToPost.mockReturnValueOnce(() => true); testStore.dispatch(Actions.toggleReaction('post_id_1', 'emoji_name_1')); expect(testStore.getActions()).toEqual([ {args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_REMOVE_REACTION'}, ]); }); }); test('addReaction', async () => { const testStore = mockStore(initialState); await testStore.dispatch(Actions.addReaction('post_id_1', 'emoji_name_1')); expect(testStore.getActions()).toEqual([ {args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_ADD_REACTION'}, {args: ['emoji_name_1'], type: 'MOCK_ADD_RECENT_EMOJI'}, ]); }); test('flagPost', async () => { const rhs = {rhsState: RHSStates.FLAG} as unknown as GlobalState['views']['rhs']; const views = {rhs} as GlobalState['views']; const testStore = mockStore({...initialState, views}); const post = testStore.getState().entities.posts.posts[latestPost.id]; await testStore.dispatch(Actions.flagPost(post.id)); expect(testStore.getActions()).toEqual([ {args: [post.id], type: 'MOCK_FLAG_POST'}, {data: {posts: {[post.id]: post}, order: [post.id]}, type: SearchTypes.RECEIVED_SEARCH_POSTS}, ]); }); test('unflagPost', async () => { const rhs = {rhsState: RHSStates.FLAG} as unknown as GlobalState['views']['rhs']; const views = {rhs} as GlobalState['views']; const testStore = mockStore({views, entities: {...initialState.entities, search: {results: [latestPost.id]}}} as GlobalState); const post = testStore.getState().entities.posts.posts[latestPost.id]; await testStore.dispatch(Actions.unflagPost(post.id)); expect(testStore.getActions()).toEqual([ {args: [post.id], type: 'MOCK_UNFLAG_POST'}, {data: {posts: [], order: []}, type: SearchTypes.RECEIVED_SEARCH_POSTS}, ]); }); test('pinPost', async () => { const rhs = {rhsState: RHSStates.PIN} as unknown as GlobalState['views']['rhs']; const views = {rhs} as GlobalState['views']; const testStore = mockStore({...initialState, views}); const post = testStore.getState().entities.posts.posts[latestPost.id]; await testStore.dispatch(Actions.pinPost(post.id)); expect(testStore.getActions()).toEqual([ {args: [post.id], type: 'MOCK_PIN_POST'}, {data: {posts: {[post.id]: post}, order: [post.id]}, type: SearchTypes.RECEIVED_SEARCH_POSTS}, ]); }); test('unpinPost', async () => { const testStore = mockStore({views: {rhs: {rhsState: RHSStates.PIN}}, entities: {...initialState.entities, search: {results: [latestPost.id]}}} as GlobalState); const post = testStore.getState().entities.posts.posts[latestPost.id]; await testStore.dispatch(Actions.unpinPost(post.id)); expect(testStore.getActions()).toEqual([ {args: [post.id], type: 'MOCK_UNPIN_POST'}, {data: {posts: [], order: []}, type: SearchTypes.RECEIVED_SEARCH_POSTS}, ]); }); });
657
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/status_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {cloneDeep} from 'lodash'; import type {UserProfile} from '@mattermost/types/users'; import {getStatusesByIds} from 'mattermost-redux/actions/users'; import {Preferences} from 'mattermost-redux/constants'; import * as Actions from 'actions/status_actions'; import mockStore from 'tests/test_store'; import type {GlobalState} from 'types/store'; jest.mock('mattermost-redux/actions/users', () => ({ getStatusesByIds: jest.fn(() => { return {type: ''}; }), })); interface CustomMatchers<R = unknown> { arrayContainingExactly(stringArray: string[]): R; } type GreatExpectations = typeof expect & CustomMatchers; describe('actions/status_actions', () => { const initialState = { views: { channel: { postVisibility: {channel_id1: 100, channel_id2: 100}, }, }, entities: { channels: { currentChannelId: 'channel_id1', channels: {channel_id1: {id: 'channel_id1', name: 'channel1', team_id: 'team_id1'}, channel_id2: {id: 'channel_id2', name: 'channel2', team_id: 'team_id1'}}, myMembers: {channel_id1: {channel_id: 'channel_id1', user_id: 'current_user_id'}}, channelsInTeam: {team_id1: ['channel_id1']}, }, general: { config: { EnableCustomEmoji: 'true', EnableCustomUserStatuses: 'true', }, }, teams: { currentTeamId: 'team_id1', teams: { team_id1: { id: 'team_id1', name: 'team1', }, }, }, users: { currentUserId: 'current_user_id', profiles: {user_id2: {id: 'user_id2', username: 'user2'}, user_id3: {id: 'user_id3', username: 'user3'}, user_id4: {id: 'user_id4', username: 'user4'}}, }, posts: { posts: {post_id1: {id: 'post_id1', user_id: 'current_user_id'}, post_id2: {id: 'post_id2', user_id: 'user_id2'}}, postsInChannel: { channel_id1: [ {order: ['post_id1', 'post_id2'], recent: true}, ], channel_id2: [], }, }, preferences: { myPreferences: { [Preferences.CATEGORY_DIRECT_CHANNEL_SHOW + '--user_id3']: {category: Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, name: 'user_id3', value: 'true', user_id: 'current_user_id'}, [Preferences.CATEGORY_DIRECT_CHANNEL_SHOW + '--user_id1']: {category: Preferences.CATEGORY_DIRECT_CHANNEL_SHOW, name: 'user_id1', value: 'false', user_id: 'current_user_id'}, }, }, }, } as unknown as GlobalState; describe('loadStatusesForChannelAndSidebar', () => { test('load statuses with posts in channel and user in sidebar', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForChannelAndSidebar()); expect(getStatusesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['current_user_id', 'user_id2', 'user_id3'])); }); test('load statuses with empty channel and user in sidebar', () => { const state = cloneDeep(initialState); state.entities.channels.currentChannelId = 'channel_id2'; const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForChannelAndSidebar()); expect(getStatusesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['current_user_id', 'user_id3'])); }); test('load statuses with empty channel and no users in sidebar', () => { const state = cloneDeep(initialState); state.entities.channels.currentChannelId = 'channel_id2'; state.entities.preferences.myPreferences = {}; const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForChannelAndSidebar()); expect(getStatusesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['current_user_id'])); }); }); describe('loadStatusesForProfilesList', () => { test('load statuses for users array', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForProfilesList([{id: 'user_id2', username: 'user2'} as UserProfile, {id: 'user_id4', username: 'user4'} as UserProfile])); expect(getStatusesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id2', 'user_id4'])); }); test('load statuses for empty users array', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForProfilesList([])); expect(getStatusesByIds).not.toHaveBeenCalled(); }); test('load statuses for null users array', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForProfilesList(null)); expect(getStatusesByIds).not.toHaveBeenCalled(); }); }); describe('loadStatusesForProfilesMap', () => { test('load statuses for users map', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForProfilesMap({ user_id2: {id: 'user_id2', username: 'user2'} as UserProfile, user_id3: {id: 'user_id3', username: 'user3'} as UserProfile, user_id4: {id: 'user_id4', username: 'user4'} as UserProfile, })); expect(getStatusesByIds).toHaveBeenCalledWith((expect as GreatExpectations).arrayContainingExactly(['user_id2', 'user_id3', 'user_id4'])); }); test('load statuses for empty users map', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForProfilesMap({})); expect(getStatusesByIds).not.toHaveBeenCalled(); }); test('load statuses for null users map', () => { const state = cloneDeep(initialState); const testStore = mockStore(state); testStore.dispatch(Actions.loadStatusesForProfilesMap(null)); expect(getStatusesByIds).not.toHaveBeenCalled(); }); }); });
659
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/storage.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Actions from 'actions/storage'; import configureStore from 'store'; describe('Actions.Storage', () => { let store = configureStore(); beforeEach(async () => { store = await configureStore(); }); it('setItem', async () => { store.dispatch(Actions.setItem('test', 'value')); expect(store.getState().storage.storage.unknown_test.value).toBe('value'); expect(typeof store.getState().storage.storage.unknown_test.timestamp).not.toBe('undefined'); }); it('removeItem', async () => { store.dispatch(Actions.setItem('test1', 'value1')); store.dispatch(Actions.setItem('test2', 'value2')); expect(store.getState().storage.storage.unknown_test1.value).toBe('value1'); expect(store.getState().storage.storage.unknown_test2.value).toBe('value2'); store.dispatch(Actions.removeItem('test1')); expect(typeof store.getState().storage.storage.unknown_test1).toBe('undefined'); expect(store.getState().storage.storage.unknown_test2.value).toBe('value2'); }); it('setGlobalItem', async () => { store.dispatch(Actions.setGlobalItem('test', 'value')); expect(store.getState().storage.storage.test.value).toBe('value'); expect(typeof store.getState().storage.storage.test.timestamp).not.toBe('undefined'); }); it('removeGlobalItem', async () => { store.dispatch(Actions.setGlobalItem('test1', 'value1')); store.dispatch(Actions.setGlobalItem('test2', 'value2')); expect(store.getState().storage.storage.test1.value).toBe('value1'); expect(store.getState().storage.storage.test2.value).toBe('value2'); store.dispatch(Actions.removeGlobalItem('test1')); expect(typeof store.getState().storage.storage.test1).toBe('undefined'); expect(store.getState().storage.storage.test2.value).toBe('value2'); }); it('actionOnGlobalItemsWithPrefix', async () => { const touchedPairs: Array<[string, number]> = []; store.dispatch(Actions.setGlobalItem('prefix_test1', 1)); store.dispatch(Actions.setGlobalItem('prefix_test2', 2)); store.dispatch(Actions.setGlobalItem('not_prefix_test', 3)); store.dispatch(Actions.actionOnGlobalItemsWithPrefix( 'prefix', (key, value) => touchedPairs.push([key, value]), )); expect(touchedPairs).toEqual([['prefix_test1', 1], ['prefix_test2', 2]]); }); }); describe('cleanLocalStorage', () => { beforeAll(() => { localStorage.clear(); }); afterEach(() => { localStorage.clear(); }); test('should clear keys used for user profile colors in compact mode', () => { const keys = [ 'harrison-#0a111f', 'harrison-#090a0b', 'jira-#0a111f', 'jira-#090a0b', 'github-#090a0b', ]; for (const key of keys) { localStorage.setItem(key, key); } Actions.cleanLocalStorage(); expect(localStorage.length).toBe(0); }); test('should not clear keys used for other things', () => { const keys = [ 'theme', 'was_logged_in', '__landingPageSeen__', 'emoji-mart.frequently', ]; for (const key of keys) { localStorage.setItem(key, key); } Actions.cleanLocalStorage(); expect(localStorage.length).toBe(keys.length); }); });
661
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/team_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as channelActions from 'mattermost-redux/actions/channels'; import * as TeamActions from 'mattermost-redux/actions/teams'; import * as userActions from 'mattermost-redux/actions/users'; import * as Actions from 'actions/team_actions'; import configureStore from 'tests/test_store'; import {getHistory} from 'utils/browser_history'; import {TestHelper} from 'utils/test_helper'; jest.mock('mattermost-redux/actions/teams', () => ({ ...jest.requireActual('mattermost-redux/actions/teams'), addUsersToTeamGracefully: jest.fn(() => { return { type: 'ADD_USER', }; }), removeUserFromTeam: jest.fn(() => { return { type: 'REMOVE_USER_FROM_TEAM', }; }), getTeamStats: jest.fn(() => { return { type: 'GET_TEAM_STATS', }; }), addUserToTeam: jest.fn(() => { return { type: 'ADD_USERS_TO_TEAM', data: { team_id: 'teamId', }, }; }), getTeam: jest.fn(() => { return { type: 'GET_TEAM', }; }), })); jest.mock('mattermost-redux/actions/channels', () => ({ viewChannel: jest.fn(() => { return { type: 'VIEW_CHANNEL', }; }), getChannelStats: jest.fn(() => { return { type: 'GET_CHANNEL_STAT', }; }), })); jest.mock('mattermost-redux/actions/users', () => ({ getUser: jest.fn(() => { return { type: 'GET_USER', }; }), })); describe('Actions.Team', () => { const currentChannelId = 'currentChannelId'; const initialState = { entities: { channels: { currentChannelId, manuallyUnread: {}, }, }, }; describe('switchTeam', () => { test('should switch to a team by its URL if no team is provided', () => { const testStore = configureStore(initialState); testStore.dispatch(Actions.switchTeam('/test')); expect(getHistory().push).toHaveBeenCalledWith('/test'); expect(testStore.getActions()).toEqual([]); }); test('should select a team without changing URL if a team is provided', () => { const testStore = configureStore(initialState); const team = TestHelper.getTeamMock(); testStore.dispatch(Actions.switchTeam('/test', team)); expect(getHistory().push).not.toHaveBeenCalled(); expect(testStore.getActions()).toContainEqual(TeamActions.selectTeam(team)); }); }); test('addUsersToTeam', () => { const testStore = configureStore(initialState); testStore.dispatch(Actions.addUsersToTeam('teamId', ['123', '1234'])); expect(TeamActions.addUsersToTeamGracefully).toHaveBeenCalledWith('teamId', ['123', '1234']); }); test('removeUserFromTeamAndGetStats', async () => { const testStore = configureStore(initialState); await testStore.dispatch(Actions.removeUserFromTeamAndGetStats('teamId', '123')); expect(userActions.getUser).toHaveBeenCalledWith('123'); expect(TeamActions.getTeamStats).toHaveBeenCalledWith('teamId'); expect(channelActions.getChannelStats).toHaveBeenCalledWith(currentChannelId); }); test('addUserToTeam', async () => { const testStore = configureStore(initialState); await testStore.dispatch(Actions.addUserToTeam('teamId', 'userId')); expect(TeamActions.addUserToTeam).toHaveBeenCalledWith('teamId', 'userId'); expect(TeamActions.getTeam).toHaveBeenCalledWith('teamId'); }); });
665
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/user_actions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Channel, ChannelMembership, ChannelMessageCount} from '@mattermost/types/channels'; import type {Post} from '@mattermost/types/posts'; import type {Team, TeamMembership} from '@mattermost/types/teams'; import type {UserProfile} from '@mattermost/types/users'; import {Preferences, General} from 'mattermost-redux/constants'; import {CategoryTypes} from 'mattermost-redux/constants/channel_categories'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import * as UserActions from 'actions/user_actions'; import store from 'stores/redux_store'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; import mockStore from 'tests/test_store'; import type {GlobalState} from 'types/store'; jest.mock('mattermost-redux/actions/users', () => { const original = jest.requireActual('mattermost-redux/actions/users'); return { ...original, searchProfiles: (...args: any[]) => ({type: 'MOCK_SEARCH_PROFILES', args}), getProfilesInTeam: (...args: any[]) => ({type: 'MOCK_GET_PROFILES_IN_TEAM', args}), getProfilesInChannel: (...args: any[]) => ({type: 'MOCK_GET_PROFILES_IN_CHANNEL', args, data: [{id: 'user_1'}]}), getProfilesInGroupChannels: (...args: any[]) => ({type: 'MOCK_GET_PROFILES_IN_GROUP_CHANNELS', args}), getStatusesByIds: (...args: any[]) => ({type: 'MOCK_GET_STATUSES_BY_ID', args}), }; }); jest.mock('mattermost-redux/actions/teams', () => { const original = jest.requireActual('mattermost-redux/actions/teams'); return { ...original, getTeamMembersByIds: (...args: any[]) => ({type: 'MOCK_GET_TEAM_MEMBERS_BY_IDS', args}), }; }); jest.mock('mattermost-redux/actions/channels', () => { const original = jest.requireActual('mattermost-redux/actions/channels'); return { ...original, getChannelMembersByIds: (...args: any[]) => ({type: 'MOCK_GET_CHANNEL_MEMBERS_BY_IDS', args}), }; }); jest.mock('mattermost-redux/actions/preferences', () => { const original = jest.requireActual('mattermost-redux/actions/preferences'); return { ...original, deletePreferences: (...args: any[]) => ({type: 'MOCK_DELETE_PREFERENCES', args}), savePreferences: (...args: any[]) => ({type: 'MOCK_SAVE_PREFERENCES', args}), }; }); jest.mock('stores/redux_store', () => { return { dispatch: jest.fn(), getState: jest.fn(), }; }); jest.mock('actions/telemetry_actions.jsx', () => { const original = jest.requireActual('actions/telemetry_actions.jsx'); return { ...original, trackEvent: jest.fn(), }; }); describe('Actions.User', () => { const initialState: GlobalState = { entities: { channels: { currentChannelId: 'current_channel_id', myMembers: { current_channel_id: { channel_id: 'current_channel_id', user_id: 'current_user_id', roles: 'channel_role', mention_count: 1, msg_count: 9, } as ChannelMembership, }, channels: { current_channel_id: { team_id: 'team_1', } as Channel, }, channelsInTeam: { team_1: ['current_channel_id'], }, messageCounts: { current_channel_id: {total: 10} as ChannelMessageCount, }, membersInChannel: { current_channel_id: { current_user_id: {channel_id: 'current_user_id'} as ChannelMembership, }, }, } as unknown as GlobalState['entities']['channels'], general: { config: {}, } as GlobalState['entities']['general'], preferences: { myPreferences: { 'theme--team_1': { category: 'theme', name: 'team_1', user_id: 'current_user_id', value: JSON.stringify(Preferences.THEMES.indigo), }, }, }, teams: { currentTeamId: 'team_1', teams: { team_1: { id: 'team_1', name: 'team-1', display_name: 'Team 1', } as Team, team_2: { id: 'team_2', name: 'team-2', display_name: 'Team 2', } as Team, }, myMembers: { team_1: {roles: 'team_role'} as TeamMembership, team_2: {roles: 'team_role'} as TeamMembership, }, membersInTeam: { team_1: { current_user_id: {id: 'current_user_id'} as unknown as TeamMembership, }, team_2: { current_user_id: {id: 'current_user_id'} as unknown as TeamMembership, }, }, } as unknown as GlobalState['entities']['teams'], users: { currentUserId: 'current_user_id', profilesInChannel: { group_channel_2: ['user_1', 'user_2'], }, } as unknown as GlobalState['entities']['users'], posts: { posts: { sample_post_id: { id: 'sample_post_id', } as Post, }, postsInChannel: { current_channel_id: [ { order: ['sample_post_id'], }, ]}, } as unknown as GlobalState['entities']['posts'], } as unknown as GlobalState['entities'], storage: { storage: {}, initialized: true, }, views: { channel: { } as GlobalState['views']['channel'], channelSidebar: { unreadFilterEnabled: false, } as GlobalState['views']['channelSidebar'], } as GlobalState['views'], } as GlobalState; test('loadProfilesAndStatusesInChannel', async () => { const testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadProfilesAndStatusesInChannel('channel_1', 0, 60, 'status', {})); const actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(['channel_1', 0, 60, 'status', {}]); expect(actualActions[0].type).toEqual('MOCK_GET_PROFILES_IN_CHANNEL'); expect(actualActions[1].args).toEqual([['user_1']]); expect(actualActions[1].type).toEqual('MOCK_GET_STATUSES_BY_ID'); }); test('loadProfilesAndTeamMembers', async () => { const expectedActions = [{type: 'MOCK_GET_PROFILES_IN_TEAM', args: ['team_1', 0, 60, '', {}]}]; let testStore = mockStore({} as GlobalState); await testStore.dispatch(UserActions.loadProfilesAndTeamMembers(0, 60, 'team_1', {})); let actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(expectedActions[0].args); expect(actualActions[0].type).toEqual(expectedActions[0].type); testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadProfilesAndTeamMembers(0, 60, '', {})); actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(expectedActions[0].args); expect(actualActions[0].type).toEqual(expectedActions[0].type); }); test('loadProfilesAndReloadChannelMembers', async () => { const expectedActions = [{type: 'MOCK_GET_PROFILES_IN_CHANNEL', args: ['current_channel_id', 0, 60, 'sort', {}]}]; const testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadProfilesAndReloadChannelMembers(0, 60, 'current_channel_id', 'sort', {})); const actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(expectedActions[0].args); expect(actualActions[0].type).toEqual(expectedActions[0].type); }); test('loadProfilesAndTeamMembersAndChannelMembers', async () => { const expectedActions = [{type: 'MOCK_GET_PROFILES_IN_CHANNEL', args: ['current_channel_id', 0, 60, '', undefined]}]; let testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadProfilesAndTeamMembersAndChannelMembers(0, 60, 'team_1', 'current_channel_id')); let actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(expectedActions[0].args); expect(actualActions[0].type).toEqual(expectedActions[0].type); testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadProfilesAndTeamMembersAndChannelMembers(0, 60, '', '')); actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(expectedActions[0].args); expect(actualActions[0].type).toEqual(expectedActions[0].type); }); test('loadTeamMembersForProfilesList', async () => { const expectedActions = [{args: ['team_1', ['other_user_id']], type: 'MOCK_GET_TEAM_MEMBERS_BY_IDS'}]; // should call getTeamMembersByIds since 'other_user_id' is not loaded yet let testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersForProfilesList( [{id: 'other_user_id'} as UserProfile], 'team_1', )); expect(testStore.getActions()).toEqual(expectedActions); // should not call getTeamMembersByIds since 'current_user_id' is already loaded testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersForProfilesList( [{id: 'current_user_id'} as UserProfile], 'team_1', )); expect(testStore.getActions()).toEqual([]); // should call getTeamMembersByIds when reloadAllMembers = true even though 'current_user_id' is already loaded testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersForProfilesList( [{id: 'current_user_id'} as UserProfile], 'team_1', true, )); expect(testStore.getActions()).toEqual([{args: ['team_1', ['current_user_id']], type: 'MOCK_GET_TEAM_MEMBERS_BY_IDS'}]); // should not call getTeamMembersByIds since no or empty profile is passed testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersForProfilesList([], 'team_1')); expect(testStore.getActions()).toEqual([]); }); test('loadTeamMembersAndChannelMembersForProfilesList', async () => { const expectedActions = [ {args: ['team_1', ['other_user_id']], type: 'MOCK_GET_TEAM_MEMBERS_BY_IDS'}, {args: ['current_channel_id', ['other_user_id']], type: 'MOCK_GET_CHANNEL_MEMBERS_BY_IDS'}, ]; // should call getTeamMembersByIds and getChannelMembersByIds since 'other_user_id' is not loaded yet let testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersAndChannelMembersForProfilesList( [{id: 'other_user_id'} as UserProfile], 'team_1', 'current_channel_id', )); expect(testStore.getActions()).toEqual(expectedActions); // should not call getTeamMembersByIds/getChannelMembersByIds since 'current_user_id' is already loaded testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersForProfilesList( [{id: 'current_user_id'} as UserProfile], 'team_1', )); expect(testStore.getActions()).toEqual([]); // should not call getTeamMembersByIds/getChannelMembersByIds since no or empty profile is passed testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadTeamMembersForProfilesList([], 'team_1')); expect(testStore.getActions()).toEqual([]); }); test('loadChannelMembersForProfilesList', async () => { const expectedActions = [{args: ['current_channel_id', ['other_user_id']], type: 'MOCK_GET_CHANNEL_MEMBERS_BY_IDS'}]; // should call getChannelMembersByIds since 'other_user_id' is not loaded yet let testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadChannelMembersForProfilesList( [{id: 'other_user_id'} as UserProfile], 'current_channel_id', )); expect(testStore.getActions()).toEqual(expectedActions); // should not call getChannelMembersByIds since 'current_user_id' is already loaded testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadChannelMembersForProfilesList( [{id: 'current_user_id'} as UserProfile], 'current_channel_id', )); expect(testStore.getActions()).toEqual([]); // should not call getChannelMembersByIds since no or empty profile is passed testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadChannelMembersForProfilesList([], 'current_channel_id')); expect(testStore.getActions()).toEqual([]); }); test('loadProfilesForGroupChannels', async () => { const mockedGroupChannels = [{id: 'group_channel_1'}, {id: 'group_channel_2'}] as Channel[]; // as users in group_channel_2 are already loaded, it should only try to load group_channel_1 const expectedActions = [{args: [['group_channel_1']], type: 'MOCK_GET_PROFILES_IN_GROUP_CHANNELS'}]; const testStore = mockStore(initialState); await testStore.dispatch(UserActions.loadProfilesForGroupChannels(mockedGroupChannels)); expect(testStore.getActions()).toEqual(expectedActions); }); test('searchProfilesAndChannelMembers', async () => { const expectedActions = [{type: 'MOCK_SEARCH_PROFILES', args: ['term', {}]}]; const testStore = mockStore(initialState); await testStore.dispatch(UserActions.searchProfilesAndChannelMembers('term')); const actualActions = testStore.getActions(); expect(actualActions[0].args).toEqual(expectedActions[0].args); expect(actualActions[0].type).toEqual(expectedActions[0].type); }); describe('getGMsForLoading', () => { const gmChannel1 = {id: 'gmChannel1', type: General.GM_CHANNEL, delete_at: 0}; const gmChannel2 = {id: 'gmChannel2', type: General.GM_CHANNEL, delete_at: 0}; const dmsCategory = {id: 'dmsCategory', type: CategoryTypes.DIRECT_MESSAGES, channel_ids: [gmChannel1.id, gmChannel2.id]}; const baseState = { ...initialState, entities: { ...initialState.entities, channelCategories: { ...initialState.entities.channelCategories, byId: { dmsCategory, }, orderByTeam: { [initialState.entities.teams.currentTeamId]: [dmsCategory.id], }, }, channels: { ...initialState.entities.channels, channels: { ...initialState.entities.channels, gmChannel1, gmChannel2, }, myMembers: { [gmChannel1.id]: {last_viewed_at: 1000}, [gmChannel2.id]: {last_viewed_at: 2000}, }, }, preferences: { ...initialState.entities.preferences, myPreferences: { ...initialState.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '10'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'true'}, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel2.id)]: {value: 'true'}, }, }, }, }; test('should not return autoclosed GMs', () => { let state = baseState; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel1, gmChannel2]); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '1'}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel2]); state = { ...state, entities: { ...state.entities, channels: { ...state.entities.channels, myMembers: { ...state.entities.channels.myMembers, [gmChannel1.id]: {last_viewed_at: 3000}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel1]); }); test('should not return manually closed GMs', () => { let state = baseState; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel1, gmChannel2]); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel1.id)]: {value: 'false'}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel2]); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel2.id)]: {value: 'false'}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([]); }); test('should return GMs that are in custom categories, even if they would be automatically hidden in the DMs category', () => { const gmChannel3 = {id: 'gmChannel3', type: General.GM_CHANNEL, delete_at: 0}; const customCategory = {id: 'customCategory', type: CategoryTypes.CUSTOM, channel_ids: [gmChannel3.id]}; let state = { ...baseState, entities: { ...baseState.entities, channelCategories: { ...baseState.entities.channelCategories, byId: { ...baseState.entities.channelCategories.byId, customCategory, }, orderByTeam: { ...baseState.entities.channelCategories.orderByTeam, [baseState.entities.teams.currentTeamId]: [customCategory.id, dmsCategory.id], }, }, channels: { ...baseState.entities.channels, channels: { ...baseState.entities.channels.channels, gmChannel3, }, myMembers: { ...baseState.entities.channels.myMembers, [gmChannel3.id]: {last_viewed_at: 500}, }, }, preferences: { ...baseState.entities.preferences, myPreferences: { ...baseState.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel3.id)]: {value: 'true'}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel3, gmChannel1, gmChannel2]); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '1'}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel3, gmChannel2]); state = { ...state, entities: { ...state.entities, preferences: { ...state.entities.preferences, myPreferences: { ...state.entities.preferences.myPreferences, [getPreferenceKey(Preferences.CATEGORY_SIDEBAR_SETTINGS, Preferences.LIMIT_VISIBLE_DMS_GMS)]: {value: '0'}, }, }, }, }; expect(UserActions.getGMsForLoading(state as unknown as GlobalState)).toEqual([gmChannel3]); }); }); test('Should call p-queue APIs on loadProfilesForGM', async () => { const gmChannel = {id: 'gmChannel', type: General.GM_CHANNEL, team_id: '', delete_at: 0}; UserActions.queue.add = jest.fn().mockReturnValue(jest.fn()); UserActions.queue.onEmpty = jest.fn(); const user = TestHelper.fakeUser(); const profiles = { current_user_id: { ...user, id: 'current_user_id', }, }; const channels = { [gmChannel.id]: gmChannel, }; const channelsInTeam = { '': [gmChannel.id], }; const myMembers = { [gmChannel.id]: {}, }; const dmsCategory = {id: 'dmsCategory', type: CategoryTypes.DIRECT_MESSAGES, channel_ids: [gmChannel.id]}; const state = { entities: { users: { currentUserId: 'current_user_id', profiles, statuses: {}, profilesInChannel: { [gmChannel.id]: new Set(['current_user_id']), }, }, teams: { currentTeamId: 'team_1', }, posts: { posts: { post_id: {id: 'post_id'}, }, postsInChannel: {}, }, channelCategories: { byId: { dmsCategory, }, orderByTeam: { team_1: [dmsCategory.id], }, }, channels: { channels, channelsInTeam, messageCounts: {}, myMembers, }, preferences: { myPreferences: { [getPreferenceKey(Preferences.CATEGORY_GROUP_CHANNEL_SHOW, gmChannel.id)]: {value: 'true'}, }, }, general: { config: {}, }, }, storage: { storage: {}, }, views: { channel: { lastViewedChannel: null, }, channelSidebar: { unreadFilterEnabled: false, }, }, } as unknown as GlobalState; const testStore = mockStore(state); store.getState.mockImplementation(testStore.getState); await UserActions.loadProfilesForGM(); expect(UserActions.queue.onEmpty).toHaveBeenCalled(); expect(UserActions.queue.add).toHaveBeenCalled(); }); });
675
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/channel_sidebar.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 {Channel, ChannelMembership} from '@mattermost/types/channels'; import {insertWithoutDuplicates} from 'mattermost-redux/utils/array_utils'; import configureStore from 'store'; import * as Actions from './channel_sidebar'; describe('adjustTargetIndexForMove', () => { const channelIds = ['one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven']; const initialState = { entities: { channelCategories: { byId: { category1: { id: 'category1', channel_ids: channelIds, sorting: CategorySorting.Manual, }, }, }, channels: { channels: { new: {id: 'new', delete_at: 0}, one: {id: 'one', delete_at: 0}, twoDeleted: {id: 'twoDeleted', delete_at: 1}, three: {id: 'three', delete_at: 0}, four: {id: 'four', delete_at: 0}, fiveDeleted: {id: 'fiveDeleted', delete_at: 1}, six: {id: 'six', delete_at: 0}, seven: {id: 'seven', delete_at: 0}, }, }, }, }; describe('should place newly added channels correctly in the category', () => { const testCases = [ { inChannelIds: ['new', 'one', 'three', 'four', 'six', 'seven'], expectedChannelIds: ['new', 'one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['one', 'new', 'three', 'four', 'six', 'seven'], expectedChannelIds: ['one', 'new', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['one', 'three', 'new', 'four', 'six', 'seven'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'new', 'four', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['one', 'three', 'four', 'new', 'six', 'seven'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'four', 'new', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['one', 'three', 'four', 'six', 'new', 'seven'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'new', 'seven'], }, { inChannelIds: ['one', 'three', 'four', 'six', 'seven', 'new'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven', 'new'], }, ]; for (let i = 0; i < testCases.length; i++) { const testCase = testCases[i]; test('at ' + i, async () => { const store = configureStore(initialState); const targetIndex = testCase.inChannelIds.indexOf('new'); const newIndex = Actions.adjustTargetIndexForMove(store.getState(), 'category1', ['new'], targetIndex, 'new'); const actualChannelIds = insertWithoutDuplicates(channelIds, 'new', newIndex); expect(actualChannelIds).toEqual(testCase.expectedChannelIds); }); } }); describe('should be able to move channels forwards', () => { const testCases = [ { inChannelIds: ['one', 'three', 'four', 'six', 'seven'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['three', 'one', 'four', 'six', 'seven'], expectedChannelIds: ['twoDeleted', 'three', 'one', 'four', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['three', 'four', 'one', 'six', 'seven'], expectedChannelIds: ['twoDeleted', 'three', 'four', 'one', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['three', 'four', 'six', 'one', 'seven'], expectedChannelIds: ['twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'one', 'seven'], }, { inChannelIds: ['three', 'four', 'six', 'seven', 'one'], expectedChannelIds: ['twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven', 'one'], }, ]; for (let i = 0; i < testCases.length; i++) { const testCase = testCases[i]; test('at ' + i, async () => { const store = configureStore(initialState); const targetIndex = testCase.inChannelIds.indexOf('one'); const newIndex = Actions.adjustTargetIndexForMove(store.getState(), 'category1', ['one'], targetIndex, 'one'); const actualChannelIds = insertWithoutDuplicates(channelIds, 'one', newIndex); expect(actualChannelIds).toEqual(testCase.expectedChannelIds); }); } }); describe('should be able to move channels backwards', () => { const testCases = [ { inChannelIds: ['one', 'three', 'four', 'six', 'seven'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six', 'seven'], }, { inChannelIds: ['one', 'three', 'four', 'seven', 'six'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'four', 'seven', 'fiveDeleted', 'six'], }, { inChannelIds: ['one', 'three', 'seven', 'four', 'six'], expectedChannelIds: ['one', 'twoDeleted', 'three', 'seven', 'four', 'fiveDeleted', 'six'], }, { inChannelIds: ['one', 'seven', 'three', 'four', 'six'], expectedChannelIds: ['one', 'seven', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six'], }, { inChannelIds: ['seven', 'one', 'three', 'four', 'six'], expectedChannelIds: ['seven', 'one', 'twoDeleted', 'three', 'four', 'fiveDeleted', 'six'], }, ]; for (let i = 0; i < testCases.length; i++) { const testCase = testCases[i]; test('at ' + i, async () => { const store = configureStore(initialState); const targetIndex = testCase.inChannelIds.indexOf('seven'); const newIndex = Actions.adjustTargetIndexForMove(store.getState(), 'category1', ['seven'], targetIndex, 'seven'); const actualChannelIds = insertWithoutDuplicates(channelIds, 'seven', newIndex); expect(actualChannelIds).toEqual(testCase.expectedChannelIds); }); } }); }); describe('multiSelectChannelTo', () => { const channelIds = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']; const initialState = { entities: { users: { currentUserId: 'user', }, channelCategories: { byId: { category1: { id: 'category1', channel_ids: channelIds.map((id) => `category1_${id}`), sorting: CategorySorting.Manual, }, category2: { id: 'category2', channel_ids: channelIds.map((id) => `category2_${id}`), sorting: CategorySorting.Manual, }, }, orderByTeam: { team1: ['category1', 'category2'], }, }, channels: { currentChannelId: 'category1_one', channels: { ...channelIds.reduce((init: {[key: string]: Partial<Channel>}, val) => { init[`category1_${val}`] = {id: `category1_${val}`, delete_at: 0}; return init; }, {}), ...channelIds.reduce((init: {[key: string]: Partial<Channel>}, val) => { init[`category2_${val}`] = {id: `category2_${val}`, delete_at: 0}; return init; }, {}), }, myMembers: { ...channelIds.reduce((init: {[key: string]: Partial<ChannelMembership>}, val) => { init[`category1_${val}`] = {channel_id: `category1_${val}`, user_id: 'user'}; return init; }, {}), ...channelIds.reduce((init: {[key: string]: Partial<ChannelMembership>}, val) => { init[`category2_${val}`] = {channel_id: `category2_${val}`, user_id: 'user'}; return init; }, {}), }, channelsInTeam: { team1: channelIds.map((id) => `category1_${id}`).concat(channelIds.map((id) => `category2_${id}`)), }, }, teams: { currentTeamId: 'team1', }, }, views: { channelSidebar: { multiSelectedChannelIds: [], lastSelectedChannel: '', }, }, }; test('should only select current channel if is selected ID and none other are selected', () => { const store = configureStore(initialState); store.dispatch(Actions.multiSelectChannelTo('category1_one')); expect(store.getState().views.channelSidebar.multiSelectedChannelIds).toEqual(['category1_one']); }); test('should select group of channels in ascending order', () => { const store = configureStore({ ...initialState, views: { channelSidebar: { multiSelectedChannelIds: ['category1_two'], lastSelectedChannel: 'category1_two', }, }, }); store.dispatch(Actions.multiSelectChannelTo('category1_seven')); expect(store.getState().views.channelSidebar.multiSelectedChannelIds).toEqual(['category1_two', 'category1_three', 'category1_four', 'category1_five', 'category1_six', 'category1_seven']); }); test('should select group of channels in descending order and sort by ascending', () => { const store = configureStore({ ...initialState, views: { channelSidebar: { multiSelectedChannelIds: ['category1_five'], lastSelectedChannel: 'category1_five', }, }, }); store.dispatch(Actions.multiSelectChannelTo('category1_one')); expect(store.getState().views.channelSidebar.multiSelectedChannelIds).toEqual(['category1_one', 'category1_two', 'category1_three', 'category1_four', 'category1_five']); }); test('should select group of channels where some other channels were already selected', () => { const store = configureStore({ ...initialState, views: { channelSidebar: { multiSelectedChannelIds: ['category1_five', 'category2_six', 'category2_three'], lastSelectedChannel: 'category1_five', }, }, }); store.dispatch(Actions.multiSelectChannelTo('category1_one')); expect(store.getState().views.channelSidebar.multiSelectedChannelIds).toEqual(['category1_one', 'category1_two', 'category1_three', 'category1_four', 'category1_five']); }); test('should select group of channels where some other channels were already selected but in new selection', () => { const store = configureStore({ ...initialState, views: { channelSidebar: { multiSelectedChannelIds: ['category1_five', 'category1_three', 'category1_one'], lastSelectedChannel: 'category1_five', }, }, }); store.dispatch(Actions.multiSelectChannelTo('category1_one')); expect(store.getState().views.channelSidebar.multiSelectedChannelIds).toEqual(['category1_one', 'category1_two', 'category1_three', 'category1_four', 'category1_five']); }); test('should select group of channels across categories', () => { const store = configureStore({ ...initialState, views: { channelSidebar: { multiSelectedChannelIds: ['category1_five'], lastSelectedChannel: 'category1_five', }, }, }); store.dispatch(Actions.multiSelectChannelTo('category2_two')); expect(store.getState().views.channelSidebar.multiSelectedChannelIds).toEqual(['category1_five', 'category1_six', 'category1_seven', 'category2_one', 'category2_two']); }); });
680
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/drafts.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {Client4} from 'mattermost-redux/client'; import {Posts, Preferences} from 'mattermost-redux/constants'; import {getPreferenceKey} from 'mattermost-redux/utils/preference_utils'; import {setGlobalItem} from 'actions/storage'; import mockStore from 'tests/test_store'; import {StoragePrefixes} from 'utils/constants'; import type {PostDraft} from 'types/store/draft'; import {removeDraft, setGlobalDraftSource, updateDraft} from './drafts'; jest.mock('mattermost-redux/client', () => { const original = jest.requireActual('mattermost-redux/client'); return { ...original, Client4: { ...original.Client4, deleteDraft: jest.fn().mockResolvedValue([]), upsertDraft: jest.fn().mockResolvedValue([]), }, }; }); jest.mock('actions/storage', () => { const original = jest.requireActual('actions/storage'); return { ...original, setGlobalItem: (...args: any) => ({type: 'MOCK_SET_GLOBAL_ITEM', args}), actionOnGlobalItemsWithPrefix: (...args: any) => ({type: 'MOCK_ACTION_ON_GLOBAL_ITEMS_WITH_PREFIX', args}), }; }); const rootId = 'fc234c34c23'; const currentUserId = '34jrnfj43'; const teamId = '4j5nmn4j3'; const channelId = '4j5j4k3k34j4'; const latestPostId = 'latestPostId'; const enabledSyncedDraftsKey = getPreferenceKey(Preferences.CATEGORY_ADVANCED_SETTINGS, Preferences.ADVANCED_SYNC_DRAFTS); describe('draft actions', () => { const initialState = { entities: { posts: { posts: { [latestPostId]: { id: latestPostId, user_id: currentUserId, message: 'test msg', channel_id: channelId, root_id: rootId, create_at: 42, }, [rootId]: { id: rootId, user_id: currentUserId, message: 'root msg', channel_id: channelId, root_id: '', create_at: 2, }, }, postsInChannel: { [channelId]: [ {order: [latestPostId], recent: true}, ], }, postsInThread: { [rootId]: [latestPostId], }, messagesHistory: { index: { [Posts.MESSAGE_TYPES.COMMENT]: 0, }, messages: ['test message'], }, }, preferences: { myPreferences: { [enabledSyncedDraftsKey]: {value: 'true'}, }, }, users: { currentUserId, profiles: { [currentUserId]: {id: currentUserId}, }, }, teams: { currentTeamId: teamId, }, emojis: { customEmoji: {}, }, general: { config: { EnableCustomEmoji: 'true', AllowSyncedDrafts: 'true', }, }, }, storage: { storage: { [`${StoragePrefixes.COMMENT_DRAFT}${rootId}`]: { value: { message: '', fileInfos: [], uploadsInProgress: [], channelId, rootId, }, timestamp: new Date(), }, }, }, websocket: { connectionId: '', }, }; let store: any; const key = StoragePrefixes.DRAFT + channelId; const upsertDraftSpy = jest.spyOn(Client4, 'upsertDraft'); const deleteDraftSpy = jest.spyOn(Client4, 'deleteDraft'); beforeEach(() => { store = mockStore(initialState); }); describe('updateDraft', () => { const draft = {message: 'test', channelId, fileInfos: [{id: 1}], uploadsInProgress: [2, 3]} as unknown as PostDraft; it('calls setGlobalItem action correctly', async () => { jest.useFakeTimers(); jest.setSystemTime(42); await store.dispatch(updateDraft(key, draft, '', false)); const testStore = mockStore(initialState); const expectedKey = StoragePrefixes.DRAFT + channelId; testStore.dispatch(setGlobalItem(expectedKey, { ...draft, createAt: 42, updateAt: 42, })); testStore.dispatch(setGlobalDraftSource(expectedKey, false)); expect(store.getActions()).toEqual(testStore.getActions()); jest.useRealTimers(); }); it('calls upsertDraft correctly', async () => { await store.dispatch(updateDraft(key, draft, '', true)); expect(upsertDraftSpy).toHaveBeenCalled(); }); }); describe('removeDraft', () => { it('calls setGlobalItem action correctly', async () => { await store.dispatch(removeDraft(key, channelId)); const testStore = mockStore(initialState); testStore.dispatch(setGlobalItem(StoragePrefixes.DRAFT + channelId, { message: '', fileInfos: [], uploadsInProgress: [], })); expect(store.getActions()).toEqual(testStore.getActions()); }); it('calls upsertDraft correctly', async () => { await store.dispatch(removeDraft(key, channelId)); expect(deleteDraftSpy).toHaveBeenCalled(); }); }); });
683
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/lhs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {MockStoreEnhanced} from 'redux-mock-store'; import type {DispatchFunc} from 'mattermost-redux/types/actions'; import {close, open, toggle} from 'actions/views/lhs'; import configureStore from 'store'; import mockStore from 'tests/test_store'; import {ActionTypes} from 'utils/constants'; import type {GlobalState} from 'types/store'; import * as Actions from './lhs'; describe('lhs view actions', () => { const initialState = { views: { lhs: { isOpen: false, }, }, }; let store: MockStoreEnhanced<GlobalState, DispatchFunc>; beforeEach(() => { store = mockStore(initialState); }); it('toggle dispatches the right action', () => { store.dispatch(toggle()); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.TOGGLE_LHS, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('open dispatches the right action', () => { store.dispatch(open()); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.OPEN_LHS, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('close dispatches the right action', () => { store.dispatch(close()); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.CLOSE_LHS, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); test('selectStaticPage', async () => { const testStore = configureStore({...initialState}); await testStore.dispatch(Actions.selectStaticPage('test')); expect(testStore.getState().views.lhs.currentStaticPageId).toEqual('test'); }); });
685
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/login.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import {Client4} from 'mattermost-redux/client'; import { login, loginById, } from 'actions/views/login'; import configureStore from 'store'; import TestHelper from 'packages/mattermost-redux/test/test_helper'; describe('actions/views/login', () => { describe('login', () => { test('should return successful when login is successful', async () => { const store = configureStore(); TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, {...TestHelper.basicUser}); const result = await store.dispatch(login('user', 'password', '')); expect(result).toEqual({data: true}); }); test('should return error when when login fails', async () => { const store = configureStore(); TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). post('/users/login'). reply(500, {}); const result = await store.dispatch(login('user', 'password', '')); expect(Object.keys(result)[0]).toEqual('error'); }); }); describe('loginById', () => { test('should return successful when login is successful', async () => { const store = configureStore(); TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). post('/users/login'). reply(200, {...TestHelper.basicUser}); const result = await store.dispatch(loginById('userId', 'password')); expect(result).toEqual({data: true}); }); test('should return error when when login fails', async () => { const store = configureStore(); TestHelper.initBasic(Client4); nock(Client4.getBaseRoute()). post('/users/login'). reply(500, {}); const result = await store.dispatch(loginById('userId', 'password')); expect(Object.keys(result)[0]).toEqual('error'); }); }); });
695
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/profile_popover.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {getChannelMember} from 'mattermost-redux/actions/channels'; import {getTeamMember} from 'mattermost-redux/actions/teams'; import testConfigureStore from 'tests/test_store'; import {getMembershipForEntities} from './profile_popover'; jest.mock('mattermost-redux/actions/channels', () => ({ getChannelMember: jest.fn(() => ({type: 'GET_CHANNEL_MEMBER'})), })); jest.mock('mattermost-redux/actions/teams', () => ({ getTeamMember: jest.fn(() => ({type: 'GET_TEAM_MEMBER'})), })); describe('getMembershipForEntities', () => { const baseState = { entities: { channels: { membersInChannel: {}, }, teams: { membersInTeam: {}, }, }, }; const userId = 'userId'; const teamId = 'teamId'; const channelId = 'channelId'; const getChannelMemberMock = getChannelMember as jest.Mock; const getTeamMemberMock = getTeamMember as jest.Mock; test('should only fetch team member in a DM/GM', () => { const store = testConfigureStore(baseState); store.dispatch(getMembershipForEntities(teamId, userId, '')); expect(getChannelMemberMock).not.toHaveBeenCalled(); expect(getTeamMemberMock).toHaveBeenCalledWith(teamId, userId); }); test('should fetch both team and channel member for regular channels', () => { const store = testConfigureStore(baseState); store.dispatch(getMembershipForEntities(teamId, userId, channelId)); expect(getChannelMemberMock).toHaveBeenCalledWith(channelId, userId); expect(getTeamMemberMock).toHaveBeenCalledWith(teamId, userId); }); });
697
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/rhs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {cloneDeep, set} from 'lodash'; import {batchActions} from 'redux-batched-actions'; import type {MockStoreEnhanced} from 'redux-mock-store'; import type {Post} from '@mattermost/types/posts'; import type {UserProfile} from '@mattermost/types/users'; import type {IDMappedObjects} from '@mattermost/types/utilities'; import {SearchTypes} from 'mattermost-redux/action_types'; import * as PostActions from 'mattermost-redux/actions/posts'; import * as SearchActions from 'mattermost-redux/actions/search'; import type {DispatchFunc} from 'mattermost-redux/types/actions'; import {trackEvent} from 'actions/telemetry_actions.jsx'; import { updateRhsState, selectPostFromRightHandSideSearch, selectPostAndHighlight, updateSearchTerms, performSearch, showSearchResults, showFlaggedPosts, showPinnedPosts, showMentions, closeRightHandSide, showRHSPlugin, hideRHSPlugin, toggleRHSPlugin, toggleMenu, openMenu, closeMenu, openAtPrevious, updateSearchType, suppressRHS, unsuppressRHS, goBack, showChannelMembers, openShowEditHistory, } from 'actions/views/rhs'; import mockStore from 'tests/test_store'; import {ActionTypes, RHSStates, Constants} from 'utils/constants'; import {TestHelper} from 'utils/test_helper'; import {getBrowserUtcOffset} from 'utils/timezone'; import type {GlobalState} from 'types/store'; import type {RhsState} from 'types/store/rhs'; import type {ViewsState} from 'types/store/views'; const currentChannelId = '123'; const currentTeamId = '321'; const currentUserId = 'user123'; const pluggableId = 'pluggableId'; const previousSelectedPost = { id: 'post123', channel_id: 'channel123', root_id: 'root123', } as Post; const UserSelectors = require('mattermost-redux/selectors/entities/users'); UserSelectors.getCurrentUserMentionKeys = jest.fn(() => [{key: '@here'}, {key: '@mattermost'}, {key: '@channel'}, {key: '@all'}]); // Mock Date.now() to return a constant value. const POST_CREATED_TIME = Date.now(); global.Date.now = jest.fn(() => POST_CREATED_TIME); jest.mock('mattermost-redux/actions/posts', () => ({ getPostThread: (...args: any) => ({type: 'MOCK_GET_POST_THREAD', args}), getMentionsAndStatusesForPosts: (...args: any) => ({type: 'MOCK_GET_MENTIONS_AND_STATUSES_FOR_POSTS', args}), })); jest.mock('mattermost-redux/actions/search', () => ({ searchPostsWithParams: (...args: any) => ({type: 'MOCK_SEARCH_POSTS', args}), searchFilesWithParams: (...args: any) => ({type: 'MOCK_SEARCH_FILES', args}), clearSearch: (...args: any) => ({type: 'MOCK_CLEAR_SEARCH', args}), getFlaggedPosts: jest.fn(), getPinnedPosts: jest.fn(), })); jest.mock('actions/telemetry_actions.jsx', () => ({ trackEvent: jest.fn(), })); describe('rhs view actions', () => { const initialState = { entities: { general: { config: { ExperimentalViewArchivedChannels: 'false', }, }, channels: { currentChannelId, }, teams: { currentTeamId, }, users: { currentUserId, profiles: { user123: { timezone: { useAutomaticTimezone: true, automaticTimezone: '', manualTimezone: '', }, } as UserProfile, } as IDMappedObjects<UserProfile>, }, posts: { posts: { [previousSelectedPost.id]: previousSelectedPost, } as IDMappedObjects<Post>, }, preferences: {myPreferences: {}}, }, views: { rhs: { rhsState: null, filesSearchExtFilter: [] as string[], }, posts: { editingPost: { show: true, postId: '818f3dprzb8mtmyoobmzcgnb8y', isRHS: false, }, }, }, } as GlobalState; let store: MockStoreEnhanced<GlobalState, DispatchFunc>; beforeEach(() => { store = mockStore(initialState); }); describe('updateRhsState', () => { test(`it dispatches ${ActionTypes.UPDATE_RHS_STATE} correctly with defaults`, () => { store.dispatch(updateRhsState(RHSStates.PIN)); const action = { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.PIN, channelId: currentChannelId, }; expect(store.getActions()).toEqual([action]); }); test(`it dispatches ${ActionTypes.UPDATE_RHS_STATE} correctly`, () => { store.dispatch(updateRhsState(RHSStates.PIN, 'channelId', RHSStates.CHANNEL_INFO as RhsState)); const action = { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.PIN, channelId: 'channelId', previousRhsState: RHSStates.CHANNEL_INFO, }; expect(store.getActions()).toEqual([action]); }); }); describe('selectPostFromRightHandSideSearch', () => { const post = { id: 'post123', channel_id: 'channel123', root_id: 'root123', } as Post; test('it dispatches PostActions.getPostThread correctly', () => { store.dispatch(selectPostFromRightHandSideSearch(post)); const compareStore = mockStore(initialState); compareStore.dispatch(PostActions.getPostThread(post.root_id)); expect(store.getActions()[0]).toEqual(compareStore.getActions()[0]); }); describe(`it dispatches ${ActionTypes.SELECT_POST} correctly`, () => { it('with mocked date', async () => { store = mockStore({ ...initialState, views: { rhs: { rhsState: RHSStates.FLAG, filesSearchExtFilter: [] as string[], }, } as ViewsState, }); await store.dispatch(selectPostFromRightHandSideSearch(post)); const action = { type: ActionTypes.SELECT_POST, postId: post.root_id, channelId: post.channel_id, previousRhsState: RHSStates.FLAG, timestamp: POST_CREATED_TIME, }; expect(store.getActions()[1]).toEqual(action); }); }); }); describe('updateSearchTerms', () => { test(`it dispatches ${ActionTypes.UPDATE_RHS_SEARCH_TERMS} correctly`, () => { const terms = '@here test terms'; store.dispatch(updateSearchTerms(terms)); const action = { type: ActionTypes.UPDATE_RHS_SEARCH_TERMS, terms, }; expect(store.getActions()).toEqual([action]); }); }); describe('performSearch', () => { const terms = '@here test search'; test('it dispatches searchPosts correctly', () => { store.dispatch(performSearch(terms, false)); // timezone offset in seconds const timeZoneOffset = getBrowserUtcOffset() * 60; const compareStore = mockStore(initialState); compareStore.dispatch(SearchActions.searchPostsWithParams(currentTeamId, {include_deleted_channels: false, terms, is_or_search: false, time_zone_offset: timeZoneOffset, page: 0, per_page: 20})); compareStore.dispatch(SearchActions.searchFilesWithParams(currentTeamId, {include_deleted_channels: false, terms, is_or_search: false, time_zone_offset: timeZoneOffset, page: 0, per_page: 20})); expect(store.getActions()).toEqual(compareStore.getActions()); store.dispatch(performSearch(terms, true)); compareStore.dispatch(SearchActions.searchPostsWithParams('', {include_deleted_channels: false, terms, is_or_search: true, time_zone_offset: timeZoneOffset, page: 0, per_page: 20})); compareStore.dispatch(SearchActions.searchFilesWithParams(currentTeamId, {include_deleted_channels: false, terms, is_or_search: true, time_zone_offset: timeZoneOffset, page: 0, per_page: 20})); expect(store.getActions()).toEqual(compareStore.getActions()); }); }); describe('showSearchResults', () => { const terms = '@here test search'; const testInitialState = { ...initialState, views: { rhs: { searchTerms: terms, filesSearchExtFilter: [] as string[], }, }, } as GlobalState; test('it dispatches the right actions', () => { store = mockStore(testInitialState); store.dispatch(showSearchResults()); const compareStore = mockStore(testInitialState); compareStore.dispatch(updateRhsState(RHSStates.SEARCH)); compareStore.dispatch({ type: ActionTypes.UPDATE_RHS_SEARCH_RESULTS_TERMS, terms, }); compareStore.dispatch(performSearch(terms)); expect(store.getActions()).toEqual(compareStore.getActions()); }); }); describe('showFlaggedPosts', () => { test('it dispatches the right actions', async () => { (SearchActions.getFlaggedPosts as jest.Mock).mockReturnValue((dispatch: DispatchFunc) => { dispatch({type: 'MOCK_GET_FLAGGED_POSTS'}); return {data: 'data'}; }); await store.dispatch(showFlaggedPosts()); expect(SearchActions.getFlaggedPosts).toHaveBeenCalled(); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.FLAG, }, { type: 'MOCK_GET_FLAGGED_POSTS', }, { type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: 'data', }, { type: SearchTypes.RECEIVED_SEARCH_TERM, data: { teamId: currentTeamId, terms: null, isOrSearch: false, }, }, ], }, ]); }); }); describe('showPinnedPosts', () => { test('it dispatches the right actions for the current channel', async () => { (SearchActions.getPinnedPosts as jest.Mock).mockReturnValue((dispatch: DispatchFunc) => { dispatch({type: 'MOCK_GET_PINNED_POSTS'}); return {data: 'data'}; }); await store.dispatch(showPinnedPosts()); expect(SearchActions.getPinnedPosts).toHaveBeenCalledWith(currentChannelId); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, channelId: currentChannelId, state: RHSStates.PIN, previousRhsState: null, }, { type: 'MOCK_GET_PINNED_POSTS', }, { type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: 'data', }, { type: SearchTypes.RECEIVED_SEARCH_TERM, data: { teamId: currentTeamId, terms: null, isOrSearch: false, }, }, ], }, ]); }); test('it dispatches the right actions for a specific channel', async () => { const channelId = 'channel1'; (SearchActions.getPinnedPosts as jest.Mock).mockReturnValue((dispatch: DispatchFunc) => { dispatch({type: 'MOCK_GET_PINNED_POSTS'}); return {data: 'data'}; }); await store.dispatch(showPinnedPosts(channelId)); expect(SearchActions.getPinnedPosts).toHaveBeenCalledWith(channelId); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, channelId, state: RHSStates.PIN, previousRhsState: null, }, { type: 'MOCK_GET_PINNED_POSTS', }, { type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: 'data', }, { type: SearchTypes.RECEIVED_SEARCH_TERM, data: { teamId: currentTeamId, terms: null, isOrSearch: false, }, }, ], }, ]); }); }); describe('showChannelMembers', () => { test('it dispatches the right actions', async () => { await store.dispatch(showChannelMembers(currentChannelId)); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, channelId: currentChannelId, state: RHSStates.CHANNEL_MEMBERS, previousRhsState: null, }, ]); }); }); describe('openShowEditHistory', () => { test('it dispatches the right actions', async () => { const post = TestHelper.getPostMock(); await store.dispatch(openShowEditHistory(post)); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.EDIT_HISTORY, postId: post.root_id || post.id, channelId: post.channel_id, timestamp: POST_CREATED_TIME, }, ]); }); }); describe('showMentions', () => { test('it dispatches the right actions', () => { store.dispatch(showMentions()); const compareStore = mockStore(initialState); compareStore.dispatch(performSearch('@mattermost ', true)); compareStore.dispatch(batchActions([ { type: ActionTypes.UPDATE_RHS_SEARCH_TERMS, terms: '@mattermost ', }, { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.MENTION, }, ])); expect(store.getActions()).toEqual(compareStore.getActions()); }); test('it calls trackEvent correctly', () => { (trackEvent as jest.Mock).mockClear(); store.dispatch(showMentions()); expect(trackEvent).toHaveBeenCalledTimes(1); expect((trackEvent as jest.Mock).mock.calls[0][0]).toEqual('api'); expect((trackEvent as jest.Mock).mock.calls[0][1]).toEqual('api_posts_search_mention'); }); }); describe('closeRightHandSide', () => { test('it dispatches the right actions without editingPost', () => { const state = cloneDeep(initialState); set(state, 'views.posts.editingPost', {}); store = mockStore(state); store.dispatch(closeRightHandSide()); const expectedActions = [{ type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: 'UPDATE_RHS_STATE', state: null, }, { type: 'SELECT_POST', postId: '', channelId: '', timestamp: 0, }, ], }]; expect(store.getActions()).toEqual(expectedActions); }); test('it dispatches the right actions with editingPost in center channel', () => { const state = cloneDeep(initialState); set(state, 'views.posts.editingPost.isRHS', false); store = mockStore(state); store.dispatch(closeRightHandSide()); const expectedActions = [{ type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: 'UPDATE_RHS_STATE', state: null, }, { type: 'SELECT_POST', postId: '', channelId: '', timestamp: 0, }, ], }]; expect(store.getActions()).toEqual(expectedActions); }); test('it dispatches the right actions with editingPost in RHS', () => { const state = cloneDeep(initialState); set(state, 'views.posts.editingPost.isRHS', true); store = mockStore(state); store.dispatch(closeRightHandSide()); const expectedActions = [{ type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: 'UPDATE_RHS_STATE', state: null, }, { type: 'SELECT_POST', postId: '', channelId: '', timestamp: 0, }, ], }]; expect(store.getActions()).toEqual(expectedActions); }); }); it('toggleMenu dispatches the right action', () => { store.dispatch(toggleMenu()); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.TOGGLE_RHS_MENU, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('openMenu dispatches the right action', () => { store.dispatch(openMenu()); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.OPEN_RHS_MENU, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('closeMenu dispatches the right action', () => { store.dispatch(closeMenu()); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.CLOSE_RHS_MENU, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); describe('Plugin actions', () => { const stateWithPluginRhs = cloneDeep(initialState); set(stateWithPluginRhs, `views.rhs.${pluggableId}`, pluggableId); set(stateWithPluginRhs, 'views.rhs.rhsState', RHSStates.PLUGIN); const stateWithoutPluginRhs = cloneDeep(initialState); set(stateWithoutPluginRhs, 'views.rhs.rhsState', RHSStates.PIN); describe('showRHSPlugin', () => { it('dispatches the right action', () => { store.dispatch(showRHSPlugin(pluggableId)); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.PLUGIN, pluggableId, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); }); describe('hideRHSPlugin', () => { it('it dispatches the right action when plugin rhs is opened', () => { store = mockStore(stateWithPluginRhs); store.dispatch(hideRHSPlugin(pluggableId)); const compareStore = mockStore(stateWithPluginRhs); compareStore.dispatch(closeRightHandSide()); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('it doesn\'t dispatch the action when plugin rhs is closed', () => { store = mockStore(stateWithoutPluginRhs); store.dispatch(hideRHSPlugin(pluggableId)); const compareStore = mockStore(initialState); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('it doesn\'t dispatch the action when other plugin rhs is opened', () => { store = mockStore(stateWithPluginRhs); store.dispatch(hideRHSPlugin('pluggableId2')); const compareStore = mockStore(initialState); expect(store.getActions()).toEqual(compareStore.getActions()); }); }); describe('toggleRHSPlugin', () => { it('it dispatches hide action when rhs is open', () => { store = mockStore(stateWithPluginRhs); store.dispatch(toggleRHSPlugin(pluggableId)); const compareStore = mockStore(initialState); compareStore.dispatch(closeRightHandSide()); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('it dispatches hide action when rhs is closed', () => { store = mockStore(stateWithoutPluginRhs); store.dispatch(toggleRHSPlugin(pluggableId)); const compareStore = mockStore(initialState); compareStore.dispatch(showRHSPlugin(pluggableId)); expect(store.getActions()).toEqual(compareStore.getActions()); }); }); }); describe('openAtPrevious', () => { const batchingReducerBatch = { type: 'BATCHING_REDUCER.BATCH', meta: { batch: true, }, payload: [ { type: SearchTypes.RECEIVED_SEARCH_POSTS, data: 'data', }, { type: SearchTypes.RECEIVED_SEARCH_TERM, data: { teamId: currentTeamId, terms: null, isOrSearch: false, }, }, ], }; function actionsForEmptySearch() { const compareStore = mockStore(initialState); compareStore.dispatch(SearchActions.clearSearch()); compareStore.dispatch(updateSearchTerms('')); compareStore.dispatch({ type: ActionTypes.UPDATE_RHS_SEARCH_RESULTS_TERMS, terms: '', }); compareStore.dispatch(updateRhsState(RHSStates.SEARCH)); return compareStore.getActions(); } it('opens to empty search when not previously opened', () => { store.dispatch(openAtPrevious(null)); expect(store.getActions()).toEqual(actionsForEmptySearch()); }); it('opens a mention search', () => { store.dispatch(openAtPrevious({isMentionSearch: true})); const compareStore = mockStore(initialState); compareStore.dispatch(performSearch('@mattermost ', true)); compareStore.dispatch(batchActions([ { type: ActionTypes.UPDATE_RHS_SEARCH_TERMS, terms: '@mattermost ', }, { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.MENTION, }, ])); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('opens pinned posts', async () => { (SearchActions.getPinnedPosts as jest.Mock).mockReturnValue((dispatch: DispatchFunc) => { dispatch({type: 'MOCK_GET_PINNED_POSTS'}); return {data: 'data'}; }); await store.dispatch(openAtPrevious({isPinnedPosts: true})); expect(SearchActions.getPinnedPosts).toHaveBeenCalledWith(currentChannelId); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, channelId: currentChannelId, state: RHSStates.PIN, previousRhsState: null, }, { type: 'MOCK_GET_PINNED_POSTS', }, batchingReducerBatch, ]); }); it('opens flagged posts', async () => { (SearchActions.getFlaggedPosts as jest.Mock).mockReturnValue((dispatch: DispatchFunc) => { dispatch({type: 'MOCK_GET_FLAGGED_POSTS'}); return {data: 'data'}; }); await store.dispatch(openAtPrevious({isFlaggedPosts: true})); expect(SearchActions.getFlaggedPosts).toHaveBeenCalled(); expect(store.getActions()).toEqual([ { type: ActionTypes.UPDATE_RHS_STATE, state: RHSStates.FLAG, }, { type: 'MOCK_GET_FLAGGED_POSTS', }, batchingReducerBatch, ]); }); it('opens selected post', async () => { const previousState = 'flag'; await store.dispatch(openAtPrevious({selectedPostId: previousSelectedPost.id, previousRhsState: previousState})); const compareStore = mockStore(initialState); compareStore.dispatch(PostActions.getPostThread(previousSelectedPost.root_id)); compareStore.dispatch({ type: ActionTypes.SELECT_POST, postId: previousSelectedPost.root_id, channelId: previousSelectedPost.channel_id, previousRhsState: previousState, timestamp: POST_CREATED_TIME, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('opens empty search when selected post does not exist', async () => { await store.dispatch(openAtPrevious({selectedPostId: 'postxyz'})); expect(store.getActions()).toEqual(actionsForEmptySearch()); }); it('opens selected post card', async () => { const previousState = 'flag'; await store.dispatch(openAtPrevious({selectedPostCardId: previousSelectedPost.id, previousRhsState: previousState})); const compareStore = mockStore(initialState); compareStore.dispatch({ type: ActionTypes.SELECT_POST_CARD, postId: previousSelectedPost.id, channelId: previousSelectedPost.channel_id, previousRhsState: previousState, }); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('opens empty search when selected post card does not exist', async () => { await store.dispatch(openAtPrevious({selectedPostCardId: 'postxyz'})); expect(store.getActions()).toEqual(actionsForEmptySearch()); }); it('opens search results', async () => { const terms = '@here test search'; const searchInitialState = { ...initialState, views: { rhs: { searchTerms: terms, filesSearchExtFilter: [] as string[], }, }, } as GlobalState; store = mockStore(searchInitialState); await store.dispatch(openAtPrevious({searchVisible: true})); const compareStore = mockStore(searchInitialState); compareStore.dispatch(updateRhsState(RHSStates.SEARCH)); compareStore.dispatch({ type: ActionTypes.UPDATE_RHS_SEARCH_RESULTS_TERMS, terms, }); compareStore.dispatch(performSearch(terms)); expect(store.getActions()).toEqual(compareStore.getActions()); }); it('opens empty search when no other options set', () => { store.dispatch(openAtPrevious({})); expect(store.getActions()).toEqual(actionsForEmptySearch()); }); }); describe('searchType', () => { test('updateSearchType', () => { const store = mockStore(initialState); store.dispatch(updateSearchType('files')); expect(store.getActions()).toEqual([{ type: ActionTypes.UPDATE_RHS_SEARCH_TYPE, searchType: 'files', }]); }); }); describe('selectPostAndHighlight', () => { const post1 = {id: '42'} as Post; const post2 = {id: '43'} as Post; const post3 = {id: '44'} as Post; beforeEach(() => { jest.useFakeTimers(); jest.setSystemTime(POST_CREATED_TIME); }); const batchedActions = (postId: string, delay = 0) => [{ meta: {batch: true}, payload: [{ postId, timestamp: POST_CREATED_TIME + delay, type: ActionTypes.SELECT_POST, }, { postId, type: ActionTypes.HIGHLIGHT_REPLY, }], type: 'BATCHING_REDUCER.BATCH', }]; it('should select, and highlight a post, and after a delay clear the highlight', () => { const store = mockStore(initialState); store.dispatch(selectPostAndHighlight(post1)); expect(store.getActions()).toEqual([ ...batchedActions('42'), ]); expect(jest.getTimerCount()).toBe(1); jest.advanceTimersByTime(Constants.PERMALINK_FADEOUT); expect(jest.getTimerCount()).toBe(0); expect(store.getActions()).toEqual([ ...batchedActions('42'), {type: ActionTypes.CLEAR_HIGHLIGHT_REPLY}, ]); }); it('should clear highlight only once after last call no matter how many times called', () => { const store = mockStore(initialState); store.dispatch(selectPostAndHighlight(post1)); jest.advanceTimersByTime(1000); store.dispatch(selectPostAndHighlight(post2)); jest.advanceTimersByTime(1000); store.dispatch(selectPostAndHighlight(post3)); expect(jest.getTimerCount()).toBe(1); jest.advanceTimersByTime(Constants.PERMALINK_FADEOUT - 2000); expect(jest.getTimerCount()).toBe(1); jest.advanceTimersByTime(2000); expect(jest.getTimerCount()).toBe(0); expect(store.getActions()).toEqual([ ...batchedActions('42'), ...batchedActions('43', 1000), ...batchedActions('44', 2000), {type: ActionTypes.CLEAR_HIGHLIGHT_REPLY}, ]); }); }); describe('rhs suppress actions', () => { it('should suppress rhs', () => { const store = mockStore(initialState); store.dispatch(suppressRHS); expect(store.getActions()).toEqual([{ type: ActionTypes.SUPPRESS_RHS, }]); }); it('should unsuppresses rhs', () => { store.dispatch(unsuppressRHS); expect(store.getActions()).toEqual([{ type: ActionTypes.UNSUPPRESS_RHS, }]); }); }); describe('rhs go back', () => { it('should be able to go back', () => { const testState = {...initialState}; testState.views.rhs.previousRhsStates = [RHSStates.CHANNEL_FILES as RhsState]; const store = mockStore(testState); store.dispatch(goBack()); expect(store.getActions()).toEqual([{ type: ActionTypes.RHS_GO_BACK, state: RHSStates.CHANNEL_FILES as RhsState, }]); }); }); });
699
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/views/root.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import * as Actions from 'actions/views/root'; import * as i18nSelectors from 'selectors/i18n'; import mockStore from 'tests/test_store'; import {ActionTypes} from 'utils/constants'; jest.mock('mattermost-redux/actions/general', () => { const original = jest.requireActual('mattermost-redux/actions/general'); return { ...original, getClientConfig: () => ({type: 'MOCK_GET_CLIENT_CONFIG'}), getLicenseConfig: () => ({type: 'MOCK_GET_LICENSE_CONFIG'}), }; }); jest.mock('mattermost-redux/actions/users', () => { const original = jest.requireActual('mattermost-redux/actions/users'); return { ...original, loadMe: () => ({type: 'MOCK_LOAD_ME'}), }; }); describe('root view actions', () => { const origCookies = document.cookie; const origWasLoggedIn = localStorage.getItem('was_logged_in'); beforeAll(() => { document.cookie = ''; localStorage.setItem('was_logged_in', ''); }); afterAll(() => { document.cookie = origCookies; localStorage.setItem('was_logged_in', origWasLoggedIn || ''); }); describe('loadConfigAndMe', () => { test('loadConfigAndMe, without user logged in', async () => { const testStore = mockStore({}); await testStore.dispatch(Actions.loadConfigAndMe()); expect(testStore.getActions()).toEqual([{type: 'MOCK_GET_CLIENT_CONFIG'}, {type: 'MOCK_GET_LICENSE_CONFIG'}]); }); test('loadConfigAndMe, with user logged in', async () => { const testStore = mockStore({}); document.cookie = 'MMUSERID=userid'; localStorage.setItem('was_logged_in', 'true'); await testStore.dispatch(Actions.loadConfigAndMe()); expect(testStore.getActions()).toEqual([{type: 'MOCK_GET_CLIENT_CONFIG'}, {type: 'MOCK_GET_LICENSE_CONFIG'}, {type: 'MOCK_LOAD_ME'}]); }); }); describe('registerPluginTranslationsSource', () => { test('Should not dispatch action when getTranslation is empty', () => { const testStore = mockStore({}); jest.spyOn(i18nSelectors, 'getTranslations').mockReturnValue(undefined as any); jest.spyOn(i18nSelectors, 'getCurrentLocale').mockReturnValue('en'); testStore.dispatch(Actions.registerPluginTranslationsSource('plugin_id', jest.fn())); expect(testStore.getActions()).toEqual([]); }); test('Should dispatch action when getTranslation is not empty', () => { const testStore = mockStore({}); jest.spyOn(i18nSelectors, 'getTranslations').mockReturnValue({}); jest.spyOn(i18nSelectors, 'getCurrentLocale').mockReturnValue('en'); testStore.dispatch(Actions.registerPluginTranslationsSource('plugin_id', jest.fn())); expect(testStore.getActions()).toEqual([{ data: { locale: 'en', translations: {}, }, type: ActionTypes.RECEIVED_TRANSLATIONS, }]); }); }); });
702
0
petrpan-code/mattermost/mattermost/webapp/channels/src/actions
petrpan-code/mattermost/mattermost/webapp/channels/src/actions/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 view actions', () => { const initialState = { views: { statusDropdown: { isOpen: false, }, }, }; it('setStatusDropdown should set the status dropdown open or not', () => { const store = configureStore(initialState); store.dispatch(setStatusDropdown(false)); expect(isStatusDropdownOpen(store.getState())).toBe(false); store.dispatch(setStatusDropdown(true)); expect(isStatusDropdownOpen(store.getState())).toBe(true); }); });
709
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/alert_banner.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 AlertBanner from './alert_banner'; describe('Components/AlertBanner', () => { test('should match snapshot', () => { const wrapper = shallow( <AlertBanner mode='info' message='message' title='title' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot for app variant', () => { const wrapper = shallow( <AlertBanner mode='info' message='message' title='title' variant='app' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when icon disabled', () => { const wrapper = shallow( <AlertBanner hideIcon={true} mode='info' message='message' title='title' variant='app' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when buttons are passed', () => { const wrapper = shallow( <AlertBanner hideIcon={true} mode='info' message='message' title='title' variant='app' actionButtonLeft={<div id='actionButtonLeft'/>} actionButtonRight={<div id='actionButtonRight'/>} />, ); expect(wrapper).toMatchSnapshot(); }); });
714
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/autocomplete_selector.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 AutocompleteSelector from './autocomplete_selector'; describe('components/widgets/settings/AutocompleteSelector', () => { test('render component with required props', () => { const wrapper = shallow( <AutocompleteSelector id='string.id' label='some label' value='some value' providers={[]} />, ); expect(wrapper).toMatchInlineSnapshot(` <div className="form-group" data-testid="autoCompleteSelector" > <label className="control-label " > some label </label> <div className="" > <Connect(SuggestionBox) className="form-control" completeOnTab={true} containerClass="select-suggestion-container" listComponent={[Function]} listPosition="top" onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onItemSelected={[Function]} openOnFocus={true} openWhenEmpty={true} providers={Array []} renderNoResults={true} replaceAllInputOnSelect={true} value="some value" /> </div> </div> `); }); test('check snapshot with value prop and changing focus', () => { const wrapper = shallow<AutocompleteSelector>( <AutocompleteSelector providers={[]} label='some label' value='value from prop' />, ); wrapper.instance().onBlur(); expect(wrapper).toMatchInlineSnapshot(` <div className="form-group" data-testid="autoCompleteSelector" > <label className="control-label " > some label </label> <div className="" > <Connect(SuggestionBox) className="form-control" completeOnTab={true} containerClass="select-suggestion-container" listComponent={[Function]} listPosition="top" onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onItemSelected={[Function]} openOnFocus={true} openWhenEmpty={true} providers={Array []} renderNoResults={true} replaceAllInputOnSelect={true} value="value from prop" /> </div> </div> `); wrapper.instance().onChange(({target: {value: 'value from input'} as HTMLInputElement})); wrapper.instance().onFocus(); expect(wrapper).toMatchInlineSnapshot(` <div className="form-group" data-testid="autoCompleteSelector" > <label className="control-label " > some label </label> <div className="" > <Connect(SuggestionBox) className="form-control" completeOnTab={true} containerClass="select-suggestion-container" listComponent={[Function]} listPosition="top" onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onItemSelected={[Function]} openOnFocus={true} openWhenEmpty={true} providers={Array []} renderNoResults={true} replaceAllInputOnSelect={true} value="value from input" /> </div> </div> `); }); test('onSelected', () => { const onSelected = jest.fn(); const wrapper = shallow<AutocompleteSelector>( <AutocompleteSelector label='some label' value='some value' providers={[]} onSelected={onSelected} />, ); const selected = {text: 'sometext', value: 'somevalue', id: '', username: '', display_name: ''}; wrapper.instance().handleSelected(selected); expect(onSelected).toHaveBeenCalledTimes(1); expect(onSelected).toHaveBeenCalledWith(selected); }); });
716
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/autosize_textarea.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 AutosizeTextarea from 'components/autosize_textarea'; describe('components/AutosizeTextarea', () => { test('should match snapshot, init', () => { const wrapper = shallow( <AutosizeTextarea/>, ); expect(wrapper).toMatchSnapshot(); }); });
720
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/color_input.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import ColorInput from './color_input'; describe('components/ColorInput', () => { const baseProps = { id: 'sidebarBg', onChange: jest.fn(), value: '#ffffff', }; test('should match snapshot, init', () => { const wrapper = shallow( <ColorInput {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, opened', () => { const wrapper = shallow( <ColorInput {...baseProps}/>, ); wrapper.find('.input-group-addon').simulate('click'); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, toggle picker', () => { const wrapper = shallow( <ColorInput {...baseProps}/>, ); wrapper.find('.input-group-addon').simulate('click'); wrapper.find('.input-group-addon').simulate('click'); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, click on picker', () => { const wrapper = shallow( <ColorInput {...baseProps}/>, ); wrapper.find('.input-group-addon').simulate('click'); wrapper.find('.color-popover').simulate('click'); expect(wrapper).toMatchSnapshot(); }); test('should have match state on togglePicker', () => { const wrapper = shallow( <ColorInput {...baseProps}/>, ); wrapper.setState({isOpened: true}); wrapper.find('.input-group-addon').simulate('click'); expect(wrapper.state('isOpened')).toEqual(false); wrapper.find('.input-group-addon').simulate('click'); expect(wrapper.state('isOpened')).toEqual(true); }); test('should keep what the user types in the textbox until blur', () => { const wrapper = shallow( <ColorInput {...baseProps}/>, ); baseProps.onChange.mockImplementation((value) => wrapper.setProps({value})); wrapper.find('input').simulate('focus', {target: null}); expect(wrapper.state('focused')).toBe(true); wrapper.find('input').simulate('change', {target: {value: '#abc'}}); expect(wrapper.state('value')).toBe('#abc'); expect(baseProps.onChange).toHaveBeenLastCalledWith('#aabbcc'); expect(wrapper.find('input').prop('value')).toEqual('#abc'); expect(wrapper.find('.color-icon').prop('style')).toHaveProperty('backgroundColor', '#abc'); wrapper.find('input').simulate('blur'); expect(wrapper.state('focused')).toBe(false); expect(wrapper.state('value')).toBe('#aabbcc'); expect(baseProps.onChange).toHaveBeenLastCalledWith('#aabbcc'); expect(wrapper.find('input').prop('value')).toEqual('#aabbcc'); expect(wrapper.find('.color-icon').prop('style')).toHaveProperty('backgroundColor', '#aabbcc'); }); });
722
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/confirm_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import ConfirmModal from './confirm_modal'; describe('ConfirmModal', () => { const baseProps = { show: true, onConfirm: jest.fn(), onCancel: jest.fn(), }; test('should pass checkbox state when confirm is pressed', () => { const props = { ...baseProps, showCheckbox: true, }; const wrapper = shallow(<ConfirmModal {...props}/>); expect(wrapper.state('checked')).toBe(false); expect(wrapper.find('input[type="checkbox"]').prop('checked')).toBe(false); expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true); wrapper.find('#confirmModalButton').simulate('click'); expect(props.onConfirm).toHaveBeenCalledWith(false); wrapper.find('input[type="checkbox"]').simulate('change', {target: {checked: true}}); expect(wrapper.state('checked')).toBe(true); expect(wrapper.find('input[type="checkbox"]').prop('checked')).toBe(true); wrapper.find('#confirmModalButton').simulate('click'); expect(props.onConfirm).toHaveBeenCalledWith(true); }); test('should pass checkbox state when cancel is pressed', () => { const props = { ...baseProps, showCheckbox: true, }; const wrapper = shallow(<ConfirmModal {...props}/>); expect(wrapper.state('checked')).toBe(false); expect(wrapper.find('input[type="checkbox"]').prop('checked')).toBe(false); expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true); wrapper.find('#cancelModalButton').simulate('click'); expect(props.onCancel).toHaveBeenCalledWith(false); wrapper.find('input[type="checkbox"]').simulate('change', {target: {checked: true}}); expect(wrapper.state('checked')).toBe(true); expect(wrapper.find('input[type="checkbox"]').prop('checked')).toBe(true); wrapper.find('#cancelModalButton').simulate('click'); expect(props.onCancel).toHaveBeenCalledWith(true); }); });
732
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/file_upload_overlay.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 FileUploadOverlay from 'components/file_upload_overlay'; describe('components/FileUploadOverlay', () => { test('should match snapshot when file upload is showing with no overlay type', () => { const wrapper = shallow( <FileUploadOverlay overlayType='' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when file upload is showing with overlay type of right', () => { const wrapper = shallow( <FileUploadOverlay overlayType='right' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when file upload is showing with overlay type of center', () => { const wrapper = shallow( <FileUploadOverlay overlayType='center' />, ); expect(wrapper).toMatchSnapshot(); }); });
735
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/formatted_markdown_message.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 {IntlProvider} from 'react-intl'; import FormattedMarkdownMessage from './formatted_markdown_message'; jest.unmock('react-intl'); describe('components/FormattedMarkdownMessage', () => { test('should render message', () => { const props = { id: 'test.foo', defaultMessage: '**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)', }; const wrapper = mount(wrapProvider(<FormattedMarkdownMessage {...props}/>)); expect(wrapper).toMatchSnapshot(); }); test('should backup to default', () => { const props = { id: 'xxx', defaultMessage: 'testing default message', }; const wrapper = mount(wrapProvider(<FormattedMarkdownMessage {...props}/>)); expect(wrapper).toMatchSnapshot(); }); test('should escape non-BR', () => { const props = { id: 'test.bar', defaultMessage: '', values: { b: (...content: string[]) => `<b>${content}</b>`, script: (...content: string[]) => `<script>${content}</script>`, }, }; const wrapper = mount(wrapProvider(<FormattedMarkdownMessage {...props}/>)); expect(wrapper).toMatchSnapshot(); }); test('values should work', () => { const props = { id: 'test.vals', defaultMessage: '*Hi* {petName}!', values: { petName: 'sweetie', }, }; const wrapper = mount(wrapProvider(<FormattedMarkdownMessage {...props}/>)); expect(wrapper).toMatchSnapshot(); }); test('should allow to disable links', () => { const props = { id: 'test.vals', defaultMessage: '*Hi* {petName}!', values: { petName: 'http://www.mattermost.com', }, disableLinks: true, }; const wrapper = mount(wrapProvider(<FormattedMarkdownMessage {...props}/>)); expect(wrapper).toMatchSnapshot(); }); }); export function wrapProvider(el: JSX.Element) { const enTranslationData = { 'test.foo': '**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)', 'test.bar': '<b>hello</b> <script>var malicious = true;</script> world!', 'test.vals': '*Hi* {petName}!', }; return ( <IntlProvider locale={'en'} messages={enTranslationData} > {el} </IntlProvider>) ; }
737
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/get_link_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {Modal} from 'react-bootstrap'; import GetLinkModal from 'components/get_link_modal'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; describe('components/GetLinkModal', () => { const onHide = jest.fn(); const requiredProps = { show: true, onHide, onExited: jest.fn(), title: 'title', link: 'https://mattermost.com', }; test('should match snapshot when all props is set', () => { const helpText = 'help text'; const props = {...requiredProps, helpText}; const wrapper = shallow( <GetLinkModal {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when helpText is not set', () => { const wrapper = shallow( <GetLinkModal {...requiredProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have called onHide', () => { const newOnHide = jest.fn(); const props = {...requiredProps, onHide: newOnHide}; const wrapper = shallow( <GetLinkModal {...props}/>, ); wrapper.find(Modal).first().props().onHide(); expect(newOnHide).toHaveBeenCalledTimes(1); expect(wrapper.state('copiedLink')).toBe(false); wrapper.setProps({show: true}); wrapper.setState({copiedLink: true}); expect(wrapper).toMatchSnapshot(); expect(wrapper.state('copiedLink')).toBe(true); wrapper.find('#linkModalCloseButton').simulate('click'); expect(newOnHide).toHaveBeenCalledTimes(2); expect(wrapper).toMatchSnapshot(); expect(wrapper.state('copiedLink')).toBe(false); }); test('should have handle copyLink', () => { const wrapper = mountWithIntl( <GetLinkModal {...requiredProps}/>, ); wrapper.find('#linkModalTextArea').simulate('click'); expect(wrapper.state('copiedLink')).toBe(true); }); });
742
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/list_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {Group} from '@mattermost/types/groups'; import {TestHelper} from 'utils/test_helper'; import ListModal, {DEFAULT_NUM_PER_PAGE} from './list_modal'; describe('components/ListModal', () => { const mockItem1 = TestHelper.getGroupMock({id: '123', name: 'bar31'}); const mockItem2 = TestHelper.getGroupMock({id: '234', name: 'bar2'}); const mockItem3 = TestHelper.getGroupMock({id: '345', name: 'bar3'}); const mockItems = [mockItem1, mockItem2]; const mockItemsPage2 = [mockItem3]; const mockSearchTerm = 'ar3'; const mockItemsSearch = mockItems.concat(mockItemsPage2).filter((item) => item.name.includes(mockSearchTerm)); const totalCount = mockItems.length + mockItemsPage2.length; const baseProps = { loadItems: async (pageNumber: number, searchTerm: string) => { if (searchTerm === mockSearchTerm) { return {items: mockItemsSearch, totalCount}; } if (pageNumber === 0) { return {items: mockItems, totalCount}; } return {items: mockItemsPage2, totalCount}; }, renderRow: (item: Group) => { return ( <div className='item' key={item.id} > {item.id} </div> ); }, titleText: 'list modal', searchPlaceholderText: 'search for name', numPerPage: DEFAULT_NUM_PER_PAGE, titleBarButtonText: 'DEFAULT', titleBarButtonTextOnClick: () => {}, }; it('should match snapshot', () => { const wrapper = shallow( <ListModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); setTimeout(() => { expect(wrapper.state('items')).toEqual(mockItems); expect(wrapper.state('totalCount')).toEqual(totalCount); expect(wrapper.state('numPerPage')).toEqual(DEFAULT_NUM_PER_PAGE); }, 0); }); it('should update numPerPage', () => { const numPerPage = totalCount - 1; const props = {...baseProps}; props.numPerPage = numPerPage; const wrapper = shallow( <ListModal {...props}/>, ); setTimeout(() => { expect(wrapper.state('numPerPage')).toEqual(numPerPage); }, 0); }); it('should match snapshot with title bar button', () => { const props = {...baseProps}; props.titleBarButtonText = 'Add Foo'; props.titleBarButtonTextOnClick = () => { }; const wrapper = shallow( <ListModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have called onHide when handleExit is called', () => { const onHide = jest.fn(); const props = {...baseProps, onHide}; const wrapper = shallow( <ListModal {...props}/>, ); (wrapper.instance() as ListModal).handleExit(); expect(onHide).toHaveBeenCalledTimes(1); }); test('paging loads new items', () => { const wrapper = shallow( <ListModal {...baseProps}/>, ); (wrapper.instance() as ListModal).onNext(); setTimeout(() => { expect(wrapper.state('page')).toEqual(1); expect(wrapper.state('items')).toEqual(mockItemsPage2); }, 0); (wrapper.instance() as ListModal).onPrev(); setTimeout(() => { expect(wrapper.state('page')).toEqual(0); expect(wrapper.state('items')).toEqual(mockItems); }, 0); }); test('search input', () => { const wrapper = shallow( <ListModal {...baseProps}/>, ); (wrapper.instance() as ListModal).onSearchInput({target: {value: mockSearchTerm}} as React.ChangeEvent<HTMLInputElement>); setTimeout(() => { expect(wrapper.state('searchTerm')).toEqual(mockSearchTerm); expect(wrapper.state('items')).toEqual(mockItemsSearch); }, 0); }); });
744
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/loading_image_preview.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import LoadingImagePreview from 'components/loading_image_preview'; describe('components/LoadingImagePreview', () => { test('should match snapshot', () => { const loading = 'Loading'; let progress = 50; const wrapper = shallow( <LoadingImagePreview loading={loading} progress={progress} />, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('span').text()).toBe('Loading 50%'); progress = 90; wrapper.setProps({loading, progress}); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('span').text()).toBe('Loading 90%'); }); });
747
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/localized_icon.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import LocalizedIcon from './localized_icon'; describe('LocalizedIcon', () => { const baseProps = { title: { id: 'test.id', defaultMessage: 'test default message', }, }; test('should render localized title', () => { const wrapper = mountWithIntl(<LocalizedIcon {...baseProps}/>); expect(wrapper.find('i').prop('title')).toBe(baseProps.title.defaultMessage); }); test('should render using given component', () => { const props = { ...baseProps, }; const wrapper = mountWithIntl( <LocalizedIcon component='span' {...props} />, ); expect(wrapper.find('i').exists()).toBe(false); expect(wrapper.find('span').exists()).toBe(true); expect(wrapper.find('span').prop('title')).toBe(baseProps.title.defaultMessage); }); test('should pass other props to component', () => { const props = { ...baseProps, className: 'my-icon', }; const wrapper = mountWithIntl(<LocalizedIcon {...props}/>); expect(wrapper.find('i').prop('className')).toBe(props.className); }); });
749
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/message_submit_error.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 MessageSubmitError from 'components/message_submit_error'; describe('components/MessageSubmitError', () => { const baseProps = { handleSubmit: jest.fn(), }; it('should display the submit link if the error is for an invalid slash command', () => { const error = { message: 'No command found', server_error_id: 'api.command.execute_command.not_found.app_error', }; const submittedMessage = 'fakecommand some text'; const props = { ...baseProps, error, submittedMessage, }; const wrapper = shallow( <MessageSubmitError {...props}/>, ); expect(wrapper.find('[id="message_submit_error.invalidCommand"]').exists()).toBe(true); expect(wrapper.text()).not.toEqual('No command found'); }); it('should not display the submit link if the error is not for an invalid slash command', () => { const error = { message: 'Some server error', server_error_id: 'api.other_error', }; const submittedMessage = '/fakecommand some text'; const props = { ...baseProps, error, submittedMessage, }; const wrapper = shallow( <MessageSubmitError {...props}/>, ); expect(wrapper.find('[id="message_submit_error.invalidCommand"]').exists()).toBe(false); expect(wrapper.text()).toEqual('Some server error'); }); });
753
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/overlay_trigger.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 {OverlayTrigger as BaseOverlayTrigger} from 'react-bootstrap'; // eslint-disable-line no-restricted-imports import {FormattedMessage, IntlProvider} from 'react-intl'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import OverlayTrigger from './overlay_trigger'; describe('OverlayTrigger', () => { const testId = 'test.value'; const intlProviderProps = { defaultLocale: 'en', locale: 'en', messages: { [testId]: 'Actual value', }, }; const baseProps = { overlay: ( <FormattedMessage id={testId} defaultMessage='Default value' /> ), }; // Intercept console error messages since we intentionally cause some as part of these tests let originalConsoleError: () => void; beforeEach(() => { originalConsoleError = console.error; console.error = jest.fn(); }); afterEach(() => { console.error = originalConsoleError; }); test('base OverlayTrigger should fail to pass intl to overlay', () => { const wrapper = mount( <IntlProvider {...intlProviderProps}> <BaseOverlayTrigger {...baseProps}> <span/> </BaseOverlayTrigger> </IntlProvider>, ); // console.error will have been called by FormattedMessage because its intl context is missing expect(() => { mount(wrapper.find(BaseOverlayTrigger).prop('overlay')); }).toThrow('[React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.'); }); test('custom OverlayTrigger should pass intl to overlay', () => { const wrapper = mount( <IntlProvider {...intlProviderProps}> <OverlayTrigger {...baseProps}> <span/> </OverlayTrigger> </IntlProvider>, ); const overlay = mount(wrapper.find(BaseOverlayTrigger).prop('overlay')); expect(overlay.text()).toBe('Actual value'); expect(console.error).not.toHaveBeenCalled(); }); test('ref should properly be forwarded', () => { const ref = React.createRef<BaseOverlayTrigger>(); const props = { ...baseProps, ref, }; const wrapper = mountWithIntl( <IntlProvider {...intlProviderProps}> <OverlayTrigger {...props}> <span/> </OverlayTrigger> </IntlProvider>, ); expect(ref.current).toBe(wrapper.find(BaseOverlayTrigger).instance()); }); test('style and className should correctly be passed to overlay', () => { const props = { ...baseProps, overlay: ( <span className='test-overlay-className' style={{backgroundColor: 'red'}} > {'test-overlay'} </span> ), defaultOverlayShown: true, // Make sure the overlay is visible }; const wrapper = mount( <IntlProvider {...intlProviderProps}> <OverlayTrigger {...props}> <span/> </OverlayTrigger> </IntlProvider>, ); // Dive into the react-bootstrap internals to find our overlay const overlay = mount((wrapper.find(BaseOverlayTrigger).instance() as any)._overlay).find('span'); // eslint-disable-line no-underscore-dangle // Confirm that we've found the right span expect(overlay.exists()).toBe(true); expect(overlay.text()).toBe('test-overlay'); // Confirm that our props are included expect(overlay.prop('className')).toContain('test-overlay-className'); expect(overlay.prop('style')).toMatchObject({backgroundColor: 'red'}); // And confirm that react-bootstrap's props are included expect(overlay.prop('className')).toContain('fade in'); expect(overlay.prop('placement')).toBe('right'); expect(overlay.prop('positionTop')).toBe(0); }); test('disabled and style should both be supported', () => { const props = { ...baseProps, overlay: ( <span style={{backgroundColor: 'red'}} > {'test-overlay'} </span> ), defaultOverlayShown: true, // Make sure the overlay is visible disabled: true, }; const wrapper = mount( <IntlProvider {...intlProviderProps}> <OverlayTrigger {...props}> <span/> </OverlayTrigger> </IntlProvider>, ); // Dive into the react-bootstrap internals to find our overlay const overlay = mount((wrapper.find(BaseOverlayTrigger).instance() as any)._overlay).find('span'); // eslint-disable-line no-underscore-dangle // Confirm that we've found the right span expect(overlay.exists()).toBe(true); expect(overlay.text()).toBe('test-overlay'); // Confirm that our props are included expect(overlay.prop('style')).toMatchObject({backgroundColor: 'red', visibility: 'hidden'}); }); });
758
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/post_deleted_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import PostDeletedModal from 'components/post_deleted_modal'; describe('components/ChannelInfoModal', () => { const baseProps = { onExited: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <PostDeletedModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
760
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/root_portal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {render} from 'tests/react_testing_utils'; import RootPortal from './root_portal'; describe('components/RootPortal', () => { beforeEach(() => { // Quick fix to disregard console error when unmounting a component console.error = jest.fn(); }); test('should match snapshot', () => { const rootPortalDiv = document.createElement('div'); rootPortalDiv.id = 'root-portal'; const {getByText, container} = render( <RootPortal> <div>{'Testing Portal'}</div> </RootPortal>, {container: document.body.appendChild(rootPortalDiv)}, ); expect(getByText('Testing Portal')).toBeVisible(); expect(container).toMatchSnapshot(); }); });
762
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/save_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import SaveButton from 'components/save_button'; describe('components/SaveButton', () => { const baseProps = { saving: false, }; test('should match snapshot, on defaultMessage', () => { const wrapper = shallow( <SaveButton {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('button').first().props().disabled).toBe(false); wrapper.setProps({defaultMessage: 'Go'} as any); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on savingMessage', () => { const props = {...baseProps, saving: true, disabled: true}; const wrapper = shallow( <SaveButton {...props}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('button').first().props().disabled).toBe(true); wrapper.setProps({savingMessage: 'Saving Config...'} as any); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, extraClasses', () => { const props = {...baseProps, extraClasses: 'some-class'}; const wrapper = shallow( <SaveButton {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
764
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/searchable_channel_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {SearchableChannelList} from 'components/searchable_channel_list'; import {type MockIntl} from 'tests/helpers/intl-test-helper'; import {Filter} from './browse_channels/browse_channels'; describe('components/SearchableChannelList', () => { const baseProps = { channels: [], isSearch: false, channelsPerPage: 10, nextPage: jest.fn(), search: jest.fn(), handleJoin: jest.fn(), loading: true, toggleArchivedChannels: jest.fn(), closeModal: jest.fn(), hideJoinedChannelsPreference: jest.fn(), changeFilter: jest.fn(), myChannelMemberships: {}, canShowArchivedChannels: false, rememberHideJoinedChannelsChecked: false, noResultsText: <>{'no channel found'}</>, filter: Filter.All, intl: { formatMessage: jest.fn(), } as MockIntl, }; test('should match init snapshot', () => { const wrapper = shallow( <SearchableChannelList {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should set page to 0 when starting search', () => { const wrapper = shallow( <SearchableChannelList {...baseProps}/>, ); wrapper.setState({page: 10}); wrapper.setProps({isSearch: true}); expect(wrapper.state('page')).toEqual(0); }); });
767
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/setting_item_max.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 SettingItemMax from 'components/setting_item_max'; import Constants from 'utils/constants'; describe('components/SettingItemMax', () => { const baseProps = { inputs: ['input_1'], clientError: '', serverError: '', infoPosition: 'bottom', section: 'section', updateSection: jest.fn(), setting: 'setting', submit: jest.fn(), saving: false, title: 'title', width: 'full', }; test('should match snapshot', () => { const wrapper = shallow(<SettingItemMax {...baseProps}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, without submit', () => { const props = {...baseProps, submit: null}; const wrapper = shallow(<SettingItemMax {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on clientError', () => { const props = {...baseProps, clientError: 'clientError'}; const wrapper = shallow(<SettingItemMax {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on serverError', () => { const props = {...baseProps, serverError: 'serverError'}; const wrapper = shallow(<SettingItemMax {...props}/>); expect(wrapper).toMatchSnapshot(); }); test('should have called updateSection on handleUpdateSection with section', () => { const updateSection = jest.fn(); const props = {...baseProps, updateSection}; const wrapper = shallow(<SettingItemMax {...props}/>); const instance = wrapper.instance() as SettingItemMax; const event = { preventDefault: jest.fn(), } as unknown as React.MouseEvent<HTMLButtonElement>; instance.handleUpdateSection(event); expect(updateSection).toHaveBeenCalled(); expect(updateSection).toHaveBeenCalledWith('section'); }); test('should have called updateSection on handleUpdateSection with empty string', () => { const updateSection = jest.fn(); const props = {...baseProps, updateSection, section: ''}; const wrapper = shallow(<SettingItemMax {...props}/>); const instance = wrapper.instance() as SettingItemMax; const event = { preventDefault: jest.fn(), } as unknown as React.MouseEvent<HTMLButtonElement>; instance.handleUpdateSection(event); expect(updateSection).toHaveBeenCalled(); expect(updateSection).toHaveBeenCalledWith(''); }); test('should have called submit on handleSubmit with setting', () => { const submit = jest.fn(); const props = {...baseProps, submit}; const wrapper = shallow(<SettingItemMax {...props}/>); const instance = wrapper.instance() as SettingItemMax; const event = { preventDefault: jest.fn(), } as unknown as React.MouseEvent<HTMLButtonElement>; instance.handleSubmit(event); expect(submit).toHaveBeenCalled(); expect(submit).toHaveBeenCalledWith('setting'); }); test('should have called submit on handleSubmit with empty string', () => { const submit = jest.fn(); const props = {...baseProps, submit, setting: ''}; const wrapper = shallow(<SettingItemMax {...props}/>); const instance = wrapper.instance() as SettingItemMax; const event = { preventDefault: jest.fn(), } as unknown as React.MouseEvent<HTMLButtonElement>; instance.handleSubmit(event); expect(submit).toHaveBeenCalled(); expect(submit).toHaveBeenCalledWith(); }); it('should have called submit on handleSubmit onKeyDown ENTER', () => { const submit = jest.fn(); const props = {...baseProps, submit}; const wrapper = shallow(<SettingItemMax {...props}/>); const instance = wrapper.instance() as SettingItemMax; instance.onKeyDown({ preventDefault: jest.fn(), key: Constants.KeyCodes.ENTER[0], target: { tagName: 'SELECT', classList: {contains: jest.fn()}, parentElement: {className: 'react-select__input'}, }, } as unknown as KeyboardEvent); expect(submit).toHaveBeenCalledTimes(0); instance.settingList = { current: { contains: jest.fn(() => true), } as unknown as HTMLDivElement, }; instance.onKeyDown({ preventDefault: jest.fn(), key: Constants.KeyCodes.ENTER[0], target: { tagName: '', classList: {contains: jest.fn()}, parentElement: {className: ''}, }, } as unknown as KeyboardEvent); expect(submit).toHaveBeenCalledTimes(1); expect(submit).toHaveBeenCalledWith('setting'); }); test('should match snapshot, with new saveTextButton', () => { const props = {...baseProps, saveButtonText: 'CustomText'}; const wrapper = shallow(<SettingItemMax {...props}/>); expect(wrapper).toMatchSnapshot(); }); });
769
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/setting_item_min.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 SettingItemMin from './setting_item_min'; describe('components/SettingItemMin', () => { const baseProps = { title: 'title', disableOpen: false, section: 'section', updateSection: jest.fn(), describe: 'describe', isMobileView: false, actions: { updateActiveSection: jest.fn(), }, }; test('should match snapshot', () => { const wrapper = shallow( <SettingItemMin {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on disableOpen to true', () => { const props = {...baseProps, disableOpen: true}; const wrapper = shallow( <SettingItemMin {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should have called updateSection on handleClick with section', () => { const updateSection = jest.fn(); const props = {...baseProps, updateSection}; const wrapper = shallow<SettingItemMin>( <SettingItemMin {...props}/>, ); wrapper.instance().handleClick({preventDefault: jest.fn()} as any); expect(updateSection).toHaveBeenCalled(); expect(updateSection).toHaveBeenCalledWith('section'); }); test('should have called updateSection on handleClick with empty string', () => { const updateSection = jest.fn(); const props = {...baseProps, updateSection, section: ''}; const wrapper = shallow<SettingItemMin>( <SettingItemMin {...props}/>, ); wrapper.instance().handleClick({preventDefault: jest.fn()} as any); expect(updateSection).toHaveBeenCalled(); expect(updateSection).toHaveBeenCalledWith(''); }); });
771
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/setting_picture.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {ReactNode} from 'react'; import {FormattedMessage} from 'react-intl'; import SettingPicture from 'components/setting_picture'; const helpText: ReactNode = ( <FormattedMessage id={'setting_picture.help.profile.example'} defaultMessage='Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}' values={{max: 52428800}} /> ); describe('components/SettingItemMin', () => { const baseProps = { clientError: '', serverError: '', src: 'http://localhost:8065/api/v4/users/src_id', loadingPicture: false, submitActive: false, onSubmit: jest.fn(), title: 'Profile Picture', onFileChange: jest.fn(), updateSection: jest.fn(), maxFileSize: 209715200, helpText, }; const mockFile = new File([new Blob()], 'image.jpeg', { type: 'image/jpeg', }); test('should match snapshot, profile picture on source', () => { const wrapper = shallow( <SettingPicture {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, profile picture on file', () => { const props = {...baseProps, file: mockFile, src: ''}; const wrapper = shallow( <SettingPicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, user icon on source', () => { const props = {...baseProps, onSetDefault: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, team icon on source', () => { const props = {...baseProps, onRemove: jest.fn(), imageContext: 'team'}; const wrapper = shallow( <SettingPicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, team icon on file', () => { const props = {...baseProps, onRemove: jest.fn(), imageContext: 'team', file: mockFile, src: ''}; const wrapper = shallow( <SettingPicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot, on loading picture', () => { const props = {...baseProps, loadingPicture: true}; const wrapper = shallow( <SettingPicture {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with active Save button', () => { const props = {...baseProps, submitActive: true}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({removeSrc: false}); expect(wrapper).toMatchSnapshot(); wrapper.setProps({submitActive: false}); wrapper.setState({removeSrc: true}); expect(wrapper).toMatchSnapshot(); }); test('should match state and call props.updateSection on handleCancel', () => { const props = {...baseProps, updateSection: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({removeSrc: true}); const instance = wrapper.instance() as SettingPicture; const evt = {preventDefault: jest.fn()} as unknown as React.MouseEvent<HTMLButtonElement>; instance.handleCancel(evt); expect(props.updateSection).toHaveBeenCalledTimes(1); expect(props.updateSection).toHaveBeenCalledWith(evt); wrapper.update(); expect(wrapper.state('removeSrc')).toEqual(false); }); test('should call props.onRemove on handleSave', () => { const props = {...baseProps, onRemove: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({removeSrc: true}); const instance = wrapper.instance() as SettingPicture; const evt = {preventDefault: jest.fn()} as unknown as React.MouseEvent; instance.handleSave(evt); expect(props.onRemove).toHaveBeenCalledTimes(1); }); test('should call props.onSetDefault on handleSave', () => { const props = {...baseProps, onSetDefault: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({setDefaultSrc: true}); const instance = wrapper.instance() as SettingPicture; const evt = {preventDefault: jest.fn()} as unknown as React.MouseEvent; instance.handleSave(evt); expect(props.onSetDefault).toHaveBeenCalledTimes(1); }); test('should match state and call props.onSubmit on handleSave', () => { const props = {...baseProps, onSubmit: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({removeSrc: false}); const instance = wrapper.instance() as SettingPicture; const evt = {preventDefault: jest.fn()} as unknown as React.MouseEvent; instance.handleSave(evt); expect(props.onSubmit).toHaveBeenCalledTimes(1); wrapper.update(); expect(wrapper.state('removeSrc')).toEqual(false); }); test('should match state on handleRemoveSrc', () => { const props = {...baseProps, onSubmit: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({removeSrc: false}); const instance = wrapper.instance() as SettingPicture; const evt = {preventDefault: jest.fn()} as unknown as React.MouseEvent; instance.handleRemoveSrc(evt); wrapper.update(); expect(wrapper.state('removeSrc')).toEqual(true); }); test('should match state and call props.onFileChange on handleFileChange', () => { const props = {...baseProps, onFileChange: jest.fn()}; const wrapper = shallow( <SettingPicture {...props}/>, ); wrapper.setState({removeSrc: true}); const instance = wrapper.instance() as SettingPicture; const evt = {preventDefault: jest.fn()} as unknown as React.ChangeEvent<HTMLInputElement>; instance.handleFileChange(evt); expect(props.onFileChange).toHaveBeenCalledTimes(1); expect(props.onFileChange).toHaveBeenCalledWith(evt); wrapper.update(); expect(wrapper.state('removeSrc')).toEqual(false); }); });
777
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/spinner_button.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {mount, shallow} from 'enzyme'; import React from 'react'; import SpinnerButton from 'components/spinner_button'; describe('components/SpinnerButton', () => { test('should match snapshot with required props', () => { const wrapper = shallow( <SpinnerButton spinning={false} spinningText='Test' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with spinning', () => { const wrapper = shallow( <SpinnerButton spinning={true} spinningText='Test' />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with children', () => { const wrapper = shallow( <SpinnerButton spinning={false} spinningText='Test' > <span id='child1'/> <span id='child2'/> </SpinnerButton>, ); expect(wrapper).toMatchSnapshot(); }); test('should handle onClick', () => { const onClick = jest.fn(); const wrapper = mount( <SpinnerButton spinning={false} onClick={onClick} spinningText='Test' />, ); wrapper.find('button').simulate('click'); expect(onClick).toHaveBeenCalledTimes(1); }); test('should add properties to underlying button', () => { const wrapper = mount( <SpinnerButton id='my-button-id' className='btn btn-success' spinningText='Test' spinning={false} />, ); const button = wrapper.find('button'); expect(button).not.toBeUndefined(); expect(button.type()).toEqual('button'); expect(button.props().id).toEqual('my-button-id'); expect(button.hasClass('btn')).toBeTruthy(); expect(button.hasClass('btn-success')).toBeTruthy(); }); });
781
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/textbox.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/textbox'; describe('components/TextBox', () => { const baseProps = { channelId: 'channelId', rootId: 'rootId', currentUserId: 'currentUserId', currentTeamId: 'currentTeamId', profilesInChannel: [ {id: 'id1'}, {id: 'id2'}, ], delayChannelAutocomplete: false, autocompleteGroups: [ {id: 'gid1'}, {id: 'gid2'}, ], actions: { autocompleteUsersInChannel: jest.fn(), autocompleteChannels: jest.fn(), searchAssociatedGroupsForReference: jest.fn(), }, useChannelMentions: true, tabIndex: 0, }; test('should match snapshot with required props', () => { function emptyFunction() {} //eslint-disable-line no-empty-function const wrapper = shallow( <Textbox id='someid' value='some test text' onChange={emptyFunction} onKeyPress={emptyFunction} characterLimit={4000} createMessage='placeholder text' supportsCommands={false} {...baseProps} />, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with additional, optional props', () => { function emptyFunction() {} //eslint-disable-line no-empty-function const wrapper = shallow( <Textbox id='someid' value='some test text' onChange={emptyFunction} onKeyPress={emptyFunction} characterLimit={4000} createMessage='placeholder text' supportsCommands={false} {...baseProps} rootId='root_id' onComposition={() => {}} onHeightChange={() => {}} onKeyDown={() => {}} onMouseUp={() => {}} onKeyUp={() => {}} onBlur={() => {}} handlePostError={() => {}} suggestionListPosition='top' emojiEnabled={true} disabled={true} badConnection={true} preview={true} openWhenEmpty={true} />, ); expect(wrapper).toMatchSnapshot(); }); test('should throw error when value is too long', () => { function emptyFunction() {} //eslint-disable-line no-empty-function // this mock function should be called when the textbox value is too long let gotError = false; function handlePostError(msg: React.ReactNode) { gotError = msg !== null; } const wrapper = shallow( <Textbox id='someid' value='some test text that exceeds char limit' onChange={emptyFunction} onKeyPress={emptyFunction} characterLimit={14} createMessage='placeholder text' supportsCommands={false} handlePostError={handlePostError} {...baseProps} />, ); expect(gotError).toEqual(true); expect(wrapper).toMatchSnapshot(); }); test('should throw error when new property is too long', () => { function emptyFunction() {} //eslint-disable-line no-empty-function // this mock function should be called when the textbox value is too long let gotError = false; function handlePostError(msg: React.ReactNode) { gotError = msg !== null; } const wrapper = shallow( <Textbox id='someid' value='some test text' onChange={emptyFunction} onKeyPress={emptyFunction} characterLimit={14} createMessage='placeholder text' supportsCommands={false} handlePostError={handlePostError} {...baseProps} />, ); wrapper.setProps({value: 'some test text that exceeds char limit'}); wrapper.update(); expect(gotError).toEqual(true); expect(wrapper).toMatchSnapshot(); }); });
783
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/toggle_modal_button.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 {FormattedMessage} from 'react-intl'; import {mountWithIntl} from 'tests/helpers/intl-test-helper'; import {ModalIdentifiers} from 'utils/constants'; import ToggleModalButton from './toggle_modal_button'; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux') as typeof import('react-redux'), useDispatch: () => jest.fn(), })); class TestModal extends React.PureComponent { render() { return ( <Modal show={true} onHide={jest.fn()} > <Modal.Header closeButton={true}/> <Modal.Body/> </Modal> ); } } describe('components/ToggleModalButton', () => { test('component should match snapshot', () => { const wrapper = mountWithIntl( <ToggleModalButton ariaLabel={'Delete Channel'} id='channelDelete' role='menuitem' modalId={ModalIdentifiers.DELETE_CHANNEL} dialogType={TestModal} > <FormattedMessage id='channel_header.delete' defaultMessage='Delete Channel' /> </ToggleModalButton>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('button span').first().html()).toBe('<span>Delete Channel</span>'); }); });
786
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/components/user_list.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {TestHelper} from 'utils/test_helper'; import UserList from './user_list'; describe('components/UserList', () => { test('should match default snapshot', () => { const props = { actionProps: { mfaEnabled: false, enableUserAccessTokens: false, experimentalEnableAuthenticationTransfer: false, doPasswordReset: jest.fn(), doEmailReset: jest.fn(), doManageTeams: jest.fn(), doManageRoles: jest.fn(), doManageTokens: jest.fn(), isDisabled: false, }, }; const wrapper = shallow( <UserList {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match default snapshot when there are users', () => { const User1 = TestHelper.getUserMock({id: 'id1'}); const User2 = TestHelper.getUserMock({id: 'id2'}); const props = { users: [ User1, User2, ], actionUserProps: {}, actionProps: { mfaEnabled: false, enableUserAccessTokens: false, experimentalEnableAuthenticationTransfer: false, doPasswordReset: jest.fn(), doEmailReset: jest.fn(), doManageTeams: jest.fn(), doManageRoles: jest.fn(), doManageTokens: jest.fn(), isDisabled: false, }, }; const wrapper = shallow( <UserList {...props}/>, ); expect(wrapper).toMatchSnapshot(); }); });
788
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/alert_banner.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Components/AlertBanner should match snapshot 1`] = ` <div className="AlertBanner info AlertBanner--sys" > <div className="AlertBanner__icon" > <InformationOutlineIcon size={24} /> </div> <div className="AlertBanner__body" > <div className="AlertBanner__title" > title </div> <div className="AlertBanner__message" > message </div> </div> </div> `; exports[`Components/AlertBanner should match snapshot for app variant 1`] = ` <div className="AlertBanner info AlertBanner--app" > <div className="AlertBanner__icon" > <InformationOutlineIcon size={24} /> </div> <div className="AlertBanner__body" > <div className="AlertBanner__title" > title </div> <div className="AlertBanner__message" > message </div> </div> </div> `; exports[`Components/AlertBanner should match snapshot when buttons are passed 1`] = ` <div className="AlertBanner info AlertBanner--app" > <div className="AlertBanner__body" > <div className="AlertBanner__title" > title </div> <div className="AlertBanner__message" > message </div> <div className="AlertBanner__actionButtons" > <div id="actionButtonLeft" /> <div id="actionButtonRight" /> </div> </div> </div> `; exports[`Components/AlertBanner should match snapshot when icon disabled 1`] = ` <div className="AlertBanner info AlertBanner--app" > <div className="AlertBanner__body" > <div className="AlertBanner__title" > title </div> <div className="AlertBanner__message" > message </div> </div> </div> `;
789
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/autosize_textarea.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/AutosizeTextarea should match snapshot, init 1`] = ` <div> <div data-testid="autosize_textarea_placeholder" id="autosize_textarea_placeholder" style={ Object { "background": "none", "borderColor": "transparent", "opacity": 0.5, "overflow": "hidden", "pointerEvents": "none", "position": "absolute", "textOverflow": "ellipsis", "whiteSpace": "nowrap", } } /> <textarea aria-label="" data-testid="autosize_textarea" dir="auto" height={0} id="autosize_textarea" role="textbox" rows={1} /> <div style={ Object { "height": 0, "overflow": "hidden", } } > <div aria-hidden={true} dir="auto" disabled={true} id="autosize_textarea-reference" style={ Object { "display": "inline-block", "height": "auto", "width": "auto", } } /> </div> </div> `;
790
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/color_input.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ColorInput should match snapshot, click on picker 1`] = ` <div className="color-input input-group" > <input className="form-control" data-testid="color-inputColorValue" id="sidebarBg-inputColorValue" maxLength={7} onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onKeyDown={[Function]} type="text" value="#ffffff" /> <span className="input-group-addon color-pad" id="sidebarBg-squareColorIcon" onClick={[Function]} > <i className="color-icon" id="sidebarBg-squareColorIconValue" style={ Object { "backgroundColor": "#ffffff", } } /> </span> <div className="color-popover" id="sidebarBg-ChromePickerModal" > <ColorPicker color="#ffffff" disableAlpha={true} onChange={[Function]} styles={Object {}} width={225} /> </div> </div> `; exports[`components/ColorInput should match snapshot, init 1`] = ` <div className="color-input input-group" > <input className="form-control" data-testid="color-inputColorValue" id="sidebarBg-inputColorValue" maxLength={7} onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onKeyDown={[Function]} type="text" value="#ffffff" /> <span className="input-group-addon color-pad" id="sidebarBg-squareColorIcon" onClick={[Function]} > <i className="color-icon" id="sidebarBg-squareColorIconValue" style={ Object { "backgroundColor": "#ffffff", } } /> </span> </div> `; exports[`components/ColorInput should match snapshot, opened 1`] = ` <div className="color-input input-group" > <input className="form-control" data-testid="color-inputColorValue" id="sidebarBg-inputColorValue" maxLength={7} onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onKeyDown={[Function]} type="text" value="#ffffff" /> <span className="input-group-addon color-pad" id="sidebarBg-squareColorIcon" onClick={[Function]} > <i className="color-icon" id="sidebarBg-squareColorIconValue" style={ Object { "backgroundColor": "#ffffff", } } /> </span> <div className="color-popover" id="sidebarBg-ChromePickerModal" > <ColorPicker color="#ffffff" disableAlpha={true} onChange={[Function]} styles={Object {}} width={225} /> </div> </div> `; exports[`components/ColorInput should match snapshot, toggle picker 1`] = ` <div className="color-input input-group" > <input className="form-control" data-testid="color-inputColorValue" id="sidebarBg-inputColorValue" maxLength={7} onBlur={[Function]} onChange={[Function]} onFocus={[Function]} onKeyDown={[Function]} type="text" value="#ffffff" /> <span className="input-group-addon color-pad" id="sidebarBg-squareColorIcon" onClick={[Function]} > <i className="color-icon" id="sidebarBg-squareColorIconValue" style={ Object { "backgroundColor": "#ffffff", } } /> </span> </div> `;
791
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/file_upload_overlay.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/FileUploadOverlay should match snapshot when file upload is showing with no overlay type 1`] = ` <div className="file-overlay hidden" > <div className="overlay__indent" > <div className="overlay__circle" > <img alt="Files" className="overlay__files" src={null} /> <span> <i className="fa fa-upload" title="Upload Icon" /> <MemoizedFormattedMessage defaultMessage="Drop a file to upload it." id="upload_overlay.info" /> </span> <img alt="Logo" className="overlay__logo" src={null} /> </div> </div> </div> `; exports[`components/FileUploadOverlay should match snapshot when file upload is showing with overlay type of center 1`] = ` <div className="file-overlay hidden center-file-overlay" > <div className="overlay__indent" > <div className="overlay__circle" > <img alt="Files" className="overlay__files" src={null} /> <span> <i className="fa fa-upload" title="Upload Icon" /> <MemoizedFormattedMessage defaultMessage="Drop a file to upload it." id="upload_overlay.info" /> </span> <img alt="Logo" className="overlay__logo" src={null} /> </div> </div> </div> `; exports[`components/FileUploadOverlay should match snapshot when file upload is showing with overlay type of right 1`] = ` <div className="file-overlay hidden right-file-overlay" > <div className="overlay__indent" > <div className="overlay__circle" > <img alt="Files" className="overlay__files" src={null} /> <span> <i className="fa fa-upload" title="Upload Icon" /> <MemoizedFormattedMessage defaultMessage="Drop a file to upload it." id="upload_overlay.info" /> </span> <img alt="Logo" className="overlay__logo" src={null} /> </div> </div> </div> `;
792
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/formatted_markdown_message.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/FormattedMarkdownMessage should allow to disable links 1`] = ` <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={ Object { "test.bar": "<b>hello</b> <script>var malicious = true;</script> world!", "test.foo": "**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)", "test.vals": "*Hi* {petName}!", } } onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <FormattedMarkdownMessage defaultMessage="*Hi* {petName}!" disableLinks={true} id="test.vals" values={ Object { "petName": "http://www.mattermost.com", } } > <span dangerouslySetInnerHTML={ Object { "__html": "<em>Hi</em> http://www.mattermost.com!", } } /> </FormattedMarkdownMessage> </IntlProvider> `; exports[`components/FormattedMarkdownMessage should backup to default 1`] = ` <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={ Object { "test.bar": "<b>hello</b> <script>var malicious = true;</script> world!", "test.foo": "**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)", "test.vals": "*Hi* {petName}!", } } onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <FormattedMarkdownMessage defaultMessage="testing default message" id="xxx" > <span dangerouslySetInnerHTML={ Object { "__html": "testing default message", } } /> </FormattedMarkdownMessage> </IntlProvider> `; exports[`components/FormattedMarkdownMessage should escape non-BR 1`] = ` <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={ Object { "test.bar": "<b>hello</b> <script>var malicious = true;</script> world!", "test.foo": "**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)", "test.vals": "*Hi* {petName}!", } } onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <FormattedMarkdownMessage defaultMessage="" id="test.bar" values={ Object { "b": [Function], "script": [Function], } } > <span dangerouslySetInnerHTML={ Object { "__html": "&lt;b&gt;hello&lt;/b&gt; &lt;script&gt;var malicious = true;&lt;/script&gt; world!", } } /> </FormattedMarkdownMessage> </IntlProvider> `; exports[`components/FormattedMarkdownMessage should render message 1`] = ` <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={ Object { "test.bar": "<b>hello</b> <script>var malicious = true;</script> world!", "test.foo": "**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)", "test.vals": "*Hi* {petName}!", } } onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <FormattedMarkdownMessage defaultMessage="**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)" id="test.foo" > <span dangerouslySetInnerHTML={ Object { "__html": "<strong>bold</strong> <em>italic</em> <a href=\\"https://mattermost.com/\\" rel=\\"noopener noreferrer\\" target=\\"_blank\\">link</a> &lt;br/&gt; <a href=\\"https://mattermost.com/\\" rel=\\"noopener noreferrer\\" target=\\"_blank\\">link target blank</a>", } } /> </FormattedMarkdownMessage> </IntlProvider> `; exports[`components/FormattedMarkdownMessage values should work 1`] = ` <IntlProvider defaultFormats={Object {}} defaultLocale="en" fallbackOnEmptyString={true} formats={Object {}} locale="en" messages={ Object { "test.bar": "<b>hello</b> <script>var malicious = true;</script> world!", "test.foo": "**bold** *italic* [link](https://mattermost.com/) <br/> [link target blank](!https://mattermost.com/)", "test.vals": "*Hi* {petName}!", } } onError={[Function]} onWarn={[Function]} textComponent={Symbol(react.fragment)} > <FormattedMarkdownMessage defaultMessage="*Hi* {petName}!" id="test.vals" values={ Object { "petName": "sweetie", } } > <span dangerouslySetInnerHTML={ Object { "__html": "<em>Hi</em> sweetie!", } } /> </FormattedMarkdownMessage> </IntlProvider> `;
793
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/get_link_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/GetLinkModal should have called onHide 1`] = ` <Modal animation={true} aria-labelledby="getLinkModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" id="getLinkModalLabel" > <h4 className="modal-title" > title </h4> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <textarea className="form-control no-resize min-height" dir="auto" id="linkModalTextArea" onClick={[Function]} readOnly={true} value="https://mattermost.com" /> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-tertiary" id="linkModalCloseButton" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="get_link.close" /> </button> <button className="btn btn-primary pull-left" data-copy-btn="true" id="linkModalCopyLink" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Copy Link" id="get_link.copy" /> </button> <p className="alert alert-success alert--confirm" > <SuccessIcon /> <MemoizedFormattedMessage defaultMessage=" Link copied" id="get_link.clipboard" /> </p> </ModalFooter> </Modal> `; exports[`components/GetLinkModal should have called onHide 2`] = ` <Modal animation={true} aria-labelledby="getLinkModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" id="getLinkModalLabel" > <h4 className="modal-title" > title </h4> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <textarea className="form-control no-resize min-height" dir="auto" id="linkModalTextArea" onClick={[Function]} readOnly={true} value="https://mattermost.com" /> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-tertiary" id="linkModalCloseButton" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="get_link.close" /> </button> <button className="btn btn-primary pull-left" data-copy-btn="true" id="linkModalCopyLink" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Copy Link" id="get_link.copy" /> </button> </ModalFooter> </Modal> `; exports[`components/GetLinkModal should match snapshot when all props is set 1`] = ` <Modal animation={true} aria-labelledby="getLinkModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" id="getLinkModalLabel" > <h4 className="modal-title" > title </h4> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <p> help text <br /> <br /> </p> <textarea className="form-control no-resize min-height" dir="auto" id="linkModalTextArea" onClick={[Function]} readOnly={true} value="https://mattermost.com" /> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-tertiary" id="linkModalCloseButton" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="get_link.close" /> </button> <button className="btn btn-primary pull-left" data-copy-btn="true" id="linkModalCopyLink" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Copy Link" id="get_link.copy" /> </button> </ModalFooter> </Modal> `; exports[`components/GetLinkModal should match snapshot when helpText is not set 1`] = ` <Modal animation={true} aria-labelledby="getLinkModalLabel" autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" id="getLinkModalLabel" > <h4 className="modal-title" > title </h4> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <textarea className="form-control no-resize min-height" dir="auto" id="linkModalTextArea" onClick={[Function]} readOnly={true} value="https://mattermost.com" /> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button className="btn btn-tertiary" id="linkModalCloseButton" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="get_link.close" /> </button> <button className="btn btn-primary pull-left" data-copy-btn="true" id="linkModalCopyLink" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Copy Link" id="get_link.copy" /> </button> </ModalFooter> </Modal> `;
794
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/list_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ListModal should match snapshot 1`] = ` <div> <Modal animation={true} autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-modal--action" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" > <span className="name" > list modal </span> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="filtered-user-list" > <div className="filter-row" > <div className="col-xs-12" > <label className="hidden-label" htmlFor="searchUsersInput" > search for name </label> <input className="form-control filter-textbox" id="searchUsersInput" onChange={[Function]} placeholder="search for name" /> </div> <div className="col-sm-12" > <span className="member-count pull-left" > <MemoizedFormattedMessage defaultMessage="{startCount, number} - {endCount, number} of {total, number} total" id="list_modal.paginatorCount" values={ Object { "endCount": 0, "startCount": 0, "total": 0, } } /> </span> </div> </div> <div className="more-modal__list" > <div> <div> <LoadingScreen key="loading" position="absolute" /> </div> </div> </div> <div className="filter-controls" /> </div> </ModalBody> </Modal> </div> `; exports[`components/ListModal should match snapshot with title bar button 1`] = ` <div> <Modal animation={true} autoFocus={true} backdrop={true} bsClass="modal" dialogClassName="a11y__modal more-modal more-modal--action" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[Function]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" > <span className="name" > list modal </span> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <div className="filtered-user-list" > <div className="filter-row" > <div className="col-xs-12" > <label className="hidden-label" htmlFor="searchUsersInput" > search for name </label> <input className="form-control filter-textbox" id="searchUsersInput" onChange={[Function]} placeholder="search for name" /> </div> <div className="col-sm-12" > <span className="member-count pull-left" > <MemoizedFormattedMessage defaultMessage="{startCount, number} - {endCount, number} of {total, number} total" id="list_modal.paginatorCount" values={ Object { "endCount": 0, "startCount": 0, "total": 0, } } /> </span> </div> </div> <div className="more-modal__list" > <div> <div> <LoadingScreen key="loading" position="absolute" /> </div> </div> </div> <div className="filter-controls" /> </div> </ModalBody> </Modal> </div> `;
795
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/loading_image_preview.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/LoadingImagePreview should match snapshot 1`] = ` <div className="view-image__loading" > <Memo(LoadingSpinner) /> <span className="loader-percent" > Loading 50% </span> </div> `; exports[`components/LoadingImagePreview should match snapshot 2`] = ` <div className="view-image__loading" > <Memo(LoadingSpinner) /> <span className="loader-percent" > Loading 90% </span> </div> `;
797
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/post_deleted_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ChannelInfoModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="postDeletedModalLabel" autoFocus={true} backdrop={true} bsClass="modal" data-testid="postDeletedModal" dialogClassName="a11y__modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="postDeletedModalLabel" > <MemoizedFormattedMessage defaultMessage="Comment could not be posted" id="post_delete.notPosted" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <p> <MemoizedFormattedMessage defaultMessage="Someone deleted the message on which you tried to post a comment." id="post_delete.someone" /> </p> </ModalBody> <ModalFooter bsClass="modal-footer" componentClass="div" > <button autoFocus={true} className="btn btn-primary" data-testid="postDeletedModalOkButton" onClick={[Function]} type="button" > <MemoizedFormattedMessage defaultMessage="Okay" id="post_delete.okay" /> </button> </ModalFooter> </Modal> `;
798
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/root_portal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/RootPortal should match snapshot 1`] = ` <div id="root-portal" > <div> <div> Testing Portal </div> </div> </div> `;
799
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/save_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SaveButton should match snapshot, extraClasses 1`] = ` <button className="btn btn-primary some-class" data-testid="saveSetting" disabled={false} id="saveSetting" type="submit" > <Memo(LoadingWrapper) loading={false} text={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } > <span> <MemoizedFormattedMessage defaultMessage="Save" id="save_button.save" /> </span> </Memo(LoadingWrapper)> </button> `; exports[`components/SaveButton should match snapshot, on defaultMessage 1`] = ` <button className="btn btn-primary " data-testid="saveSetting" disabled={false} id="saveSetting" type="submit" > <Memo(LoadingWrapper) loading={false} text={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } > <span> <MemoizedFormattedMessage defaultMessage="Save" id="save_button.save" /> </span> </Memo(LoadingWrapper)> </button> `; exports[`components/SaveButton should match snapshot, on defaultMessage 2`] = ` <button className="btn btn-primary " data-testid="saveSetting" disabled={false} id="saveSetting" type="submit" > <Memo(LoadingWrapper) loading={false} text={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } > <span> Go </span> </Memo(LoadingWrapper)> </button> `; exports[`components/SaveButton should match snapshot, on savingMessage 1`] = ` <button className="btn btn-primary " data-testid="saveSetting" disabled={true} id="saveSetting" type="submit" > <Memo(LoadingWrapper) loading={true} text={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } > <span> <MemoizedFormattedMessage defaultMessage="Save" id="save_button.save" /> </span> </Memo(LoadingWrapper)> </button> `; exports[`components/SaveButton should match snapshot, on savingMessage 2`] = ` <button className="btn btn-primary " data-testid="saveSetting" disabled={true} id="saveSetting" type="submit" > <Memo(LoadingWrapper) loading={true} text="Saving Config..." > <span> <MemoizedFormattedMessage defaultMessage="Save" id="save_button.save" /> </span> </Memo(LoadingWrapper)> </button> `;
800
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/searchable_channel_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SearchableChannelList should match init snapshot 1`] = ` <div className="filtered-user-list" > <div className="filter-row filter-row--full" > <span aria-hidden="true" id="searchIcon" > <MagnifyIcon size={18} /> </span> <QuickInput aria-label="Search Channels" className="form-control filter-textbox" clearable={true} id="searchChannelsTextbox" onClear={[Function]} onInput={[Function]} value="" /> </div> <div className="more-modal__dropdown" > <span id="channelCountLabel" > 0 Results </span> <div id="modalPreferenceContainer" > <Menu menu={ Object { "aria-label": "Browse channels", "id": "browseChannelsDropdown", } } menuButton={ Object { "children": <React.Fragment> <Memo(MemoizedFormattedMessage) defaultMessage="Channel Type: All" id="more_channels.show_all_channels" /> <ChevronDownIcon color="rgba(var(--center-channel-color-rgb), 0.64)" size={16} /> </React.Fragment>, "id": "menuWrapper", } } > <MenuItem aria-label="All channel types" id="channelsMoreDropdownAll" key="channelsMoreDropdownAll" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="All channel types" id="suggestion.all" /> } leadingElement={ <GlobeCheckedIcon size={16} /> } onClick={[Function]} trailingElements={ <CheckIcon color="var(--button-bg)" size={18} /> } /> <MenuItem aria-label="Public channels" id="channelsMoreDropdownPublic" key="channelsMoreDropdownPublic" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Public channels" id="suggestion.public" /> } leadingElement={ <GlobeIcon size={16} /> } onClick={[Function]} trailingElements={null} /> <MenuItem aria-label="Private channels" id="channelsMoreDropdownPrivate" key="channelsMoreDropdownPrivate" labels={ <Memo(MemoizedFormattedMessage) defaultMessage="Private channels" id="suggestion.private" /> } leadingElement={ <LockOutlineIcon size={16} /> } onClick={[Function]} trailingElements={null} /> </Menu> <div id="hideJoinedPreferenceCheckbox" onClick={[Function]} > <button aria-label="Hide joined channels checkbox, not checked" className="get-app__checkbox" /> <MemoizedFormattedMessage defaultMessage="Hide Joined" id="more_channels.hide_joined" /> </div> </div> </div> <div className="more-modal__list" role="search" tabIndex={-1} > <div id="moreChannelsList" tabIndex={-1} > <LoadingScreen /> </div> </div> <div className="filter-controls" /> </div> `;
801
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/setting_item_max.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SettingItemMax should match snapshot 1`] = ` <section className="section-max form-horizontal " > <h4 className="col-sm-12 section-title" id="settingTitle" > title </h4> <div className="col-sm-12" > <div className="setting-list" tabIndex={-1} > <div className="setting-list-item" > input_1 </div> <div className="setting-list-item" > <hr /> <SaveButton btnClass="" defaultMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Save" id="save_button.save" /> } disabled={false} extraClasses="" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> <button className="btn btn-tertiary" id="cancelSetting" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_item_max.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMax should match snapshot, on clientError 1`] = ` <section className="section-max form-horizontal " > <h4 className="col-sm-12 section-title" id="settingTitle" > title </h4> <div className="col-sm-12" > <div className="setting-list" tabIndex={-1} > <div className="setting-list-item" > input_1 </div> <div className="setting-list-item" > <hr /> <div className="form-group" > <label className="col-sm-12 has-error" id="clientError" > clientError </label> </div> <SaveButton btnClass="" defaultMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Save" id="save_button.save" /> } disabled={false} extraClasses="" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> <button className="btn btn-tertiary" id="cancelSetting" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_item_max.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMax should match snapshot, on serverError 1`] = ` <section className="section-max form-horizontal " > <h4 className="col-sm-12 section-title" id="settingTitle" > title </h4> <div className="col-sm-12" > <div className="setting-list" tabIndex={-1} > <div className="setting-list-item" > input_1 </div> <div className="setting-list-item" > <hr /> <div className="form-group" > <label className="col-sm-12 has-error" id="serverError" > serverError </label> </div> <SaveButton btnClass="" defaultMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Save" id="save_button.save" /> } disabled={false} extraClasses="" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> <button className="btn btn-tertiary" id="cancelSetting" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_item_max.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMax should match snapshot, with new saveTextButton 1`] = ` <section className="section-max form-horizontal " > <h4 className="col-sm-12 section-title" id="settingTitle" > title </h4> <div className="col-sm-12" > <div className="setting-list" tabIndex={-1} > <div className="setting-list-item" > input_1 </div> <div className="setting-list-item" > <hr /> <SaveButton btnClass="" defaultMessage="CustomText" disabled={false} extraClasses="" onClick={[Function]} saving={false} savingMessage={ <Memo(MemoizedFormattedMessage) defaultMessage="Saving" id="save_button.saving" /> } /> <button className="btn btn-tertiary" id="cancelSetting" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_item_max.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMax should match snapshot, without submit 1`] = ` <section className="section-max form-horizontal " > <h4 className="col-sm-12 section-title" id="settingTitle" > title </h4> <div className="col-sm-12" > <div className="setting-list" tabIndex={-1} > <div className="setting-list-item" > input_1 </div> <div className="setting-list-item" > <hr /> <button className="btn btn-tertiary" id="cancelSetting" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_item_max.cancel" /> </button> </div> </div> </div> </section> `;
802
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/setting_item_min.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SettingItemMin should match snapshot 1`] = ` <div className="section-min" onClick={[Function]} > <div className="secion-min__header" > <h4 className="section-min__title" id="sectionTitle" > title </h4> <button aria-expanded={false} aria-labelledby="sectionTitle sectionEdit" className="color--link style--none section-min__edit" id="sectionEdit" onClick={[Function]} > <EditIcon /> <MemoizedFormattedMessage defaultMessage="Edit" id="setting_item_min.edit" /> </button> </div> <div className="section-min__describe" id="sectionDesc" > describe </div> </div> `; exports[`components/SettingItemMin should match snapshot, on disableOpen to true 1`] = ` <div className="section-min" onClick={[Function]} > <div className="secion-min__header" > <h4 className="section-min__title" id="sectionTitle" > title </h4> <button aria-expanded={false} aria-labelledby="sectionTitle sectionEdit" className="color--link style--none section-min__edit" id="sectionEdit" onClick={[Function]} > <EditIcon /> <MemoizedFormattedMessage defaultMessage="Edit" id="setting_item_min.edit" /> </button> </div> <div className="section-min__describe" id="sectionDesc" > describe </div> </div> `;
803
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/setting_picture.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SettingItemMin should match snapshot with active Save button 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <img alt="profile image" className="profile-img" src="http://localhost:8065/api/v4/users/src_id" /> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-primary" data-testid="saveSettingPicture" disabled={false} onClick={[Function]} tabIndex={0} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot with active Save button 2`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-primary" data-testid="saveSettingPicture" disabled={false} onClick={[Function]} tabIndex={0} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot, on loading picture 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <img alt="profile image" className="profile-img" src="http://localhost:8065/api/v4/users/src_id" /> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={true} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={true} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Uploading..." className="btn btn-inactive disabled" data-testid="saveSettingPicture" disabled={true} onClick={[Function]} tabIndex={-1} > <Memo(LoadingWrapper) loading={true} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot, profile picture on file 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <div className="profile-img-preview" > <div className="img-preview__image" > <div alt="profile image preview" className="profile-img-preview" style={ Object { "backgroundImage": "url(null)", } } /> </div> </div> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-inactive disabled" data-testid="saveSettingPicture" disabled={true} onClick={[Function]} tabIndex={-1} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot, profile picture on source 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <img alt="profile image" className="profile-img" src="http://localhost:8065/api/v4/users/src_id" /> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-inactive disabled" data-testid="saveSettingPicture" disabled={true} onClick={[Function]} tabIndex={-1} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot, team icon on file 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <div className="team-img-preview" > <div className="img-preview__image" > <div alt="team image preview" className="team-img-preview" style={ Object { "backgroundImage": "url(null)", } } /> </div> </div> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-inactive disabled" data-testid="saveSettingPicture" disabled={true} onClick={[Function]} tabIndex={-1} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot, team icon on source 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <div className="team-img__container" > <div aria-hidden={true} className="img-preview__image" > <img alt="team image" className="team-img" src="http://localhost:8065/api/v4/users/src_id" /> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="removeIcon" > <div aria-hidden={true} > <Memo(MemoizedFormattedMessage) defaultMessage="Remove This Icon" id="setting_picture.remove" /> </div> </Tooltip> } placement="right" trigger={ Array [ "hover", "focus", ] } > <button className="team-img__remove" data-testid="removeSettingPicture" onClick={[Function]} > <span aria-hidden={true} > × </span> <span className="sr-only" > <MemoizedFormattedMessage defaultMessage="Remove This Icon" id="setting_picture.remove" /> </span> </button> </OverlayTrigger> </div> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-inactive disabled" data-testid="saveSettingPicture" disabled={true} onClick={[Function]} tabIndex={-1} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `; exports[`components/SettingItemMin should match snapshot, user icon on source 1`] = ` <section className="section-max form-horizontal" > <h4 className="col-xs-12 section-title" > Profile Picture </h4> <div className="col-xs-offset-3 col-xs-8" > <div aria-describedby="setting-picture__helptext" aria-label="Profile Picture" className="setting-list" tabIndex={-1} > <li className="setting-list-item" role="presentation" > <div className="profile-img__container" > <div aria-hidden={true} className="img-preview__image" > <img alt="profile image" className="profile-img" src="http://localhost:8065/api/v4/users/src_id" /> </div> <OverlayTrigger defaultOverlayShown={false} delayShow={400} overlay={ <Tooltip id="removeIcon" > <div aria-hidden={true} > <Memo(MemoizedFormattedMessage) defaultMessage="Remove Profile Picture" id="setting_picture.remove_profile_picture" /> </div> </Tooltip> } placement="right" trigger={ Array [ "hover", "focus", ] } > <button className="profile-img__remove" data-testid="removeSettingPicture" onClick={[Function]} > <span aria-hidden={true} > × </span> <span className="sr-only" > <MemoizedFormattedMessage defaultMessage="Remove Profile Picture" id="setting_picture.remove_profile_picture" /> </span> </button> </OverlayTrigger> </div> </li> <div className="setting-list-item pt-3" id="setting-picture__helptext" > <MemoizedFormattedMessage defaultMessage="Upload a picture in BMP, JPG or PNG format. Maximum file size: {max}" id="setting_picture.help.profile.example" values={ Object { "max": 52428800, } } /> </div> <div className="setting-list-item" > <hr /> <FormError error={null} errors={ Array [ "", "", ] } type="modal" /> <span> <input accept=".jpeg,.jpg,.png,.bmp" aria-hidden={true} className="hidden" data-testid="uploadPicture" disabled={false} onChange={[Function]} tabIndex={-1} type="file" /> <button aria-label="Select" className="btn btn-primary btn-file" data-testid="inputSettingPictureButton" disabled={false} onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Select" id="setting_picture.select" /> </button> <button aria-label="Save" className="btn btn-inactive disabled" data-testid="saveSettingPicture" disabled={true} onClick={[Function]} tabIndex={-1} > <Memo(LoadingWrapper) loading={false} text="Uploading..." > <MemoizedFormattedMessage defaultMessage="Save" id="setting_picture.save" /> </Memo(LoadingWrapper)> </button> </span> <button aria-label="Cancel" className="btn btn-tertiary theme ml-2" data-testid="cancelSettingPicture" onClick={[Function]} > <MemoizedFormattedMessage defaultMessage="Cancel" id="setting_picture.cancel" /> </button> </div> </div> </div> </section> `;
805
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/spinner_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/SpinnerButton should match snapshot with children 1`] = ` <button disabled={false} > <Memo(LoadingWrapper) loading={false} text="Test" > <span id="child1" /> <span id="child2" /> </Memo(LoadingWrapper)> </button> `; exports[`components/SpinnerButton should match snapshot with required props 1`] = ` <button disabled={false} > <Memo(LoadingWrapper) loading={false} text="Test" /> </button> `; exports[`components/SpinnerButton should match snapshot with spinning 1`] = ` <button disabled={true} > <Memo(LoadingWrapper) loading={true} text="Test" /> </button> `;
806
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/textbox.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/TextBox should match snapshot with additional, optional props 1`] = ` <div className="textarea-wrapper textarea-wrapper-preview" > <div className="form-control custom-textarea textbox-preview-area" onBlur={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} tabIndex={0} > <Connect(PostMarkdown) channelId="channelId" imageProps={ Object { "hideUtilities": true, } } message="some test text" /> </div> <Connect(SuggestionBox) className="form-control custom-textarea textbox-edit-area custom-textarea--emoji-picker bad-connection" contextId="channelId" disabled={true} id="someid" inputComponent={ Object { "$$typeof": Symbol(react.memo), "compare": null, "type": Object { "$$typeof": Symbol(react.forward_ref), "propTypes": Object { "className": [Function], "defaultValue": [Function], "disabled": [Function], "id": [Function], "onChange": [Function], "onHeightChange": [Function], "onInput": [Function], "onWidthChange": [Function], "placeholder": [Function], "value": [Function], }, "render": [Function], }, } } listComponent={[Function]} listPosition="top" onBlur={[Function]} onChange={[Function]} onComposition={[Function]} onHeightChange={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} onKeyUp={[Function]} onMouseUp={[Function]} openWhenEmpty={true} placeholder="placeholder text" providers={ Array [ AtMentionProvider { "addLastViewAtToProfiles": [Function], "autocompleteGroups": Array [ Object { "id": "gid1", }, Object { "id": "gid2", }, ], "autocompleteUsersInChannel": [Function], "channelId": "channelId", "currentUserId": "currentUserId", "data": null, "disableDispatches": false, "forceDispatch": false, "getProfilesInChannel": [Function], "lastCompletedWord": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "priorityProfiles": undefined, "requestStarted": false, "searchAssociatedGroupsForReference": [Function], "triggerCharacter": "@", "useChannelMentions": true, }, ChannelMentionProvider { "autocompleteChannels": [MockFunction], "delayChannelAutocomplete": false, "disableDispatches": false, "forceDispatch": false, "lastCompletedWord": "", "lastPrefixTrimmed": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": "~", }, EmoticonProvider { "disableDispatches": false, "forceDispatch": false, "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": ":", }, ] } renderDividers={ Array [ "all", ] } spellCheck="true" style={ Object { "visibility": "hidden", } } value="some test text" /> </div> `; exports[`components/TextBox should match snapshot with required props 1`] = ` <div className="textarea-wrapper" > <div className="form-control custom-textarea textbox-preview-area" onBlur={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} tabIndex={0} > <Connect(PostMarkdown) channelId="channelId" imageProps={ Object { "hideUtilities": true, } } message="some test text" /> </div> <Connect(SuggestionBox) className="form-control custom-textarea textbox-edit-area" contextId="channelId" id="someid" inputComponent={ Object { "$$typeof": Symbol(react.memo), "compare": null, "type": Object { "$$typeof": Symbol(react.forward_ref), "propTypes": Object { "className": [Function], "defaultValue": [Function], "disabled": [Function], "id": [Function], "onChange": [Function], "onHeightChange": [Function], "onInput": [Function], "onWidthChange": [Function], "placeholder": [Function], "value": [Function], }, "render": [Function], }, } } listComponent={[Function]} onBlur={[Function]} onChange={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} onKeyUp={[Function]} onMouseUp={[Function]} placeholder="placeholder text" providers={ Array [ AtMentionProvider { "addLastViewAtToProfiles": [Function], "autocompleteGroups": Array [ Object { "id": "gid1", }, Object { "id": "gid2", }, ], "autocompleteUsersInChannel": [Function], "channelId": "channelId", "currentUserId": "currentUserId", "data": null, "disableDispatches": false, "forceDispatch": false, "getProfilesInChannel": [Function], "lastCompletedWord": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "priorityProfiles": undefined, "requestStarted": false, "searchAssociatedGroupsForReference": [Function], "triggerCharacter": "@", "useChannelMentions": true, }, ChannelMentionProvider { "autocompleteChannels": [MockFunction], "delayChannelAutocomplete": false, "disableDispatches": false, "forceDispatch": false, "lastCompletedWord": "", "lastPrefixTrimmed": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": "~", }, EmoticonProvider { "disableDispatches": false, "forceDispatch": false, "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": ":", }, ] } renderDividers={ Array [ "all", ] } spellCheck="true" style={ Object { "visibility": "visible", } } value="some test text" /> </div> `; exports[`components/TextBox should throw error when new property is too long 1`] = ` <div className="textarea-wrapper" > <div className="form-control custom-textarea textbox-preview-area" onBlur={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} tabIndex={0} > <Connect(PostMarkdown) channelId="channelId" imageProps={ Object { "hideUtilities": true, } } message="some test text that exceeds char limit" /> </div> <Connect(SuggestionBox) className="form-control custom-textarea textbox-edit-area" contextId="channelId" id="someid" inputComponent={ Object { "$$typeof": Symbol(react.memo), "compare": null, "type": Object { "$$typeof": Symbol(react.forward_ref), "propTypes": Object { "className": [Function], "defaultValue": [Function], "disabled": [Function], "id": [Function], "onChange": [Function], "onHeightChange": [Function], "onInput": [Function], "onWidthChange": [Function], "placeholder": [Function], "value": [Function], }, "render": [Function], }, } } listComponent={[Function]} onBlur={[Function]} onChange={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} onKeyUp={[Function]} onMouseUp={[Function]} placeholder="placeholder text" providers={ Array [ AtMentionProvider { "addLastViewAtToProfiles": [Function], "autocompleteGroups": Array [ Object { "id": "gid1", }, Object { "id": "gid2", }, ], "autocompleteUsersInChannel": [Function], "channelId": "channelId", "currentUserId": "currentUserId", "data": null, "disableDispatches": false, "forceDispatch": false, "getProfilesInChannel": [Function], "lastCompletedWord": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "priorityProfiles": undefined, "requestStarted": false, "searchAssociatedGroupsForReference": [Function], "triggerCharacter": "@", "useChannelMentions": true, }, ChannelMentionProvider { "autocompleteChannels": [MockFunction], "delayChannelAutocomplete": false, "disableDispatches": false, "forceDispatch": false, "lastCompletedWord": "", "lastPrefixTrimmed": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": "~", }, EmoticonProvider { "disableDispatches": false, "forceDispatch": false, "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": ":", }, ] } renderDividers={ Array [ "all", ] } spellCheck="true" style={ Object { "visibility": "visible", } } value="some test text that exceeds char limit" /> </div> `; exports[`components/TextBox should throw error when value is too long 1`] = ` <div className="textarea-wrapper" > <div className="form-control custom-textarea textbox-preview-area" onBlur={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} tabIndex={0} > <Connect(PostMarkdown) channelId="channelId" imageProps={ Object { "hideUtilities": true, } } message="some test text that exceeds char limit" /> </div> <Connect(SuggestionBox) className="form-control custom-textarea textbox-edit-area" contextId="channelId" id="someid" inputComponent={ Object { "$$typeof": Symbol(react.memo), "compare": null, "type": Object { "$$typeof": Symbol(react.forward_ref), "propTypes": Object { "className": [Function], "defaultValue": [Function], "disabled": [Function], "id": [Function], "onChange": [Function], "onHeightChange": [Function], "onInput": [Function], "onWidthChange": [Function], "placeholder": [Function], "value": [Function], }, "render": [Function], }, } } listComponent={[Function]} onBlur={[Function]} onChange={[Function]} onKeyDown={[Function]} onKeyPress={[Function]} onKeyUp={[Function]} onMouseUp={[Function]} placeholder="placeholder text" providers={ Array [ AtMentionProvider { "addLastViewAtToProfiles": [Function], "autocompleteGroups": Array [ Object { "id": "gid1", }, Object { "id": "gid2", }, ], "autocompleteUsersInChannel": [Function], "channelId": "channelId", "currentUserId": "currentUserId", "data": null, "disableDispatches": false, "forceDispatch": false, "getProfilesInChannel": [Function], "lastCompletedWord": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "priorityProfiles": undefined, "requestStarted": false, "searchAssociatedGroupsForReference": [Function], "triggerCharacter": "@", "useChannelMentions": true, }, ChannelMentionProvider { "autocompleteChannels": [MockFunction], "delayChannelAutocomplete": false, "disableDispatches": false, "forceDispatch": false, "lastCompletedWord": "", "lastPrefixTrimmed": "", "lastPrefixWithNoResults": "", "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": "~", }, EmoticonProvider { "disableDispatches": false, "forceDispatch": false, "latestComplete": true, "latestPrefix": "", "requestStarted": false, "triggerCharacter": ":", }, ] } renderDividers={ Array [ "all", ] } spellCheck="true" style={ Object { "visibility": "visible", } } value="some test text that exceeds char limit" /> </div> `;
807
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/toggle_modal_button.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ToggleModalButton component should match snapshot 1`] = ` <ToggleModalButton ariaLabel="Delete Channel" dialogType={[Function]} id="channelDelete" modalId="delete_channel" role="menuitem" > <button aria-label="Delete Channel dialog" className="style--none " id="channelDelete" onClick={[Function]} role="menuitem" > <FormattedMessage defaultMessage="Delete Channel" id="channel_header.delete" > <span> Delete Channel </span> </FormattedMessage> </button> </ToggleModalButton> `;
808
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/__snapshots__/user_list.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/UserList should match default snapshot 1`] = ` <div> <div className="more-modal__placeholder-row" data-testid="noUsersFound" key="no-users-found" > <p> <MemoizedFormattedMessage defaultMessage="No users found" id="user_list.notFound" /> </p> </div> </div> `; exports[`components/UserList should match default snapshot when there are users 1`] = ` <div> <Connect(UserListRow) actionProps={ Object { "doEmailReset": [MockFunction], "doManageRoles": [MockFunction], "doManageTeams": [MockFunction], "doManageTokens": [MockFunction], "doPasswordReset": [MockFunction], "enableUserAccessTokens": false, "experimentalEnableAuthenticationTransfer": false, "isDisabled": false, "mfaEnabled": false, } } actions={Array []} index={0} key="id1" totalUsers={2} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "id1", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } userCount={0} /> <Connect(UserListRow) actionProps={ Object { "doEmailReset": [MockFunction], "doManageRoles": [MockFunction], "doManageTeams": [MockFunction], "doManageTokens": [MockFunction], "doPasswordReset": [MockFunction], "enableUserAccessTokens": false, "experimentalEnableAuthenticationTransfer": false, "isDisabled": false, "mfaEnabled": false, } } actions={Array []} index={1} key="id2" totalUsers={2} user={ Object { "auth_service": "", "bot_description": "", "create_at": 0, "delete_at": 0, "email": "", "first_name": "", "id": "id2", "is_bot": false, "last_activity_at": 0, "last_name": "", "last_password_update": 0, "last_picture_update": 0, "locale": "", "mfa_active": false, "nickname": "", "notify_props": Object { "calls_desktop_sound": "true", "channel": "false", "comments": "never", "desktop": "default", "desktop_sound": "false", "email": "false", "first_name": "false", "highlight_keys": "", "mark_unread": "mention", "mention_keys": "", "push": "none", "push_status": "offline", }, "password": "", "position": "", "props": Object {}, "roles": "", "terms_of_service_create_at": 0, "terms_of_service_id": "", "update_at": 0, "username": "some-user", } } userCount={1} /> </div> `;
809
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/about_build_modal/about_build_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {ClientConfig, ClientLicense} from '@mattermost/types/config'; import AboutBuildModal from 'components/about_build_modal/about_build_modal'; import {renderWithContext, screen, userEvent} from 'tests/react_testing_utils'; import {AboutLinks} from 'utils/constants'; import AboutBuildModalCloud from './about_build_modal_cloud/about_build_modal_cloud'; describe('components/AboutBuildModal', () => { const RealDate: DateConstructor = Date; function mockDate(date: Date) { function mock() { return new RealDate(date); } mock.now = () => date.getTime(); global.Date = mock as any; } let config: Partial<ClientConfig> = {}; let license: ClientLicense = {}; afterEach(() => { global.Date = RealDate; config = {}; license = {}; }); beforeEach(() => { mockDate(new Date(2017, 6, 1)); config = { BuildEnterpriseReady: 'true', Version: '3.6.0', SchemaVersion: '77', BuildNumber: '123456', SQLDriverName: 'Postgres', BuildHash: 'abcdef1234567890', BuildHashEnterprise: '0123456789abcdef', BuildDate: '21 January 2017', TermsOfServiceLink: AboutLinks.TERMS_OF_SERVICE, PrivacyPolicyLink: AboutLinks.PRIVACY_POLICY, }; license = { IsLicensed: 'true', Company: 'Mattermost Inc', }; }); test('should match snapshot for enterprise edition', () => { renderAboutBuildModal({config, license}); expect(screen.getByTestId('aboutModalVersion')).toHaveTextContent('Mattermost Version: 3.6.0'); expect(screen.getByTestId('aboutModalDBVersionString')).toHaveTextContent('Database Schema Version: 77'); expect(screen.getByTestId('aboutModalBuildNumber')).toHaveTextContent('Build Number: 123456'); expect(screen.getByText('Mattermost Enterprise Edition')).toBeInTheDocument(); expect(screen.getByText('Modern communication from behind your firewall.')).toBeInTheDocument(); expect(screen.getByRole('link', {name: 'mattermost.com'})).toHaveAttribute('href', 'https://mattermost.com/?utm_source=mattermost&utm_medium=in-product&utm_content=about_build_modal&uid=&sid='); expect(screen.getByText('EE Build Hash: 0123456789abcdef', {exact: false})).toBeInTheDocument(); expect(screen.getByRole('link', {name: 'server'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-server/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'desktop'})).toHaveAttribute('href', 'https://github.com/mattermost/desktop/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'mobile'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-mobile/blob/master/NOTICE.txt'); }); test('should match snapshot for team edition', () => { const teamConfig = { ...config, BuildEnterpriseReady: 'false', BuildHashEnterprise: '', }; renderAboutBuildModal({config: teamConfig, license: {}}); expect(screen.getByTestId('aboutModalVersion')).toHaveTextContent('Mattermost Version: 3.6.0'); expect(screen.getByTestId('aboutModalDBVersionString')).toHaveTextContent('Database Schema Version: 77'); expect(screen.getByTestId('aboutModalBuildNumber')).toHaveTextContent('Build Number: 123456'); expect(screen.getByText('Mattermost Team Edition')).toBeInTheDocument(); expect(screen.getByText('All your team communication in one place, instantly searchable and accessible anywhere.')).toBeInTheDocument(); expect(screen.getByRole('link', {name: 'mattermost.com/community/'})).toHaveAttribute('href', 'https://mattermost.com/community/?utm_source=mattermost&utm_medium=in-product&utm_content=about_build_modal&uid=&sid='); expect(screen.queryByText('EE Build Hash: 0123456789abcdef')).not.toBeInTheDocument(); expect(screen.getByRole('link', {name: 'server'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-server/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'desktop'})).toHaveAttribute('href', 'https://github.com/mattermost/desktop/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'mobile'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-mobile/blob/master/NOTICE.txt'); }); test('should match snapshot for cloud edition', () => { if (license !== null) { license.Cloud = 'true'; } renderWithContext( <AboutBuildModalCloud config={config} license={license} show={true} onExited={jest.fn()} doHide={jest.fn()} />, ); expect(screen.getByText('Mattermost Cloud')).toBeInTheDocument(); expect(screen.getByText('High trust messaging for the enterprise')).toBeInTheDocument(); expect(screen.getByTestId('aboutModalVersion')).toHaveTextContent('Mattermost Version: 3.6.0'); expect(screen.getByText('0123456789abcdef', {exact: false})).toBeInTheDocument(); expect(screen.getByRole('link', {name: 'server'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-server/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'desktop'})).toHaveAttribute('href', 'https://github.com/mattermost/desktop/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'mobile'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-mobile/blob/master/NOTICE.txt'); }); test('should show n/a if this is a dev build', () => { const sameBuildConfig = { ...config, BuildEnterpriseReady: 'false', BuildHashEnterprise: '', Version: '3.6.0', SchemaVersion: '77', BuildNumber: 'dev', }; renderAboutBuildModal({config: sameBuildConfig, license: {}}); expect(screen.getByTestId('aboutModalVersion')).toHaveTextContent('Mattermost Version: dev'); expect(screen.getByTestId('aboutModalDBVersionString')).toHaveTextContent('Database Schema Version: 77'); expect(screen.getByTestId('aboutModalBuildNumber')).toHaveTextContent('Build Number: n/a'); expect(screen.getByText('Mattermost Team Edition')).toBeInTheDocument(); expect(screen.getByText('All your team communication in one place, instantly searchable and accessible anywhere.')).toBeInTheDocument(); expect(screen.getByRole('link', {name: 'mattermost.com/community/'})).toHaveAttribute('href', 'https://mattermost.com/community/?utm_source=mattermost&utm_medium=in-product&utm_content=about_build_modal&uid=&sid='); expect(screen.queryByText('EE Build Hash: 0123456789abcdef')).not.toBeInTheDocument(); expect(screen.getByRole('link', {name: 'server'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-server/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'desktop'})).toHaveAttribute('href', 'https://github.com/mattermost/desktop/blob/master/NOTICE.txt'); expect(screen.getByRole('link', {name: 'mobile'})).toHaveAttribute('href', 'https://github.com/mattermost/mattermost-mobile/blob/master/NOTICE.txt'); }); test('should call onExited callback when the modal is hidden', () => { const onExited = jest.fn(); const state = { entities: { general: { config: {}, license: { Cloud: 'false', }, }, users: { currentUserId: 'currentUserId', }, }, }; renderWithContext( <AboutBuildModal config={config} license={license} onExited={onExited} />, state, ); userEvent.click(screen.getByText('Close')); expect(onExited).toHaveBeenCalledTimes(1); }); test('should show default tos and privacy policy links and not the config links', () => { const state = { entities: { general: { config: {}, license: { Cloud: 'false', }, }, users: { currentUserId: 'currentUserId', }, }, }; renderWithContext( <AboutBuildModal config={config} license={license} onExited={jest.fn()} />, state, ); expect(screen.getByRole('link', {name: 'Terms of Use'})).toHaveAttribute('href', `${AboutLinks.TERMS_OF_SERVICE}?utm_source=mattermost&utm_medium=in-product&utm_content=about_build_modal&uid=currentUserId&sid=`); expect(screen.getByRole('link', {name: 'Privacy Policy'})).toHaveAttribute('href', `${AboutLinks.PRIVACY_POLICY}?utm_source=mattermost&utm_medium=in-product&utm_content=about_build_modal&uid=currentUserId&sid=`); expect(screen.getByRole('link', {name: 'Terms of Use'})).not.toHaveAttribute('href', config?.TermsOfServiceLink); expect(screen.getByRole('link', {name: 'Privacy Policy'})).not.toHaveAttribute('href', config?.PrivacyPolicyLink); }); function renderAboutBuildModal(props = {}) { const onExited = jest.fn(); const show = true; const allProps = { show, onExited, config, license, ...props, }; return renderWithContext(<AboutBuildModal {...allProps}/>); } });
815
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/access_history_modal/access_history_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {fireEvent, screen, render, waitForElementToBeRemoved, waitFor} from '@testing-library/react'; import {shallow} from 'enzyme'; import React from 'react'; import AccessHistoryModal from 'components/access_history_modal/access_history_modal'; import AuditTable from 'components/audit_table'; import LoadingScreen from 'components/loading_screen'; import {withIntl} from 'tests/helpers/intl-test-helper'; describe('components/AccessHistoryModal', () => { const baseProps = { onHide: jest.fn(), actions: { getUserAudits: jest.fn(), }, userAudits: [], currentUserId: '', }; test('should match snapshot when no audits exist', () => { const wrapper = shallow( <AccessHistoryModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(LoadingScreen).exists()).toBe(true); expect(wrapper.find(AuditTable).exists()).toBe(false); }); test('should match snapshot when audits exist', () => { const wrapper = shallow( <AccessHistoryModal {...baseProps}/>, ); wrapper.setProps({userAudits: ['audit1', 'audit2']}); expect(wrapper).toMatchSnapshot(); expect(wrapper.find(LoadingScreen).exists()).toBe(false); expect(wrapper.find(AuditTable).exists()).toBe(true); }); test('should have called actions.getUserAudits only when first rendered', () => { const actions = { getUserAudits: jest.fn(), }; const props = {...baseProps, actions}; const view = render(withIntl(<AccessHistoryModal {...props}/>)); expect(actions.getUserAudits).toHaveBeenCalledTimes(1); const newProps = {...props, currentUserId: 'foo'}; view.rerender(withIntl(<AccessHistoryModal {...newProps}/>)); expect(actions.getUserAudits).toHaveBeenCalledTimes(1); }); test('should hide', async () => { render(withIntl(<AccessHistoryModal {...baseProps}/>)); await waitFor(() => screen.getByText('Access History')); fireEvent.click(screen.getByLabelText('Close')); await waitForElementToBeRemoved(() => screen.getByText('Access History')); }); });
818
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/access_history_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/access_history_modal/__snapshots__/access_history_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/AccessHistoryModal should match snapshot when audits exist 1`] = ` <Modal animation={true} aria-labelledby="accessHistoryModalLabel" autoFocus={true} backdrop={true} bsClass="modal" bsSize="large" dialogClassName="a11y__modal modal--scroll access-history-modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="accessHistoryModalLabel" > <MemoizedFormattedMessage defaultMessage="Access History" id="access_history.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <Connect(injectIntl(AuditTable)) audits={ Array [ "audit1", "audit2", ] } showIp={true} showSession={true} /> </ModalBody> <ModalFooter bsClass="modal-footer" className="modal-footer--invisible" componentClass="div" > <button className="btn btn-tertiary" id="closeModalButton" type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="general_button.close" /> </button> </ModalFooter> </Modal> `; exports[`components/AccessHistoryModal should match snapshot when no audits exist 1`] = ` <Modal animation={true} aria-labelledby="accessHistoryModalLabel" autoFocus={true} backdrop={true} bsClass="modal" bsSize="large" dialogClassName="a11y__modal modal--scroll access-history-modal" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="accessHistoryModalLabel" > <MemoizedFormattedMessage defaultMessage="Access History" id="access_history.title" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <LoadingScreen /> </ModalBody> <ModalFooter bsClass="modal-footer" className="modal-footer--invisible" componentClass="div" > <button className="btn btn-tertiary" id="closeModalButton" type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="general_button.close" /> </button> </ModalFooter> </Modal> `;
822
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu/actions_menu.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import type {PostType} from '@mattermost/types/posts'; import {shallowWithIntl} from 'tests/helpers/intl-test-helper'; import {TestHelper} from 'utils/test_helper'; import type {PluginComponent} from 'types/store/plugins'; import ActionsMenu, {PLUGGABLE_COMPONENT} from './actions_menu'; import type {Props} from './actions_menu'; jest.mock('utils/utils', () => { const original = jest.requireActual('utils/utils'); return { ...original, isMobile: jest.fn(() => false), }; }); const dropdownComponents: PluginComponent[] = [ { id: 'the_component_id', pluginId: 'playbooks', action: jest.fn(), }, ]; describe('components/actions_menu/ActionsMenu', () => { const baseProps: Omit<Props, 'intl'> = { appBindings: [], appsEnabled: false, teamId: 'team_id_1', handleDropdownOpened: jest.fn(), isMenuOpen: true, isSysAdmin: true, pluginMenuItems: [], post: TestHelper.getPostMock({id: 'post_id_1', is_pinned: false, type: '' as PostType}), components: {}, location: 'center', canOpenMarketplace: false, actions: { openModal: jest.fn(), openAppsModal: jest.fn(), handleBindingClick: jest.fn(), postEphemeralCallResponseForPost: jest.fn(), fetchBindings: jest.fn(), }, }; test('sysadmin - should have divider when plugin menu item exists', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); expect(wrapper.find('#divider_post_post_id_1_marketplace').exists()).toBe(false); wrapper.setProps({ pluginMenuItems: dropdownComponents, canOpenMarketplace: true, }); expect(wrapper.find('#divider_post_post_id_1_marketplace').exists()).toBe(true); }); test('has actions - marketplace enabled and user has SYSCONSOLE_WRITE_PLUGINS - should show actions and app marketplace', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); wrapper.setProps({ pluginMenuItems: dropdownComponents, canOpenMarketplace: true, }); expect(wrapper).toMatchSnapshot(); }); test('has actions - marketplace disabled or user not having SYSCONSOLE_WRITE_PLUGINS - should not show actions and app marketplace', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); wrapper.setProps({ pluginMenuItems: dropdownComponents, canOpenMarketplace: false, }); expect(wrapper).toMatchSnapshot(); }); test('no actions - sysadmin - menu should show visit marketplace', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); wrapper.setProps({ canOpenMarketplace: true, }); expect(wrapper).toMatchSnapshot(); }); test('no actions - end user - menu should not be visible to end user', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); wrapper.setProps({ isSysAdmin: false, }); // menu should be empty expect(wrapper.debug()).toMatchSnapshot(); }); test('sysadmin - should have divider when pluggable menu item exists', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); expect(wrapper.find('#divider_post_post_id_1_marketplace').exists()).toBe(false); wrapper.setProps({ components: { [PLUGGABLE_COMPONENT]: dropdownComponents, }, canOpenMarketplace: true, }); expect(wrapper.find('#divider_post_post_id_1_marketplace').exists()).toBe(true); }); test('end user - should not have divider when pluggable menu item exists', () => { const wrapper = shallowWithIntl( <ActionsMenu {...baseProps}/>, ); wrapper.setProps({ isSysAdmin: false, }); expect(wrapper.find('#divider_post_post_id_1_marketplace').exists()).toBe(false); wrapper.setProps({ components: { [PLUGGABLE_COMPONENT]: dropdownComponents, }, }); expect(wrapper.find('#divider_post_post_id_1_marketplace').exists()).toBe(false); }); });
824
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu/actions_menu_empty.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 ActionsMenu from 'components/actions_menu/actions_menu'; import type {Props} from 'components/actions_menu/actions_menu'; import {TestHelper} from 'utils/test_helper'; jest.mock('utils/utils', () => { return { isMobile: jest.fn(() => false), localizeMessage: jest.fn().mockReturnValue(''), }; }); jest.mock('utils/post_utils', () => { const original = jest.requireActual('utils/post_utils'); return { ...original, isSystemMessage: jest.fn(() => true), }; }); describe('components/actions_menu/ActionsMenu returning empty ("")', () => { test('should match snapshot, return empty ("") on Center', () => { const baseProps: Omit<Props, 'intl'> = { post: TestHelper.getPostMock({id: 'post_id_1'}), components: {}, teamId: 'team_id_1', actions: { openModal: jest.fn(), openAppsModal: jest.fn(), handleBindingClick: jest.fn(), postEphemeralCallResponseForPost: jest.fn(), fetchBindings: jest.fn(), }, appBindings: [], pluginMenuItems: [], appsEnabled: false, isSysAdmin: true, canOpenMarketplace: false, }; const wrapper = shallow( <ActionsMenu {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
826
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu/actions_menu_mobile.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import ActionsMenu from 'components/actions_menu/actions_menu'; import type {Props} from 'components/actions_menu/actions_menu'; import {TestHelper} from 'utils/test_helper'; jest.mock('utils/utils', () => { return { isMobile: jest.fn(() => true), localizeMessage: jest.fn(), }; }); jest.mock('utils/post_utils', () => { const original = jest.requireActual('utils/post_utils'); return { ...original, isSystemMessage: jest.fn(() => true), }; }); describe('components/actions_menu/ActionsMenu on mobile view', () => { test('should match snapshot', () => { const baseProps: Omit<Props, 'intl'> = { post: TestHelper.getPostMock({id: 'post_id_1'}), components: {}, teamId: 'team_id_1', actions: { openModal: jest.fn(), openAppsModal: jest.fn(), handleBindingClick: jest.fn(), postEphemeralCallResponseForPost: jest.fn(), fetchBindings: jest.fn(), }, appBindings: [], pluginMenuItems: [], appsEnabled: false, isSysAdmin: true, canOpenMarketplace: false, }; const wrapper = shallow( <ActionsMenu {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); });
830
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu/__snapshots__/actions_menu.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/actions_menu/ActionsMenu has actions - marketplace disabled or user not having SYSCONSOLE_WRITE_PLUGINS - should not show actions and app marketplace 1`] = ` <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} open={true} > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip bsClass="tooltip" className="hidden-xs" id="actions-menu-icon-tooltip" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Message actions" id="post_info.tooltip.actions" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <button aria-expanded="false" aria-label="actions" className="post-menu__item post-menu__item--active" id="center_actions_button_post_id_1" key="more-actions-button" type="button" > <i className="icon icon-apps" /> </button> </OverlayTrigger> <Menu ariaLabel="Post extra options" id="center_actions_dropdown_post_id_1" key="center_actions_dropdown_post_id_1" openLeft={true} openUp={false} > <MenuItemAction key="the_component_id_pluginmenuitem" onClick={[Function]} show={true} /> <Connect(Pluggable) key="post_id_1pluggable" pluggableName="PostDropdownMenuItem" postId="post_id_1" /> </Menu> </MenuWrapper> `; exports[`components/actions_menu/ActionsMenu has actions - marketplace enabled and user has SYSCONSOLE_WRITE_PLUGINS - should show actions and app marketplace 1`] = ` <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} open={true} > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip bsClass="tooltip" className="hidden-xs" id="actions-menu-icon-tooltip" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Message actions" id="post_info.tooltip.actions" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <button aria-expanded="false" aria-label="actions" className="post-menu__item post-menu__item--active" id="center_actions_button_post_id_1" key="more-actions-button" type="button" > <i className="icon icon-apps" /> </button> </OverlayTrigger> <Menu ariaLabel="Post extra options" id="center_actions_dropdown_post_id_1" key="center_actions_dropdown_post_id_1" openLeft={true} openUp={false} > <MenuItemAction key="the_component_id_pluginmenuitem" onClick={[Function]} show={true} /> <Connect(Pluggable) key="post_id_1pluggable" pluggableName="PostDropdownMenuItem" postId="post_id_1" /> <li className="MenuItem__divider" id="divider_post_post_id_1_marketplace" role="menuitem" /> <MenuItemAction icon={ <ActionsMenuIcon name="icon-view-grid-plus-outline" /> } id="marketplace_icon_post_id_1" key="marketplace_post_id_1" onClick={[Function]} show={true} text="App Marketplace" /> </Menu> </MenuWrapper> `; exports[`components/actions_menu/ActionsMenu no actions - end user - menu should not be visible to end user 1`] = `""`; exports[`components/actions_menu/ActionsMenu no actions - sysadmin - menu should show visit marketplace 1`] = ` <MenuWrapper animationComponent={[Function]} className="" onToggle={[Function]} open={true} > <OverlayTrigger className="hidden-xs" defaultOverlayShown={false} delayShow={500} overlay={ <Tooltip bsClass="tooltip" className="hidden-xs" id="actions-menu-icon-tooltip" placement="right" > <Memo(MemoizedFormattedMessage) defaultMessage="Message actions" id="post_info.tooltip.actions" /> </Tooltip> } placement="top" rootClose={true} trigger={ Array [ "hover", "focus", ] } > <button aria-expanded="false" aria-label="actions" className="post-menu__item post-menu__item--active" id="center_actions_button_post_id_1" key="more-actions-button" type="button" > <i className="icon icon-apps" /> </button> </OverlayTrigger> <Menu ariaLabel="Post extra options" id="center_actions_dropdown_post_id_1" key="center_actions_dropdown_post_id_1" openLeft={true} openUp={false} > <Connect(SystemPermissionGate) key="visit-marketplace-permissions" permissions={ Array [ "manage_system", ] } > <div className="visit-marketplace-text" > <FormattedMarkdownMessage defaultMessage="No Actions currently\\\\nconfigured for this server" id="post_info.actions.noActions" /> </div> <div className="visit-marketplace" > <button className="btn btn-primary visit-marketplace-button" id="marketPlaceButton" onClick={[Function]} > <ActionsMenuIcon name="icon-view-grid-plus-outline visit-marketplace-button-icon" /> <span className="visit-marketplace-button-text" > <FormattedMarkdownMessage defaultMessage="Visit the Marketplace" id="post_info.actions.visitMarketplace" /> </span> </button> </div> </Connect(SystemPermissionGate)> </Menu> </MenuWrapper> `;
831
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu/__snapshots__/actions_menu_empty.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/actions_menu/ActionsMenu returning empty ("") should match snapshot, return empty ("") on Center 1`] = ` <ContextConsumer> <Component /> </ContextConsumer> `;
832
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu
petrpan-code/mattermost/mattermost/webapp/channels/src/components/actions_menu/__snapshots__/actions_menu_mobile.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/actions_menu/ActionsMenu on mobile view should match snapshot 1`] = ` <ContextConsumer> <Component /> </ContextConsumer> `;
833
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components
petrpan-code/mattermost/mattermost/webapp/channels/src/components/activity_log_modal/activity_log_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import type {MouseEvent} from 'react'; import {General} from 'mattermost-redux/constants'; import ActivityLogModal from 'components/activity_log_modal/activity_log_modal'; describe('components/ActivityLogModal', () => { const baseProps = { sessions: [], currentUserId: '', onHide: jest.fn(), actions: { getSessions: jest.fn(), revokeSession: jest.fn(), }, locale: General.DEFAULT_LOCALE, }; test('should match snapshot', () => { const wrapper = shallow<ActivityLogModal>( <ActivityLogModal {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot when submitRevoke is called', () => { const revokeSession = jest.fn().mockImplementation( () => { return new Promise<void>((resolve) => { process.nextTick(() => resolve()); }); }, ); const actions = { getSessions: jest.fn(), revokeSession, }; const props = {...baseProps, actions}; const wrapper = shallow<ActivityLogModal>( <ActivityLogModal {...props}/>, ); wrapper.instance().submitRevoke('altId', {preventDefault: jest.fn()} as unknown as MouseEvent); expect(wrapper).toMatchSnapshot(); expect(revokeSession).toHaveBeenCalledTimes(1); expect(revokeSession).toHaveBeenCalledWith('', 'altId'); }); test('should have called actions.getUserAudits when onShow is called', () => { const actions = { getSessions: jest.fn(), revokeSession: jest.fn(), }; const props = {...baseProps, actions}; const wrapper = shallow<ActivityLogModal>( <ActivityLogModal {...props}/>, ); wrapper.instance().onShow(); expect(actions.getSessions).toHaveBeenCalledTimes(2); }); test('should match state when onHide is called', () => { const wrapper = shallow<ActivityLogModal>( <ActivityLogModal {...baseProps}/>, ); wrapper.setState({show: true}); wrapper.instance().onHide(); expect(wrapper.state('show')).toEqual(false); }); });
836
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/activity_log_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/activity_log_modal/__snapshots__/activity_log_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`components/ActivityLogModal should match snapshot 1`] = ` <Modal animation={true} aria-labelledby="activityLogModalLabel" autoFocus={true} backdrop={true} bsClass="modal" bsSize="large" dialogClassName="a11y__modal modal--scroll" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="activityLogModalLabel" > <MemoizedFormattedMessage defaultMessage="Active Sessions" id="activity_log.activeSessions" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <p className="session-help-text" > <MemoizedFormattedMessage defaultMessage="Sessions are created when you log in through a new browser on a device. Sessions let you use Mattermost without having to log in again for a time period specified by the system administrator. To end the session sooner, use the 'Log Out' button." id="activity_log.sessionsDescription" /> </p> <form role="form" /> </ModalBody> <ModalFooter bsClass="modal-footer" className="modal-footer--invisible" componentClass="div" > <button className="btn btn-tertiary" id="closeModalButton" type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="general_button.close" /> </button> </ModalFooter> </Modal> `; exports[`components/ActivityLogModal should match snapshot when submitRevoke is called 1`] = ` <Modal animation={true} aria-labelledby="activityLogModalLabel" autoFocus={true} backdrop={true} bsClass="modal" bsSize="large" dialogClassName="a11y__modal modal--scroll" dialogComponentClass={[Function]} enforceFocus={true} keyboard={true} manager={ ModalManager { "add": [Function], "containers": Array [], "data": Array [], "handleContainerOverflow": true, "hideSiblingNodes": true, "isTopModal": [Function], "modals": Array [], "remove": [Function], } } onExited={[MockFunction]} onHide={[Function]} renderBackdrop={[Function]} restoreFocus={true} role="dialog" show={true} > <ModalHeader bsClass="modal-header" closeButton={true} closeLabel="Close" > <ModalTitle bsClass="modal-title" componentClass="h1" id="activityLogModalLabel" > <MemoizedFormattedMessage defaultMessage="Active Sessions" id="activity_log.activeSessions" /> </ModalTitle> </ModalHeader> <ModalBody bsClass="modal-body" componentClass="div" > <p className="session-help-text" > <MemoizedFormattedMessage defaultMessage="Sessions are created when you log in through a new browser on a device. Sessions let you use Mattermost without having to log in again for a time period specified by the system administrator. To end the session sooner, use the 'Log Out' button." id="activity_log.sessionsDescription" /> </p> <form role="form" /> </ModalBody> <ModalFooter bsClass="modal-footer" className="modal-footer--invisible" componentClass="div" > <button className="btn btn-tertiary" id="closeModalButton" type="button" > <MemoizedFormattedMessage defaultMessage="Close" id="general_button.close" /> </button> </ModalFooter> </Modal> `;
837
0
petrpan-code/mattermost/mattermost/webapp/channels/src/components/activity_log_modal
petrpan-code/mattermost/mattermost/webapp/channels/src/components/activity_log_modal/components/activity_log.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import React from 'react'; import {FormattedMessage} from 'react-intl'; import {General} from 'mattermost-redux/constants'; import ActivityLog from 'components/activity_log_modal/components/activity_log'; import {TestHelper} from 'utils/test_helper'; import {localizeMessage} from 'utils/utils'; describe('components/activity_log_modal/ActivityLog', () => { const baseProps = { index: 0, locale: General.DEFAULT_LOCALE, currentSession: TestHelper.getSessionMock({ props: {os: 'Linux', platform: 'Linux', browser: 'Desktop App'}, id: 'sessionId', create_at: 1534917291042, last_activity_at: 1534917643890, }), submitRevoke: jest.fn(), }; test('should match snapshot', () => { const wrapper = shallow( <ActivityLog {...baseProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('should match snapshot with mobile props', () => { const mobileDeviceIdProps = Object.assign({}, baseProps, {currentSession: {...baseProps.currentSession, device_id: 'apple'}}); const wrapper = shallow( <ActivityLog {...mobileDeviceIdProps}/>, ); expect(wrapper).toMatchSnapshot(); }); test('submitRevoke is called correctly', () => { const wrapper = shallow<ActivityLog>( <ActivityLog {...baseProps}/>, ); const event = {preventDefault: jest.fn()}; wrapper.instance().submitRevoke(event as unknown as React.MouseEvent); expect(baseProps.submitRevoke).toBeCalled(); expect(baseProps.submitRevoke).toHaveBeenCalledTimes(1); expect(baseProps.submitRevoke).toBeCalledWith('sessionId', event); }); test('handleMoreInfo updates state correctly', () => { const wrapper = shallow<ActivityLog>( <ActivityLog {...baseProps}/>, ); wrapper.instance().handleMoreInfo(); expect(wrapper.state()).toEqual({moreInfo: true}); }); test('should match when isMobileSession is called', () => { const wrapper = shallow<ActivityLog>( <ActivityLog {...baseProps}/>, ); const isMobileSession = wrapper.instance().isMobileSession; expect(isMobileSession(TestHelper.getSessionMock({device_id: 'apple'}))).toEqual(true); expect(isMobileSession(TestHelper.getSessionMock({device_id: 'android'}))).toEqual(true); expect(isMobileSession(TestHelper.getSessionMock({device_id: 'none'}))).toEqual(false); }); test('should match when mobileSessionInfo is called', () => { const wrapper = shallow<ActivityLog>( <ActivityLog {...baseProps}/>, ); const mobileSessionInfo = wrapper.instance().mobileSessionInfo; const appleText = ( <FormattedMessage defaultMessage='iPhone Native Classic App' id='activity_log_modal.iphoneNativeClassicApp' /> ); const apple = {devicePicture: 'fa fa-apple', deviceTitle: localizeMessage('device_icons.apple', 'Apple Icon'), devicePlatform: appleText}; expect(mobileSessionInfo(TestHelper.getSessionMock({device_id: 'apple'}))).toEqual(apple); const androidText = ( <FormattedMessage defaultMessage='Android Native Classic App' id='activity_log_modal.androidNativeClassicApp' /> ); const android = {devicePicture: 'fa fa-android', deviceTitle: localizeMessage('device_icons.android', 'Android Icon'), devicePlatform: androidText}; expect(mobileSessionInfo(TestHelper.getSessionMock({device_id: 'android'}))).toEqual(android); const appleRNText = ( <FormattedMessage defaultMessage='iPhone Native App' id='activity_log_modal.iphoneNativeApp' /> ); const appleRN = {devicePicture: 'fa fa-apple', deviceTitle: localizeMessage('device_icons.apple', 'Apple Icon'), devicePlatform: appleRNText}; expect(mobileSessionInfo(TestHelper.getSessionMock({device_id: 'apple_rn'}))).toEqual(appleRN); const androidRNText = ( <FormattedMessage defaultMessage='Android Native App' id='activity_log_modal.androidNativeApp' /> ); const androidRN = {devicePicture: 'fa fa-android', deviceTitle: localizeMessage('device_icons.android', 'Android Icon'), devicePlatform: androidRNText}; expect(mobileSessionInfo(TestHelper.getSessionMock({device_id: 'android_rn'}))).toEqual(androidRN); }); });