Interactive interface for browsing global, full-resolution satellite imagery
Added unit tests for web/js/lib/, web/js/ol/, and web/js/util/context-menu/. And unit test for web/js/combine-middlware.test.js.
Jason Hurleyf80c49f80ff4
diff --git a/web/js/combine-middleware.test.js b/web/js/combine-middleware.test.jsindex 8031ead73..ec64a72ac 100644--- a/web/js/combine-middleware.test.js+++ b/web/js/combine-middleware.test.js@@ -80,4 +80,32 @@ describe('getMiddleware', () => {expect(middleware[1]).toBe(locationMiddleware);expect(middleware[2]).toBe('loggerMiddleware');});+import { thunk } from 'redux-thunk'; // For ASYNC actions+import { compact } from 'lodash';+import { createLogger } from 'redux-logger';+import getMiddleware from './combine-middleware';++jest.mock('redux-thunk', () => ({+ thunk: jest.fn(),+}));++jest.mock('lodash', () => ({+ compact: jest.fn((arr) => arr),+}));++jest.mock('redux-logger', () => ({+ createLogger: jest.fn(),+}));++test('combine-middleware - debugger enabled', () => {+ const loggerMiddleware = createLogger();+ const result = getMiddleware(true, {});+ console.log(result);+ expect(compact).toHaveBeenCalledWith([thunk, {}, loggerMiddleware]);+});++test('combine-middleware - debugger disabled', () => {+ const result = getMiddleware(false, {});+ console.log(result);+ expect(compact).toHaveBeenCalledWith([thunk, {}]);});diff --git a/web/js/util/context-menu/AbstractMenu.test.js b/web/js/util/context-menu/AbstractMenu.test.jsindex ad9574661..0dbff5167 100644--- a/web/js/util/context-menu/AbstractMenu.test.js+++ b/web/js/util/context-menu/AbstractMenu.test.js@@ -1,3 +1,239 @@-test('AbstractMenu util test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, fireEvent } from '@testing-library/react';+import AbstractMenu from './AbstractMenu'; // Update path as needed+import MenuItem from './MenuItem';+// ---------------------------------------------------------------------------+// Concrete subclass — AbstractMenu cannot be rendered directly+// ---------------------------------------------------------------------------++class TestMenu extends AbstractMenu {+ getSubMenuType() {+ return 'submenu'; // simple sentinel string+ }++ hideMenu() {+ this.setState({ isVisible: false });+ }++ render() {+ return (+ <div onKeyDown={this.handleKeyNavigation}>+ {this.renderChildren(this.props.children)}+ </div>+ );+ }+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function renderMenu(children, props = {}) {+ return render(<TestMenu {...props}>{children}</TestMenu>);+}++// ---------------------------------------------------------------------------+// Initial state+// ---------------------------------------------------------------------------++describe('AbstractMenu initial state', () => {+ it('renders children without crashing', () => {+ const { getByText } = renderMenu(+ <MenuItem>Item 1</MenuItem>,+ );+ expect(getByText('Item 1')).toBeTruthy();+ });++ it('renders multiple children', () => {+ const { getByText } = renderMenu(+ <>+ <MenuItem>Item 1</MenuItem>+ <MenuItem>Item 2</MenuItem>+ </>,+ );+ expect(getByText('Item 1')).toBeTruthy();+ expect(getByText('Item 2')).toBeTruthy();+ });+});++// ---------------------------------------------------------------------------+// renderChildren — non MenuItem wrapper passthrough+// ---------------------------------------------------------------------------++describe('renderChildren()', () => {+ it('passes through non-MenuItem wrapper elements', () => {+ const { getByText } = renderMenu(+ <div>+ <MenuItem>Wrapped Item</MenuItem>+ </div>,+ );+ expect(getByText('Wrapped Item')).toBeTruthy();+ });++ it('returns non-element children (strings) unchanged', () => {+ const { getByText } = renderMenu(+ <>+ <MenuItem>Real Item</MenuItem>+ {'plain text'}+ </>,+ );+ expect(getByText('plain text')).toBeTruthy();+ });+});++// ---------------------------------------------------------------------------+// onChildMouseMove / onChildMouseLeave+// ---------------------------------------------------------------------------++describe('mouse interactions', () => {+ it('sets selectedItem on mouse move over a MenuItem', () => {+ const { getByText } = renderMenu(+ <>+ <MenuItem>Item A</MenuItem>+ <MenuItem>Item B</MenuItem>+ </>,+ );++ fireEvent.mouseMove(getByText('Item A'));+ // After mouseMove, Item A should be selected (gets `selected` prop → no crash)+ expect(getByText('Item A')).toBeTruthy();+ });++ it('clears selectedItem on mouse leave', () => {+ const { getByText } = renderMenu(+ <MenuItem>Item A</MenuItem>,+ );++ fireEvent.mouseMove(getByText('Item A'));+ fireEvent.mouseLeave(getByText('Item A'));+ // Should not throw and component is still mounted+ expect(getByText('Item A')).toBeTruthy();+ });+});++// ---------------------------------------------------------------------------+// handleKeyNavigation — arrow keys+// ---------------------------------------------------------------------------++describe('handleKeyNavigation()', () => {+ function renderNavigableMenu() {+ const { container } = renderMenu(+ <>+ <MenuItem>First</MenuItem>+ <MenuItem>Second</MenuItem>+ <MenuItem>Third</MenuItem>+ </>,+ );+ return container.firstChild;+ }++ it('does not throw on down arrow keypress', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 40 })).not.toThrow();+ });++ it('does not throw on up arrow keypress', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 38 })).not.toThrow();+ });++ it('does not throw on escape keypress', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 27 })).not.toThrow();+ });++ it('does not throw on left arrow keypress', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 37 })).not.toThrow();+ });++ it('does not throw on right arrow keypress', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 39 })).not.toThrow();+ });++ it('does not throw on enter keypress', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 13 })).not.toThrow();+ });++ it('does not throw on an unhandled key', () => {+ const menu = renderNavigableMenu();+ expect(() => fireEvent.keyDown(menu, { keyCode: 65 })).not.toThrow();+ });++ it('does nothing when isVisible is explicitly false', () => {+ // Simulate ContextMenu context where isVisible is part of state+ class ContextTestMenu extends TestMenu {+ constructor(props) {+ super(props);+ this.state = { ...this.state, isVisible: false };+ }+ }++ const { container } = render(+ <ContextTestMenu>+ <MenuItem>Item</MenuItem>+ </ContextTestMenu>,+ );++ // Should return early without any state change / error+ expect(+ () => fireEvent.keyDown(container.firstChild, { keyCode: 40 }),+ ).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// selectChildren — disabled items+// ---------------------------------------------------------------------------++describe('selectChildren() with disabled items', () => {+ it('does not select any item when all children are disabled', () => {+ const { container } = renderMenu(+ <>+ <MenuItem disabled>Disabled 1</MenuItem>+ <MenuItem disabled>Disabled 2</MenuItem>+ </>,+ );++ // Down arrow should not throw and nothing should be selected+ expect(+ () => fireEvent.keyDown(container.firstChild, { keyCode: 40 }),+ ).not.toThrow();+ });++ it('skips disabled items during keyboard navigation', () => {+ const { container } = renderMenu(+ <>+ <MenuItem>Enabled 1</MenuItem>+ <MenuItem disabled>Disabled</MenuItem>+ <MenuItem>Enabled 2</MenuItem>+ </>,+ );++ // Navigate down twice — should skip the disabled item+ fireEvent.keyDown(container.firstChild, { keyCode: 40 });+ expect(+ () => fireEvent.keyDown(container.firstChild, { keyCode: 40 }),+ ).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// handleForceClose+// ---------------------------------------------------------------------------++describe('handleForceClose()', () => {+ it('does not throw when called', () => {+ const { container } = renderMenu(+ <MenuItem>Item</MenuItem>,+ );++ // Trigger right arrow to potentially set forceSubMenuOpen, then close+ expect(+ () => fireEvent.keyDown(container.firstChild, { keyCode: 39 }),+ ).not.toThrow();+ });});diff --git a/web/js/util/context-menu/ContextMenu.test.js b/web/js/util/context-menu/ContextMenu.test.jsindex ac74a4a16..f80faf312 100644--- a/web/js/util/context-menu/ContextMenu.test.js+++ b/web/js/util/context-menu/ContextMenu.test.js@@ -1,3 +1,464 @@-test('ContextMenu util test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, fireEvent, act } from '@testing-library/react';+import ContextMenu from './ContextMenu'; // Update path as needed+import listener from './globalEventListener';+import { hideMenu } from './actions';+import { cssClasses } from './helpers';+import MenuItem from './MenuItem';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./globalEventListener', () => ({+ register: jest.fn(() => 'mock-listen-id'),+ unregister: jest.fn(),+}));++jest.mock('./actions', () => ({+ hideMenu: jest.fn(),+ showMenu: jest.fn(),+}));++jest.mock('./helpers', () => ({+ cssClasses: {+ menu: 'react-contextmenu',+ menuVisible: 'react-contextmenu--visible',+ },+ callIfExists: jest.fn((fn, ...args) => fn && fn(...args)),+ store: { data: {}, target: null },+}));++jest.mock('./SubMenu', () => 'SubMenu');++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const MENU_ID = 'test-menu';++function renderMenu(props = {}) {+ return render(+ <ContextMenu id={MENU_ID} {...props}>+ <MenuItem>Item 1</MenuItem>+ <MenuItem>Item 2</MenuItem>+ </ContextMenu>,+ );+}++// Retrieve the handleShow/handleHide callbacks registered with the listener+function getRegisteredHandlers() {+ const [handleShow, handleHide] = listener.register.mock.calls[+ listener.register.mock.calls.length - 1+ ];+ return { handleShow, handleHide };+}++function makeShowEvent(id = MENU_ID, x = 100, y = 200) {+ return { detail: { id, position: { x, y } } };+}++// ---------------------------------------------------------------------------+// Rendering+// ---------------------------------------------------------------------------++describe('ContextMenu rendering', () => {+ beforeEach(() => jest.clearAllMocks());++ it('renders a nav element with role="menu"', () => {+ const { getByRole } = renderMenu();+ expect(getByRole('menu')).toBeTruthy();+ });++ it('applies the base cssClass to the nav', () => {+ const { getByRole } = renderMenu();+ expect(getByRole('menu').className).toContain(cssClasses.menu);+ });++ it('applies a custom className prop', () => {+ const { getByRole } = renderMenu({ className: 'my-custom-class' });+ expect(getByRole('menu').className).toContain('my-custom-class');+ });++ it('is not visible by default (no visible class)', () => {+ const { getByRole } = renderMenu();+ expect(getByRole('menu').className).not.toContain(cssClasses.menuVisible);+ });++ it('renders children', () => {+ const { getByText } = renderMenu();+ expect(getByText('Item 1')).toBeTruthy();+ expect(getByText('Item 2')).toBeTruthy();+ });++ it('applies inline style with position fixed and opacity 0 when hidden', () => {+ const { getByRole } = renderMenu();+ const nav = getByRole('menu');+ expect(nav.style.position).toBe('fixed');+ expect(nav.style.opacity).toBe('0');+ expect(nav.style.pointerEvents).toBe('none');+ });+});++// ---------------------------------------------------------------------------+// Lifecycle — listener registration+// ---------------------------------------------------------------------------++describe('lifecycle', () => {+ beforeEach(() => jest.clearAllMocks());++ it('registers with globalEventListener on mount', () => {+ renderMenu();+ expect(listener.register).toHaveBeenCalledTimes(1);+ });++ it('passes two functions to listener.register', () => {+ renderMenu();+ const [a, b] = listener.register.mock.calls[0];+ expect(typeof a).toBe('function');+ expect(typeof b).toBe('function');+ });++ it('unregisters listener on unmount', () => {+ const { unmount } = renderMenu();+ unmount();+ expect(listener.unregister).toHaveBeenCalledWith('mock-listen-id');+ });++ it('does not call unregister if listenId is falsy', () => {+ listener.register.mockReturnValueOnce(null);+ const { unmount } = renderMenu();+ unmount();+ expect(listener.unregister).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleShow+// ---------------------------------------------------------------------------++describe('handleShow()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('adds the visible class when id matches', () => {+ const { getByRole } = renderMenu();+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent()));++ expect(getByRole('menu').className).toContain(cssClasses.menuVisible);+ });++ it('does not show when id does not match', () => {+ const { getByRole } = renderMenu();+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent('other-menu')));++ expect(getByRole('menu').className).not.toContain(cssClasses.menuVisible);+ });++ it('does not show when menu is already visible', () => {+ const { getByRole } = renderMenu();+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent()));+ act(() => handleShow(makeShowEvent())); // second call — already visible++ expect(getByRole('menu').className).toContain(cssClasses.menuVisible);+ });++ it('calls onShow prop when shown', () => {+ const onShow = jest.fn();+ renderMenu({ onShow });+ const { handleShow } = getRegisteredHandlers();++ const event = makeShowEvent();+ act(() => handleShow(event));++ expect(onShow).toHaveBeenCalled();+ });++ it('registers document handlers when shown', () => {+ const addSpy = jest.spyOn(document, 'addEventListener');+ renderMenu();+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent()));++ expect(addSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));+ expect(addSpy).toHaveBeenCalledWith('keydown', expect.any(Function));+ addSpy.mockRestore();+ });++ it('does not register scroll handler when preventHideOnScroll is true', () => {+ const addSpy = jest.spyOn(document, 'addEventListener');+ renderMenu({ preventHideOnScroll: true });+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent()));++ const scrollCalls = addSpy.mock.calls.filter(([ev]) => ev === 'scroll');+ expect(scrollCalls.length).toBe(0);+ addSpy.mockRestore();+ });++ it('does not register contextmenu handler when preventHideOnContextMenu is true', () => {+ const addSpy = jest.spyOn(document, 'addEventListener');+ renderMenu({ preventHideOnContextMenu: true });+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent()));++ const ctxCalls = addSpy.mock.calls.filter(([ev]) => ev === 'contextmenu');+ expect(ctxCalls.length).toBe(0);+ addSpy.mockRestore();+ });++ it('does not register resize handler when preventHideOnResize is true', () => {+ const addSpy = jest.spyOn(window, 'addEventListener');+ renderMenu({ preventHideOnResize: true });+ const { handleShow } = getRegisteredHandlers();++ act(() => handleShow(makeShowEvent()));++ const resizeCalls = addSpy.mock.calls.filter(([ev]) => ev === 'resize');+ expect(resizeCalls.length).toBe(0);+ addSpy.mockRestore();+ });+});++// ---------------------------------------------------------------------------+// handleHide+// ---------------------------------------------------------------------------++describe('handleHide()', () => {+ beforeEach(() => jest.clearAllMocks());++ function showAndGetHandlers(extraProps = {}) {+ const utils = renderMenu(extraProps);+ const handlers = getRegisteredHandlers();+ act(() => handlers.handleShow(makeShowEvent()));+ return { utils, ...handlers };+ }++ it('hides the menu when called without detail', () => {+ const { utils, handleHide } = showAndGetHandlers();+ act(() => handleHide({}));+ expect(utils.getByRole('menu').className).not.toContain(cssClasses.menuVisible);+ });++ it('hides the menu when detail.id matches', () => {+ const { utils, handleHide } = showAndGetHandlers();+ act(() => handleHide({ detail: { id: MENU_ID } }));+ expect(utils.getByRole('menu').className).not.toContain(cssClasses.menuVisible);+ });++ it('does not hide when detail.id is a different menu', () => {+ const { utils, handleHide } = showAndGetHandlers();+ act(() => handleHide({ detail: { id: 'other-menu' } }));+ expect(utils.getByRole('menu').className).toContain(cssClasses.menuVisible);+ });++ it('calls onHide prop when hidden', () => {+ const onHide = jest.fn();+ const { handleHide } = showAndGetHandlers({ onHide });+ act(() => handleHide({}));+ expect(onHide).toHaveBeenCalled();+ });++ it('unregisters document handlers when hidden', () => {+ const removeSpy = jest.spyOn(document, 'removeEventListener');+ const { handleHide } = showAndGetHandlers();+ act(() => handleHide({}));+ expect(removeSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));+ expect(removeSpy).toHaveBeenCalledWith('keydown', expect.any(Function));+ removeSpy.mockRestore();+ });++ it('does nothing when menu is already hidden', () => {+ renderMenu();+ const { handleHide } = getRegisteredHandlers();+ const onHide = jest.fn();++ // menu was never shown — handleHide should be a no-op+ act(() => handleHide({}));+ expect(onHide).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleOutsideClick+// ---------------------------------------------------------------------------++describe('handleOutsideClick()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls hideMenu when click is outside the menu', () => {+ renderMenu();+ const { handleShow } = getRegisteredHandlers();+ act(() => handleShow(makeShowEvent()));++ // Click on an element outside the menu+ const outside = document.createElement('div');+ document.body.appendChild(outside);+ act(() => fireEvent.mouseDown(outside));++ expect(hideMenu).toHaveBeenCalled();+ document.body.removeChild(outside);+ });++ it('does not call hideMenu when click is inside the menu', () => {+ const { getByText } = renderMenu();+ const { handleShow } = getRegisteredHandlers();+ act(() => handleShow(makeShowEvent()));++ act(() => fireEvent.mouseDown(getByText('Item 1')));++ expect(hideMenu).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleMouseLeave+// ---------------------------------------------------------------------------++describe('handleMouseLeave()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls onMouseLeave prop', () => {+ const onMouseLeave = jest.fn();+ const { getByRole } = renderMenu({ onMouseLeave });+ act(() => fireEvent.mouseLeave(getByRole('menu')));+ expect(onMouseLeave).toHaveBeenCalled();+ });++ it('calls hideMenu when hideOnLeave is true', () => {+ const { getByRole } = renderMenu({ hideOnLeave: true });+ act(() => fireEvent.mouseLeave(getByRole('menu')));+ expect(hideMenu).toHaveBeenCalled();+ });++ it('does not call hideMenu when hideOnLeave is false', () => {+ const { getByRole } = renderMenu({ hideOnLeave: false });+ act(() => fireEvent.mouseLeave(getByRole('menu')));+ expect(hideMenu).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleContextMenu+// ---------------------------------------------------------------------------++describe('handleContextMenu()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('does not throw when right-clicking inside the menu', () => {+ const { getByRole } = renderMenu();+ expect(() => act(() => fireEvent.contextMenu(getByRole('menu')))).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// hideMenu (keyboard)+// ---------------------------------------------------------------------------++describe('hideMenu() keyboard handler', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls hideMenu on Escape key (27)', () => {+ renderMenu();+ const { handleShow } = getRegisteredHandlers();+ act(() => handleShow(makeShowEvent()));++ act(() => fireEvent.keyDown(document, { keyCode: 27 }));++ expect(hideMenu).toHaveBeenCalled();+ });++ it('calls hideMenu on Enter key (13)', () => {+ renderMenu();+ const { handleShow } = getRegisteredHandlers();+ act(() => handleShow(makeShowEvent()));++ act(() => fireEvent.keyDown(document, { keyCode: 13 }));++ expect(hideMenu).toHaveBeenCalled();+ });++ it('does not call hideMenu on other keys', () => {+ renderMenu();+ const { handleShow } = getRegisteredHandlers();+ act(() => handleShow(makeShowEvent()));++ act(() => fireEvent.keyDown(document, { keyCode: 65 })); // 'a'++ expect(hideMenu).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// getMenuPosition+// ---------------------------------------------------------------------------++describe('getMenuPosition()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('returns default top/left when no menu ref exists', () => {+ const menu = new ContextMenu({ id: MENU_ID, children: [] });+ menu.menu = null;+ const pos = menu.getMenuPosition(50, 80);+ expect(pos).toEqual({ top: 80, left: 50 });+ });++ it('adjusts left when menu would overflow right edge', () => {+ const menu = new ContextMenu({ id: MENU_ID, children: [] });+ menu.menu = {+ getBoundingClientRect: () => ({ width: 200, height: 100 }),+ };+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 300 });+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 600 });++ const pos = menu.getMenuPosition(250, 100); // 250 + 200 > 300+ expect(pos.left).toBeLessThan(250);+ });++ it('adjusts top when menu would overflow bottom edge', () => {+ const menu = new ContextMenu({ id: MENU_ID, children: [] });+ menu.menu = {+ getBoundingClientRect: () => ({ width: 100, height: 200 }),+ };+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 600 });+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 300 });++ const pos = menu.getMenuPosition(50, 250); // 250 + 200 > 300+ expect(pos.top).toBeLessThan(250);+ });+});++// ---------------------------------------------------------------------------+// getRTLMenuPosition+// ---------------------------------------------------------------------------++describe('getRTLMenuPosition()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('returns default top/left when no menu ref exists', () => {+ const menu = new ContextMenu({ id: MENU_ID, children: [] });+ menu.menu = null;+ const pos = menu.getRTLMenuPosition(50, 80);+ expect(pos).toEqual({ top: 80, left: 50 });+ });++ it('positions menu to the left of the cursor in RTL mode', () => {+ const menu = new ContextMenu({ id: MENU_ID, children: [] });+ menu.menu = {+ getBoundingClientRect: () => ({ width: 100, height: 50 }),+ };+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 800 });+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 600 });++ const pos = menu.getRTLMenuPosition(300, 100);+ expect(pos.left).toBe(200); // 300 - 100+ });});diff --git a/web/js/util/context-menu/ContextMenuTrigger.test.js b/web/js/util/context-menu/ContextMenuTrigger.test.jsindex 5e25a2503..275aa540f 100644--- a/web/js/util/context-menu/ContextMenuTrigger.test.js+++ b/web/js/util/context-menu/ContextMenuTrigger.test.js@@ -1,3 +1,389 @@-test('ContextMenuTrigger util test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, fireEvent, act } from '@testing-library/react';+import ContextMenuTrigger from './ContextMenuTrigger'; // Update path as needed+import { showMenu, hideMenu } from './actions';+import { cssClasses } from './helpers';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./actions', () => ({+ showMenu: jest.fn(),+ hideMenu: jest.fn(),+}));++jest.mock('./helpers', () => ({+ callIfExists: jest.fn((fn, ...args) => fn && fn(...args)),+ cssClasses: {+ menuWrapper: 'react-contextmenu-wrapper',+ },+}));++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const MENU_ID = 'test-menu';++function renderTrigger(props = {}) {+ return render(+ <ContextMenuTrigger id={MENU_ID} {...props}>+ <span data-testid="child">Right click me</span>+ </ContextMenuTrigger>,+ );+}++function rightClickEvent(overrides = {}) {+ return { button: 2, clientX: 100, clientY: 200, ...overrides };+}++// ---------------------------------------------------------------------------+// Rendering+// ---------------------------------------------------------------------------++describe('ContextMenuTrigger rendering', () => {+ beforeEach(() => jest.clearAllMocks());++ it('renders a div wrapper by default', () => {+ const { container } = renderTrigger();+ expect(container.firstChild.tagName).toBe('DIV');+ });++ it('renders a custom tag when renderTag is provided', () => {+ const { container } = renderTrigger({ renderTag: 'span' });+ expect(container.firstChild.tagName).toBe('SPAN');+ });++ it('applies the menuWrapper cssClass', () => {+ const { container } = renderTrigger();+ expect(container.firstChild.className).toContain(cssClasses.menuWrapper);+ });++ it('applies additional className from attributes prop', () => {+ const { container } = renderTrigger({ attributes: { className: 'extra-class' } });+ expect(container.firstChild.className).toContain('extra-class');+ });++ it('renders children', () => {+ const { getByTestId } = renderTrigger();+ expect(getByTestId('child')).toBeTruthy();+ });++ it('passes through additional attributes to the wrapper element', () => {+ const { container } = renderTrigger({ attributes: { 'data-custom': 'value' } });+ expect(container.firstChild.getAttribute('data-custom')).toBe('value');+ });+});++// ---------------------------------------------------------------------------+// handleContextMenu+// ---------------------------------------------------------------------------++describe('handleContextMenu()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls showMenu on right-click (button 2)', () => {+ const { container } = renderTrigger();+ fireEvent.contextMenu(container.firstChild, rightClickEvent());+ expect(showMenu).toHaveBeenCalled();+ });++ it('calls hideMenu before showMenu', () => {+ const callOrder = [];+ hideMenu.mockImplementation(() => callOrder.push('hide'));+ showMenu.mockImplementation(() => callOrder.push('show'));++ const { container } = renderTrigger();+ fireEvent.contextMenu(container.firstChild, rightClickEvent());++ expect(callOrder).toEqual(['hide', 'show']);+ });++ it('does not call showMenu when mouseButton does not match', () => {+ const { container } = renderTrigger({ mouseButton: 0 });+ fireEvent.contextMenu(container.firstChild, rightClickEvent({ button: 2 }));+ expect(showMenu).not.toHaveBeenCalled();+ });++ it('calls the onContextMenu attribute callback', () => {+ const onContextMenu = jest.fn();+ const { container } = renderTrigger({ attributes: { onContextMenu } });+ fireEvent.contextMenu(container.firstChild, rightClickEvent());+ expect(onContextMenu).toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleContextClick+// ---------------------------------------------------------------------------++describe('handleContextClick()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('does not call showMenu when disable is true', () => {+ const { container } = renderTrigger({ disable: true });+ fireEvent.contextMenu(container.firstChild, rightClickEvent());+ expect(showMenu).not.toHaveBeenCalled();+ });++ it('does not call showMenu when disableIfShiftIsPressed and shiftKey is true', () => {+ const { container } = renderTrigger({ disableIfShiftIsPressed: true });+ fireEvent.contextMenu(container.firstChild, rightClickEvent({ shiftKey: true }));+ expect(showMenu).not.toHaveBeenCalled();+ });++ it('calls showMenu when disableIfShiftIsPressed but shiftKey is false', () => {+ const { container } = renderTrigger({ disableIfShiftIsPressed: true });+ fireEvent.contextMenu(container.firstChild, rightClickEvent({ shiftKey: false }));+ expect(showMenu).toHaveBeenCalled();+ });++ it('passes position x/y from clientX/clientY to showMenu', () => {+ const { container } = renderTrigger();+ fireEvent.contextMenu(container.firstChild, rightClickEvent({ clientX: 150, clientY: 250 }));+ const config = showMenu.mock.calls[0][0];+ expect(config.position.x).toBe(150);+ expect(config.position.y).toBe(250);+ });++ it('subtracts posX and posY offsets from position', () => {+ const { container } = renderTrigger({ posX: 10, posY: 20 });+ fireEvent.contextMenu(container.firstChild, rightClickEvent({ clientX: 150, clientY: 250 }));+ const config = showMenu.mock.calls[0][0];+ expect(config.position.x).toBe(140);+ expect(config.position.y).toBe(230);+ });++ it('passes the menu id to showMenu', () => {+ const { container } = renderTrigger();+ fireEvent.contextMenu(container.firstChild, rightClickEvent());+ const config = showMenu.mock.calls[0][0];+ expect(config.id).toBe(MENU_ID);+ });++ it('includes data from collect function in showMenu config', () => {+ const collect = jest.fn(() => ({ customKey: 'customValue' }));+ const { container } = renderTrigger({ collect });+ fireEvent.contextMenu(container.firstChild, rightClickEvent());+ const config = showMenu.mock.calls[0][0];+ expect(config.data.customKey).toBe('customValue');+ });++ it('handles a Promise returned from collect', async () => {+ const collect = jest.fn(() => Promise.resolve({ asyncKey: 'asyncValue' }));+ const { container } = renderTrigger({ collect });++ await act(async () => {+ fireEvent.contextMenu(container.firstChild, rightClickEvent());+ });++ const config = showMenu.mock.calls[0][0];+ expect(config.data.asyncKey).toBe('asyncValue');+ });+});++// ---------------------------------------------------------------------------+// handleMouseClick+// ---------------------------------------------------------------------------++describe('handleMouseClick()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls showMenu when mouseButton is 0 and left click occurs', () => {+ const { container } = renderTrigger({ mouseButton: 0 });+ fireEvent.click(container.firstChild, { button: 0, clientX: 100, clientY: 200 });+ expect(showMenu).toHaveBeenCalled();+ });++ it('does not call showMenu when button does not match mouseButton', () => {+ const { container } = renderTrigger({ mouseButton: 0 });+ fireEvent.click(container.firstChild, { button: 2 });+ expect(showMenu).not.toHaveBeenCalled();+ });++ it('calls the onClick attribute callback', () => {+ const onClick = jest.fn();+ const { container } = renderTrigger({ mouseButton: 0, attributes: { onClick } });+ fireEvent.click(container.firstChild, { button: 0, clientX: 100, clientY: 200 });+ expect(onClick).toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleMouseDown / handleMouseUp / handleMouseOut+// ---------------------------------------------------------------------------++describe('handleMouseDown()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls the onMouseDown attribute callback', () => {+ const onMouseDown = jest.fn();+ const { container } = renderTrigger({ attributes: { onMouseDown } });+ fireEvent.mouseDown(container.firstChild, { button: 0 });+ expect(onMouseDown).toHaveBeenCalled();+ });++ it('triggers context click after holdToDisplay timeout on left click', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: 500 });++ fireEvent.mouseDown(container.firstChild, {+ button: 0,+ clientX: 100,+ clientY: 200,+ persist: jest.fn(),+ stopPropagation: jest.fn(),+ });++ act(() => jest.advanceTimersByTime(500));++ expect(showMenu).toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('does not trigger hold timeout when holdToDisplay is -1', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: -1 });++ fireEvent.mouseDown(container.firstChild, { button: 0 });++ act(() => jest.advanceTimersByTime(2000));++ expect(showMenu).not.toHaveBeenCalled();+ jest.useRealTimers();+ });+});++describe('handleMouseUp()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('cancels the hold timeout on mouse up', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: 500 });++ fireEvent.mouseDown(container.firstChild, {+ button: 0,+ clientX: 100,+ clientY: 200,+ persist: jest.fn(),+ stopPropagation: jest.fn(),+ });++ fireEvent.mouseUp(container.firstChild, { button: 0 });+ act(() => jest.advanceTimersByTime(500));++ expect(showMenu).not.toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('calls the onMouseUp attribute callback', () => {+ const onMouseUp = jest.fn();+ const { container } = renderTrigger({ attributes: { onMouseUp } });+ fireEvent.mouseUp(container.firstChild, { button: 0 });+ expect(onMouseUp).toHaveBeenCalled();+ });+});++describe('handleMouseOut()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('cancels the hold timeout on mouse out', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: 500 });++ fireEvent.mouseDown(container.firstChild, {+ button: 0,+ clientX: 100,+ clientY: 200,+ persist: jest.fn(),+ stopPropagation: jest.fn(),+ });++ fireEvent.mouseOut(container.firstChild, { button: 0 });+ act(() => jest.advanceTimersByTime(500));++ expect(showMenu).not.toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('calls the onMouseOut attribute callback', () => {+ const onMouseOut = jest.fn();+ const { container } = renderTrigger({ attributes: { onMouseOut } });+ fireEvent.mouseOut(container.firstChild, { button: 0 });+ expect(onMouseOut).toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleTouchstart / handleTouchEnd+// ---------------------------------------------------------------------------++describe('handleTouchstart()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('triggers context click after holdToDisplay timeout on touch', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: 500 });++ fireEvent.touchStart(container.firstChild, {+ touches: [{ pageX: 100, pageY: 200 }],+ persist: jest.fn(),+ stopPropagation: jest.fn(),+ });++ act(() => jest.advanceTimersByTime(500));++ expect(showMenu).toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('does not trigger when holdToDisplay is -1', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: -1 });++ fireEvent.touchStart(container.firstChild, {+ touches: [{ pageX: 100, pageY: 200 }],+ });++ act(() => jest.advanceTimersByTime(2000));++ expect(showMenu).not.toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('calls the onTouchStart attribute callback', () => {+ const onTouchStart = jest.fn();+ const { container } = renderTrigger({ attributes: { onTouchStart } });+ fireEvent.touchStart(container.firstChild);+ expect(onTouchStart).toHaveBeenCalled();+ });+});++describe('handleTouchEnd()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('cancels the touch hold timeout on touch end', () => {+ jest.useFakeTimers();+ const { container } = renderTrigger({ holdToDisplay: 500 });++ fireEvent.touchStart(container.firstChild, {+ touches: [{ pageX: 100, pageY: 200 }],+ persist: jest.fn(),+ stopPropagation: jest.fn(),+ });++ fireEvent.touchEnd(container.firstChild);+ act(() => jest.advanceTimersByTime(500));++ expect(showMenu).not.toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('calls the onTouchEnd attribute callback', () => {+ const onTouchEnd = jest.fn();+ const { container } = renderTrigger({ attributes: { onTouchEnd } });+ fireEvent.touchEnd(container.firstChild);+ expect(onTouchEnd).toHaveBeenCalled();+ });});diff --git a/web/js/util/context-menu/MenuItem.test.js b/web/js/util/context-menu/MenuItem.test.jsindex edd508312..eb5beeb53 100644--- a/web/js/util/context-menu/MenuItem.test.js+++ b/web/js/util/context-menu/MenuItem.test.js@@ -1,3 +1,437 @@-test('MenuItem module test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, fireEvent } from '@testing-library/react';+import MenuItem from './MenuItem'; // Update path as needed+import { hideMenu } from './actions';+import { callIfExists, cssClasses, store } from './helpers';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./actions', () => ({+ hideMenu: jest.fn(),+}));++jest.mock('./helpers', () => ({+ callIfExists: jest.fn((fn, ...args) => fn && fn(...args)),+ cssClasses: {+ menuItem: 'react-contextmenu-item',+ menuItemDisabled: 'react-contextmenu-item--disabled',+ menuItemDivider: 'react-contextmenu-item--divider',+ menuItemSelected: 'react-contextmenu-item--selected',+ },+ store: { data: {}, target: null },+}));++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function renderItem(props = {}) {+ return render(+ <MenuItem {...props}>+ {props.children ?? <span data-testid="child">Item Label</span>}+ </MenuItem>,+ );+}++function clickItem(element, button = 0) {+ fireEvent.click(element, { button });+}++// ---------------------------------------------------------------------------+// Rendering+// ---------------------------------------------------------------------------++describe('MenuItem rendering', () => {+ beforeEach(() => jest.clearAllMocks());++ it('renders a div with role="menuitem"', () => {+ const { getByRole } = renderItem();+ expect(getByRole('menuitem')).toBeTruthy();+ });++ it('renders children by default', () => {+ const { getByTestId } = renderItem();+ expect(getByTestId('child')).toBeTruthy();+ });++ it('does not render children when divider is true', () => {+ const { queryByTestId } = renderItem({ divider: true });+ expect(queryByTestId('child')).toBeNull();+ });++ it('applies the base menuItem cssClass', () => {+ const { getByRole } = renderItem();+ expect(getByRole('menuitem').className).toContain(cssClasses.menuItem);+ });++ it('applies a custom className prop', () => {+ const { getByRole } = renderItem({ className: 'my-custom-class' });+ expect(getByRole('menuitem').className).toContain('my-custom-class');+ });++ it('applies attributes.className', () => {+ const { getByRole } = renderItem({ attributes: { className: 'attr-class' } });+ expect(getByRole('menuitem').className).toContain('attr-class');+ });++ it('applies disabled class when disabled is true', () => {+ const { getByRole } = renderItem({ disabled: true });+ expect(getByRole('menuitem').className).toContain(cssClasses.menuItemDisabled);+ });++ it('applies attributes.disabledClassName when disabled', () => {+ const { getByRole } = renderItem({+ disabled: true,+ attributes: { disabledClassName: 'custom-disabled' },+ });+ expect(getByRole('menuitem').className).toContain('custom-disabled');+ });++ it('does not apply disabled class when disabled is false', () => {+ const { getByRole } = renderItem({ disabled: false });+ expect(getByRole('menuitem').className).not.toContain(cssClasses.menuItemDisabled);+ });++ it('applies divider class when divider is true', () => {+ const { getByRole } = renderItem({ divider: true });+ expect(getByRole('menuitem').className).toContain(cssClasses.menuItemDivider);+ });++ it('applies attributes.dividerClassName when divider', () => {+ const { getByRole } = renderItem({+ divider: true,+ attributes: { dividerClassName: 'custom-divider' },+ });+ expect(getByRole('menuitem').className).toContain('custom-divider');+ });++ it('does not apply divider class when divider is false', () => {+ const { getByRole } = renderItem({ divider: false });+ expect(getByRole('menuitem').className).not.toContain(cssClasses.menuItemDivider);+ });++ it('applies selected class when selected is true', () => {+ const { getByRole } = renderItem({ selected: true });+ expect(getByRole('menuitem').className).toContain(cssClasses.menuItemSelected);+ });++ it('applies attributes.selectedClassName when selected', () => {+ const { getByRole } = renderItem({+ selected: true,+ attributes: { selectedClassName: 'custom-selected' },+ });+ expect(getByRole('menuitem').className).toContain('custom-selected');+ });++ it('does not apply selected class when selected is false', () => {+ const { getByRole } = renderItem({ selected: false });+ expect(getByRole('menuitem').className).not.toContain(cssClasses.menuItemSelected);+ });++ it('sets aria-disabled to "true" when disabled', () => {+ const { getByRole } = renderItem({ disabled: true });+ expect(getByRole('menuitem').getAttribute('aria-disabled')).toBe('true');+ });++ it('sets aria-disabled to "false" when not disabled', () => {+ const { getByRole } = renderItem({ disabled: false });+ expect(getByRole('menuitem').getAttribute('aria-disabled')).toBe('false');+ });++ it('sets aria-orientation to "horizontal" when divider', () => {+ const { getByRole } = renderItem({ divider: true });+ expect(getByRole('menuitem').getAttribute('aria-orientation')).toBe('horizontal');+ });++ it('does not set aria-orientation when not a divider', () => {+ const { getByRole } = renderItem({ divider: false });+ expect(getByRole('menuitem').getAttribute('aria-orientation')).toBeNull();+ });++ it('passes through extra attributes to the div', () => {+ const { getByRole } = renderItem({ attributes: { 'data-custom': 'value' } });+ expect(getByRole('menuitem').getAttribute('data-custom')).toBe('value');+ });++ it('renders null children when children prop is null', () => {+ const { getByRole } = renderItem({ children: null });+ expect(getByRole('menuitem')).toBeTruthy();+ });+});++// ---------------------------------------------------------------------------+// handleClick — button guard+// ---------------------------------------------------------------------------++describe('handleClick() button guard', () => {+ beforeEach(() => jest.clearAllMocks());++ it('does not prevent default for left click (button 0)', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ onClick });+ fireEvent.click(getByRole('menuitem'), { button: 0 });+ expect(onClick).toHaveBeenCalled();+ expect(hideMenu).toHaveBeenCalled();+ });++ it('calls onClick for middle click (button 1)', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ onClick });+ fireEvent.click(getByRole('menuitem'), { button: 1 });+ expect(onClick).toHaveBeenCalled();+ });++ it('calls hideMenu for middle click (button 1)', () => {+ const { getByRole } = renderItem();+ fireEvent.click(getByRole('menuitem'), { button: 1 });+ expect(hideMenu).toHaveBeenCalled();+ });++ it('does not call onClick or hideMenu for button > 1 when disabled', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ disabled: true, onClick });+ fireEvent.click(getByRole('menuitem'), { button: 2 });+ expect(onClick).not.toHaveBeenCalled();+ expect(hideMenu).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleClick — disabled / divider guards+// ---------------------------------------------------------------------------++describe('handleClick() disabled and divider guards', () => {+ beforeEach(() => jest.clearAllMocks());++ it('does not call onClick when disabled', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ disabled: true, onClick });+ clickItem(getByRole('menuitem'));+ expect(onClick).not.toHaveBeenCalled();+ });++ it('does not call hideMenu when disabled', () => {+ const { getByRole } = renderItem({ disabled: true });+ clickItem(getByRole('menuitem'));+ expect(hideMenu).not.toHaveBeenCalled();+ });++ it('does not call onClick when divider is true', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ divider: true, onClick });+ clickItem(getByRole('menuitem'));+ expect(onClick).not.toHaveBeenCalled();+ });++ it('does not call hideMenu when divider is true', () => {+ const { getByRole } = renderItem({ divider: true });+ clickItem(getByRole('menuitem'));+ expect(hideMenu).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleClick — preventClose+// ---------------------------------------------------------------------------++describe('handleClick() preventClose', () => {+ beforeEach(() => jest.clearAllMocks());++ it('does not call hideMenu when preventClose is true', () => {+ const { getByRole } = renderItem({ preventClose: true });+ clickItem(getByRole('menuitem'));+ expect(hideMenu).not.toHaveBeenCalled();+ });++ it('still calls onClick when preventClose is true', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ preventClose: true, onClick });+ clickItem(getByRole('menuitem'));+ expect(onClick).toHaveBeenCalled();+ });++ it('calls hideMenu when preventClose is false', () => {+ const { getByRole } = renderItem({ preventClose: false });+ clickItem(getByRole('menuitem'));+ expect(hideMenu).toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleClick — data merging+// ---------------------------------------------------------------------------++describe('handleClick() data merging', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ store.data = {};+ store.target = null;+ });++ it('passes merged data and store.data to onClick', () => {+ const onClick = jest.fn();+ store.data = { storeKey: 'storeValue' };++ const { getByRole } = renderItem({ onClick, data: { itemKey: 'itemValue' } });+ clickItem(getByRole('menuitem'));++ const dataArg = onClick.mock.calls[0][1];+ expect(dataArg.itemKey).toBe('itemValue');+ expect(dataArg.storeKey).toBe('storeValue');+ });++ it('store.data properties override item data properties with same key', () => {+ const onClick = jest.fn();+ store.data = { key: 'fromStore' };++ const { getByRole } = renderItem({ onClick, data: { key: 'fromItem' } });+ clickItem(getByRole('menuitem'));++ const dataArg = onClick.mock.calls[0][1];+ expect(dataArg.key).toBe('fromStore');+ });++ it('passes store.target as the third argument to onClick', () => {+ const onClick = jest.fn();+ const mockTarget = document.createElement('div');+ store.target = mockTarget;++ const { getByRole } = renderItem({ onClick });+ clickItem(getByRole('menuitem'));++ expect(onClick.mock.calls[0][2]).toBe(mockTarget);+ });++ it('passes the click event as the first argument to onClick', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ onClick });+ clickItem(getByRole('menuitem'));++ const eventArg = onClick.mock.calls[0][0];+ expect(eventArg).toBeTruthy();+ expect(typeof eventArg.preventDefault).toBe('function');+ });++ it('works when data prop is an empty object', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ onClick, data: {} });+ clickItem(getByRole('menuitem'));+ expect(onClick).toHaveBeenCalled();+ });++ it('works when store.data is empty', () => {+ const onClick = jest.fn();+ store.data = {};+ const { getByRole } = renderItem({ onClick, data: { key: 'value' } });+ clickItem(getByRole('menuitem'));+ const dataArg = onClick.mock.calls[0][1];+ expect(dataArg.key).toBe('value');+ });+});++// ---------------------------------------------------------------------------+// Mouse event handlers+// ---------------------------------------------------------------------------++describe('mouse event handlers', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls onMouseMove prop when mouse moves over item', () => {+ const onMouseMove = jest.fn();+ const { getByRole } = renderItem({ onMouseMove });+ fireEvent.mouseMove(getByRole('menuitem'));+ expect(onMouseMove).toHaveBeenCalled();+ });++ it('calls onMouseLeave prop when mouse leaves item', () => {+ const onMouseLeave = jest.fn();+ const { getByRole } = renderItem({ onMouseLeave });+ fireEvent.mouseLeave(getByRole('menuitem'));+ expect(onMouseLeave).toHaveBeenCalled();+ });++ it('does not throw when default onMouseMove is used', () => {+ const { getByRole } = renderItem();+ expect(() => fireEvent.mouseMove(getByRole('menuitem'))).not.toThrow();+ });++ it('does not throw when default onMouseLeave is used', () => {+ const { getByRole } = renderItem();+ expect(() => fireEvent.mouseLeave(getByRole('menuitem'))).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// Touch handler+// ---------------------------------------------------------------------------++describe('touch handler (onTouchEnd)', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls onClick on touch end with button 0', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ onClick });+ fireEvent.touchEnd(getByRole('menuitem'), { button: 0 });+ expect(onClick).toHaveBeenCalled();+ });++ it('calls hideMenu on touch end by default', () => {+ const { getByRole } = renderItem();+ fireEvent.touchEnd(getByRole('menuitem'), { button: 0 });+ expect(hideMenu).toHaveBeenCalled();+ });++ it('does not call onClick on touch end when disabled', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ disabled: true, onClick });+ fireEvent.touchEnd(getByRole('menuitem'), { button: 0 });+ expect(onClick).not.toHaveBeenCalled();+ });++ it('does not call hideMenu on touch end when divider is true', () => {+ const { getByRole } = renderItem({ divider: true });+ fireEvent.touchEnd(getByRole('menuitem'), { button: 0 });+ expect(hideMenu).not.toHaveBeenCalled();+ });++ it('does not call hideMenu on touch end when preventClose is true', () => {+ const { getByRole } = renderItem({ preventClose: true });+ fireEvent.touchEnd(getByRole('menuitem'), { button: 0 });+ expect(hideMenu).not.toHaveBeenCalled();+ });++ it('calls preventDefault for touch end with button > 1', () => {+ const { getByRole } = renderItem();+ // button 2 triggers the preventDefault branch+ expect(() =>+ fireEvent.touchEnd(getByRole('menuitem'), { button: 2 }),+ ).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// callIfExists integration+// ---------------------------------------------------------------------------++describe('callIfExists integration', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls callIfExists with the onClick prop', () => {+ const onClick = jest.fn();+ const { getByRole } = renderItem({ onClick });+ clickItem(getByRole('menuitem'));+ expect(callIfExists).toHaveBeenCalledWith(+ onClick,+ expect.anything(), // event+ expect.anything(), // merged data+ store.target,+ );+ });++ it('does not throw when onClick prop is not provided (uses default)', () => {+ const { getByRole } = renderItem();+ expect(() => clickItem(getByRole('menuitem'))).not.toThrow();+ });});diff --git a/web/js/util/context-menu/SubMenu.test.js b/web/js/util/context-menu/SubMenu.test.jsindex 27074136b..c4ccd458b 100644--- a/web/js/util/context-menu/SubMenu.test.js+++ b/web/js/util/context-menu/SubMenu.test.js@@ -1,3 +1,639 @@-test('SubMenu module test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, fireEvent, act } from '@testing-library/react';+import SubMenu from './SubMenu';+import MenuItem from './MenuItem';+import { hideMenu } from './actions';+import { callIfExists, cssClasses, store } from './helpers';+import listener from './globalEventListener';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./actions', () => ({ hideMenu: jest.fn() }));++jest.mock('./helpers', () => ({+ callIfExists: jest.fn((fn, ...args) => fn && fn(...args)),+ hasOwnProp: jest.fn((obj, key) => Object.prototype.hasOwnProperty.call(obj, key)),+ cssClasses: {+ menu: 'react-contextmenu',+ menuVisible: 'react-contextmenu--visible',+ menuItem: 'react-contextmenu-item',+ menuItemActive: 'react-contextmenu-item--active',+ menuItemDisabled: 'react-contextmenu-item--disabled',+ menuItemSelected: 'react-contextmenu-item--selected',+ subMenu: 'react-contextmenu-submenu',+ },+ store: { data: {}, target: null },+}));++jest.mock('./globalEventListener', () => ({+ register: jest.fn(() => 'mock-listen-id'),+ unregister: jest.fn(),+}));++// ---------------------------------------------------------------------------+// Silence React DOM unknown prop warnings+// ---------------------------------------------------------------------------++beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => {+ console.error.mockRestore();+ store.data = {};+ store.target = null;+});++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function renderSubMenu(props = {}) {+ return render(+ <SubMenu title={<span data-testid="title">Submenu</span>} {...props}>+ <MenuItem>Child Item</MenuItem>+ </SubMenu>,+ );+}++function getHideHandler() {+ return listener.register.mock.calls[listener.register.mock.calls.length - 1][1];+}++function openSubMenu(outerNav, delay = 100) {+ fireEvent.mouseEnter(outerNav);+ act(() => jest.advanceTimersByTime(delay));+}++function setupSubMenuRect(subMenuNav, overrides = {}) {+ subMenuNav.getBoundingClientRect = () => ({+ bottom: 100,+ right: 100,+ left: 50,+ width: 100,+ height: 50,+ ...overrides,+ });+}++// ---------------------------------------------------------------------------+// Rendering+// ---------------------------------------------------------------------------++describe('rendering', () => {+ it('renders nav with role menuitem', () => {+ const { getAllByRole } = renderSubMenu();+ expect(getAllByRole('menuitem').length).toBeGreaterThan(0);+ });++ it('renders title', () => {+ const { getByTestId } = renderSubMenu();+ expect(getByTestId('title')).toBeTruthy();+ });++ it('renders children', () => {+ const { getByText } = renderSubMenu();+ expect(getByText('Child Item')).toBeTruthy();+ });++ it('applies menuItem and subMenu classes to outer nav', () => {+ const { getAllByRole } = renderSubMenu();+ const nav = getAllByRole('menuitem')[0];+ expect(nav.className).toContain(cssClasses.menuItem);+ expect(nav.className).toContain(cssClasses.subMenu);+ });++ it('applies custom className to inner nav', () => {+ const { getAllByRole } = renderSubMenu({ className: 'custom' });+ expect(getAllByRole('menu')[0].className).toContain('custom');+ });++ it('applies disabled class when disabled', () => {+ const { getByTestId } = renderSubMenu({ disabled: true });+ expect(getByTestId('title').parentElement.className).toContain(cssClasses.menuItemDisabled);+ });++ it('applies attributes.disabledClassName when disabled', () => {+ const { getByTestId } = renderSubMenu({+ disabled: true,+ attributes: { disabledClassName: 'dis' },+ });+ expect(getByTestId('title').parentElement.className).toContain('dis');+ });++ it('applies selected class when selected', () => {+ const { getByTestId } = renderSubMenu({ selected: true });+ expect(getByTestId('title').parentElement.className).toContain(cssClasses.menuItemSelected);+ });++ it('applies attributes.selectedClassName when selected', () => {+ const { getByTestId } = renderSubMenu({+ selected: true,+ attributes: { selectedClassName: 'sel' },+ });+ expect(getByTestId('title').parentElement.className).toContain('sel');+ });++ it('applies attributes.visibleClassName when visible', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({+ hoverDelay: 100,+ attributes: { visibleClassName: 'vis' },+ });+ openSubMenu(getAllByRole('menuitem')[0]);+ expect(getByTestId('title').parentElement.className).toContain('vis');+ jest.useRealTimers();+ });++ it('applies attributes.listClassName to outer nav', () => {+ const { getAllByRole } = renderSubMenu({ attributes: { listClassName: 'list' } });+ expect(getAllByRole('menuitem')[0].className).toContain('list');+ });++ it('applies attributes.className to title div', () => {+ const { getByTestId } = renderSubMenu({ attributes: { className: 'attr' } });+ expect(getByTestId('title').parentElement.className).toContain('attr');+ });++ it('forwards onMouseMove to title div', () => {+ const onMouseMove = jest.fn();+ const { getByTestId } = renderSubMenu({ onMouseMove });+ fireEvent.mouseMove(getByTestId('title').parentElement);+ expect(onMouseMove).toHaveBeenCalled();+ });++ it('forwards onMouseOut to title div', () => {+ const onMouseOut = jest.fn();+ const { getByTestId } = renderSubMenu({ onMouseOut });+ fireEvent.mouseOut(getByTestId('title').parentElement);+ expect(onMouseOut).toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// Lifecycle+// ---------------------------------------------------------------------------++describe('lifecycle', () => {+ it('registers listener on mount', () => {+ renderSubMenu();+ // clearAllMocks runs in beforeEach so count is exactly 1 per test+ expect(listener.register).toHaveBeenCalledTimes(1);+ });++ it('unregisters listener on unmount', () => {+ const { unmount } = renderSubMenu();+ unmount();+ expect(listener.unregister).toHaveBeenCalledWith('mock-listen-id');+ });++ it('does not unregister when listenId is falsy', () => {+ listener.register.mockReturnValueOnce(null);+ const { unmount } = renderSubMenu();+ unmount();+ expect(listener.unregister).not.toHaveBeenCalled();+ });++ it('clears open timer on unmount', () => {+ jest.useFakeTimers();+ const clearSpy = jest.spyOn(global, 'clearTimeout');+ const { getAllByRole, unmount } = renderSubMenu({ hoverDelay: 500 });+ fireEvent.mouseEnter(getAllByRole('menuitem')[0]);+ unmount();+ expect(clearSpy).toHaveBeenCalled();+ clearSpy.mockRestore();+ jest.useRealTimers();+ });++ it('clears close timer on unmount', () => {+ jest.useFakeTimers();+ const clearSpy = jest.spyOn(global, 'clearTimeout');+ const { getAllByRole, unmount } = renderSubMenu({ hoverDelay: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ fireEvent.mouseLeave(getAllByRole('menuitem')[0]);+ unmount();+ expect(clearSpy).toHaveBeenCalled();+ clearSpy.mockRestore();+ jest.useRealTimers();+ });+});++// ---------------------------------------------------------------------------+// shouldComponentUpdate+// ---------------------------------------------------------------------------++describe('shouldComponentUpdate', () => {+ it('always returns true and tracks visibility change', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({ hoverDelay: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ expect(getByTestId('title').parentElement.className).toContain(cssClasses.menuItemActive);+ jest.useRealTimers();+ });++ it('isVisibilityChange is false when visible and forceOpen both true', () => {+ jest.useFakeTimers();+ const { getAllByRole, rerender } = render(+ <SubMenu title={<span>T</span>} forceOpen={false} hoverDelay={100}>+ <MenuItem>C</MenuItem>+ </SubMenu>,+ );+ openSubMenu(getAllByRole('menuitem')[0]);+ const subMenuNav = getAllByRole('menu')[0];+ setupSubMenuRect(subMenuNav);+ rerender(+ <SubMenu title={<span>T</span>} forceOpen hoverDelay={100}>+ <MenuItem>C</MenuItem>+ </SubMenu>,+ );+ act(() => jest.runAllTimers());+ expect(subMenuNav).toBeTruthy();+ jest.useRealTimers();+ });+});++// ---------------------------------------------------------------------------+// componentDidUpdate — show branch+// ---------------------------------------------------------------------------++describe('componentDidUpdate show branch', () => {+ it('adds menuVisible class after opening (LTR, no overflow)', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ const subMenuNav = getAllByRole('menu')[0];+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 800 });+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 800 });+ setupSubMenuRect(subMenuNav, { bottom: 200, right: 200 });+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());+ expect(subMenuNav.className).toContain(cssClasses.menuVisible);+ jest.useRealTimers();+ });++ it('positions with bottom/right when overflowing in LTR', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ const subMenuNav = getAllByRole('menu')[0];+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 300 });+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 300 });+ setupSubMenuRect(subMenuNav, { bottom: 500, right: 500 });+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());+ expect(subMenuNav.className).toContain(cssClasses.menuVisible);+ jest.useRealTimers();+ });++ it('adds menuVisible class for RTL with no overflow', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100, rtl: true });+ const subMenuNav = getAllByRole('menu')[0];+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 800 });+ setupSubMenuRect(subMenuNav, { bottom: 200, left: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());+ expect(subMenuNav.className).toContain(cssClasses.menuVisible);+ jest.useRealTimers();+ });++ it('adds menuVisible class for RTL with bottom overflow and left < 0', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100, rtl: true });+ const subMenuNav = getAllByRole('menu')[0];+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 300 });+ setupSubMenuRect(subMenuNav, { bottom: 500, left: -50 });+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());+ expect(subMenuNav.className).toContain(cssClasses.menuVisible);+ jest.useRealTimers();+ });++ it('shows when forceOpen becomes true', () => {+ jest.useFakeTimers();+ const { getAllByRole, rerender } = render(+ <SubMenu title={<span>T</span>} forceOpen={false}>+ <MenuItem>C</MenuItem>+ </SubMenu>,+ );+ const subMenuNav = getAllByRole('menu')[0];+ setupSubMenuRect(subMenuNav);+ rerender(+ <SubMenu title={<span>T</span>} forceOpen>+ <MenuItem>C</MenuItem>+ </SubMenu>,+ );+ act(() => jest.runAllTimers());+ expect(subMenuNav.className).toContain(cssClasses.menuVisible);+ jest.useRealTimers();+ });+});++// ---------------------------------------------------------------------------+// componentDidUpdate — hide branch+// ---------------------------------------------------------------------------++describe('componentDidUpdate hide branch', () => {+ it('removes menuVisible and resets styles on transitionend', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ const outerNav = getAllByRole('menuitem')[0];+ const subMenuNav = getAllByRole('menu')[0];+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 800 });+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 800 });+ setupSubMenuRect(subMenuNav);+ openSubMenu(outerNav);+ act(() => jest.runAllTimers());+ fireEvent.mouseLeave(outerNav);+ act(() => jest.advanceTimersByTime(100));+ act(() => fireEvent.transitionEnd(subMenuNav));+ expect(subMenuNav.style.top).toBe('0px');+ expect(subMenuNav.style.left).toBe('100%');+ jest.useRealTimers();+ });++ it('does not run update logic when isVisibilityChange is false', () => {+ const { rerender } = render(+ <SubMenu title={<span>T</span>} forceOpen={false}>+ <MenuItem>C</MenuItem>+ </SubMenu>,+ );+ expect(() =>+ rerender(+ <SubMenu title={<span>T</span>} forceOpen={false}>+ <MenuItem>C</MenuItem>+ </SubMenu>,+ ),+ ).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// handleMouseEnter+// ---------------------------------------------------------------------------++describe('handleMouseEnter', () => {+ it('opens after hoverDelay', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({ hoverDelay: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ expect(getByTestId('title').parentElement.className).toContain(cssClasses.menuItemActive);+ jest.useRealTimers();+ });++ it('does not open when disabled', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({ disabled: true, hoverDelay: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ expect(getByTestId('title').parentElement.className).not.toContain(cssClasses.menuItemActive);+ jest.useRealTimers();+ });++ it('does not open again if already visible', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ const outerNav = getAllByRole('menuitem')[0];+ openSubMenu(outerNav);+ const spy = jest.spyOn(global, 'setTimeout');+ fireEvent.mouseEnter(outerNav);+ expect(spy).not.toHaveBeenCalled();+ spy.mockRestore();+ jest.useRealTimers();+ });++ it('clears close timer on enter', () => {+ jest.useFakeTimers();+ const clearSpy = jest.spyOn(global, 'clearTimeout');+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ const outerNav = getAllByRole('menuitem')[0];+ openSubMenu(outerNav);+ fireEvent.mouseLeave(outerNav);+ fireEvent.mouseEnter(outerNav);+ expect(clearSpy).toHaveBeenCalled();+ clearSpy.mockRestore();+ jest.useRealTimers();+ });+});++// ---------------------------------------------------------------------------+// handleMouseLeave+// ---------------------------------------------------------------------------++describe('handleMouseLeave', () => {+ it('closes after hoverDelay', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({ hoverDelay: 100 });+ const outerNav = getAllByRole('menuitem')[0];+ openSubMenu(outerNav);+ fireEvent.mouseLeave(outerNav);+ act(() => jest.advanceTimersByTime(100));+ expect(getByTestId('title').parentElement.className).not.toContain(cssClasses.menuItemActive);+ jest.useRealTimers();+ });++ it('does not set close timer when not visible', () => {+ jest.useFakeTimers();+ const spy = jest.spyOn(global, 'setTimeout');+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ fireEvent.mouseLeave(getAllByRole('menuitem')[0]);+ expect(spy).not.toHaveBeenCalled();+ spy.mockRestore();+ jest.useRealTimers();+ });++ it('clears open timer on leave', () => {+ jest.useFakeTimers();+ const clearSpy = jest.spyOn(global, 'clearTimeout');+ const { getAllByRole } = renderSubMenu({ hoverDelay: 500 });+ fireEvent.mouseEnter(getAllByRole('menuitem')[0]);+ fireEvent.mouseLeave(getAllByRole('menuitem')[0]);+ expect(clearSpy).toHaveBeenCalled();+ clearSpy.mockRestore();+ jest.useRealTimers();+ });+});++// ---------------------------------------------------------------------------+// handleClick+// ---------------------------------------------------------------------------++describe('handleClick', () => {+ it('does not call onClick when disabled', () => {+ const onClick = jest.fn();+ const { getByTestId } = renderSubMenu({ disabled: true, onClick });+ fireEvent.click(getByTestId('title').parentElement);+ expect(onClick).not.toHaveBeenCalled();+ });++ it('calls callIfExists with onClick when not disabled', () => {+ const onClick = jest.fn();+ const { getByTestId } = renderSubMenu({ onClick });+ fireEvent.click(getByTestId('title').parentElement);+ expect(callIfExists).toHaveBeenCalledWith(+ onClick,+ expect.anything(),+ expect.anything(),+ store.target,+ );+ });++ it('calls hideMenu when onClick provided and not preventCloseOnClick', () => {+ const onClick = jest.fn();+ const { getByTestId } = renderSubMenu({ onClick });+ fireEvent.click(getByTestId('title').parentElement);+ expect(hideMenu).toHaveBeenCalled();+ });++ it('does not call hideMenu when onClick not provided', () => {+ // clearAllMocks in beforeEach ensures clean state+ const { getByTestId } = renderSubMenu();+ fireEvent.click(getByTestId('title').parentElement);+ expect(hideMenu).not.toHaveBeenCalled();+ });++ it('does not call hideMenu when preventCloseOnClick is true', () => {+ const onClick = jest.fn();+ const { getByTestId } = renderSubMenu({ onClick, preventCloseOnClick: true });+ fireEvent.click(getByTestId('title').parentElement);+ expect(hideMenu).not.toHaveBeenCalled();+ });++ it('merges props.data and store.data', () => {+ // Set store.data directly on the mock object+ const mockStore = require('./helpers').store;+ mockStore.data = { sk: 'sv' };++ const onClick = jest.fn();+ const { getByTestId } = renderSubMenu({ onClick, data: { ik: 'iv' } });+ fireEvent.click(getByTestId('title').parentElement);++ // callIfExists is called once in this test (mocks cleared in beforeEach)+ const arg = callIfExists.mock.calls[0][2];+ expect(arg.sk).toBe('sv');+ expect(arg.ik).toBe('iv');+ mockStore.data = {};+ });++ it('passes store.target as third arg', () => {+ const mockStore = require('./helpers').store;+ const t = document.createElement('div');+ mockStore.target = t;++ const onClick = jest.fn();+ const { getByTestId } = renderSubMenu({ onClick });+ fireEvent.click(getByTestId('title').parentElement);++ expect(callIfExists.mock.calls[0][3]).toBe(t);+ mockStore.target = null;+ });+});++// ---------------------------------------------------------------------------+// hideSubMenu+// ---------------------------------------------------------------------------++describe('hideSubMenu', () => {+ it('hides the menu', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({ hoverDelay: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => getHideHandler()({ detail: null }));+ expect(getByTestId('title').parentElement.className).not.toContain(cssClasses.menuItemActive);+ jest.useRealTimers();+ });++ it('calls forceClose when forceOpen is true', () => {+ const forceClose = jest.fn();+ renderSubMenu({ forceOpen: true, forceClose });+ act(() => getHideHandler()({ detail: null }));+ expect(forceClose).toHaveBeenCalled();+ });++ it('does not hide when detail.id does not match menu id', () => {+ jest.useFakeTimers();+ const { getAllByRole, getByTestId } = renderSubMenu({ hoverDelay: 100 });+ const subMenuNav = getAllByRole('menu')[0];+ setupSubMenuRect(subMenuNav);+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());+ act(() => getHideHandler()({ detail: { id: 'other' } }));+ expect(getByTestId('title').parentElement.className).toContain(cssClasses.menuItemActive);+ jest.useRealTimers();+ });++ it('does not throw with empty detail', () => {+ renderSubMenu();+ expect(() => act(() => getHideHandler()({ detail: null }))).not.toThrow();+ });++ it('does not throw with detail but no id', () => {+ renderSubMenu();+ expect(() => act(() => getHideHandler()({ detail: {} }))).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// registerHandlers / unregisterHandlers+// ---------------------------------------------------------------------------++describe('registerHandlers / unregisterHandlers', () => {+ it('swaps keydown handlers on register', () => {+ jest.useFakeTimers();+ const removeSpy = jest.spyOn(document, 'removeEventListener');+ const addSpy = jest.spyOn(document, 'addEventListener');+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());+ expect(removeSpy).toHaveBeenCalledWith('keydown', expect.any(Function));+ expect(addSpy).toHaveBeenCalledWith('keydown', expect.any(Function));+ removeSpy.mockRestore();+ addSpy.mockRestore();+ jest.useRealTimers();+ });++ it('restores keydown handler on close via transitionend (not dismounting)', () => {+ jest.useFakeTimers();+ const { getAllByRole } = renderSubMenu({ hoverDelay: 100 });+ const outerNav = getAllByRole('menuitem')[0];+ const subMenuNav = getAllByRole('menu')[0];+ Object.defineProperty(window, 'innerHeight', { writable: true, value: 800 });+ Object.defineProperty(window, 'innerWidth', { writable: true, value: 800 });+ setupSubMenuRect(subMenuNav);++ openSubMenu(outerNav);+ act(() => jest.runAllTimers());++ // Close the submenu+ fireEvent.mouseLeave(outerNav);+ act(() => jest.advanceTimersByTime(100));++ // Spy AFTER close timer fires but BEFORE transitionend+ const addSpy = jest.spyOn(document, 'addEventListener');++ // transitionend triggers cleanup which calls unregisterHandlers(false)+ act(() => fireEvent.transitionEnd(subMenuNav));++ expect(addSpy).toHaveBeenCalledWith('keydown', expect.any(Function));+ addSpy.mockRestore();+ jest.useRealTimers();+ });++ it('does not restore keydown handler when dismounting', () => {+ jest.useFakeTimers();+ const { getAllByRole, unmount } = renderSubMenu({ hoverDelay: 100 });+ const subMenuNav = getAllByRole('menu')[0];+ setupSubMenuRect(subMenuNav);+ openSubMenu(getAllByRole('menuitem')[0]);+ act(() => jest.runAllTimers());++ // Spy before unmount+ const addSpy = jest.spyOn(document, 'addEventListener');+ unmount();++ // unregisterHandlers(true) must NOT re-add keydown+ expect(addSpy.mock.calls.filter(([e]) => e === 'keydown').length).toBe(0);+ addSpy.mockRestore();+ jest.useRealTimers();+ });});diff --git a/web/js/util/context-menu/actions.test.js b/web/js/util/context-menu/actions.test.jsindex f5b3a6e69..ef09e797f 100644--- a/web/js/util/context-menu/actions.test.js+++ b/web/js/util/context-menu/actions.test.js@@ -1,3 +1,224 @@-test('actions util test', () => {+import {+ dispatchGlobalEvent,+ showMenu,+ hideMenu,+ MENU_SHOW,+ MENU_HIDE,+} from './actions';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./helpers', () => ({+ store: {},+}));++// ---------------------------------------------------------------------------+// Constants+// ---------------------------------------------------------------------------++describe('constants', () => {+ it('MENU_SHOW has the correct value', () => {+ expect(MENU_SHOW).toBe('REACT_CONTEXTMENU_SHOW');+ });++ it('MENU_HIDE has the correct value', () => {+ expect(MENU_HIDE).toBe('REACT_CONTEXTMENU_HIDE');+ });+});++// ---------------------------------------------------------------------------+// dispatchGlobalEvent+// ---------------------------------------------------------------------------++describe('dispatchGlobalEvent()', () => {+ let dispatchSpy;++ beforeEach(() => {+ dispatchSpy = jest.spyOn(window, 'dispatchEvent');+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('dispatches an event on the default window target', () => {+ dispatchGlobalEvent('TEST_EVENT', { foo: 'bar' });+ expect(dispatchSpy).toHaveBeenCalledTimes(1);+ });++ it('dispatches an event with the correct event name', () => {+ dispatchGlobalEvent('MY_EVENT', {});+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.type).toBe('MY_EVENT');+ });++ it('passes opts as event detail', () => {+ const opts = { id: 'menu-1', x: 100, y: 200 };+ dispatchGlobalEvent('TEST_EVENT', opts);+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.detail).toEqual(opts);+ });++ it('dispatches on a custom target when provided', () => {+ const customTarget = document.createElement('div');+ const customDispatchSpy = jest.spyOn(customTarget, 'dispatchEvent');++ dispatchGlobalEvent('TEST_EVENT', { foo: 'bar' }, customTarget);++ expect(customDispatchSpy).toHaveBeenCalledTimes(1);+ expect(dispatchSpy).not.toHaveBeenCalled();+ });++ it('does not dispatch when target is null', () => {+ dispatchGlobalEvent('TEST_EVENT', { foo: 'bar' }, null);+ expect(dispatchSpy).not.toHaveBeenCalled();+ });++ it('merges opts into the store after dispatch', async () => {+ const { store } = await import('./helpers');+ const opts = { position: { x: 50, y: 75 } };++ dispatchGlobalEvent('TEST_EVENT', opts);++ expect(store).toMatchObject(opts);+ });++ it('does not update store when target is null', async () => {+ const { store } = await import('./helpers');+ // Reset store+ Object.keys(store).forEach((k) => delete store[k]);++ dispatchGlobalEvent('TEST_EVENT', { shouldNotAppear: true }, null);++ expect(store.shouldNotAppear).toBeUndefined();+ });++ it('uses document.createEvent when CustomEvent is not a function', () => {+ const originalCustomEvent = window.CustomEvent;+ // Simulate IE where CustomEvent is not a constructor function+ window.CustomEvent = undefined;++ const createEventSpy = jest.spyOn(document, 'createEvent');++ dispatchGlobalEvent('TEST_EVENT', { foo: 'bar' });++ expect(createEventSpy).toHaveBeenCalledWith('CustomEvent');++ window.CustomEvent = originalCustomEvent;+ createEventSpy.mockRestore();+ });+});++// ---------------------------------------------------------------------------+// showMenu+// ---------------------------------------------------------------------------++describe('showMenu()', () => {+ let dispatchSpy;++ beforeEach(() => {+ dispatchSpy = jest.spyOn(window, 'dispatchEvent');+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('dispatches a MENU_SHOW event', () => {+ showMenu();+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.type).toBe(MENU_SHOW);+ });++ it('includes type MENU_SHOW in the event detail', () => {+ showMenu({ id: 'my-menu' });+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.detail.type).toBe(MENU_SHOW);+ });++ it('merges provided opts into the event detail', () => {+ showMenu({ id: 'my-menu', x: 10 });+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.detail.id).toBe('my-menu');+ expect(dispatched.detail.x).toBe(10);+ });++ it('works with no arguments', () => {+ expect(() => showMenu()).not.toThrow();+ });++ it('dispatches on a custom target when provided', () => {+ const customTarget = document.createElement('div');+ const customDispatchSpy = jest.spyOn(customTarget, 'dispatchEvent');++ showMenu({}, customTarget);++ expect(customDispatchSpy).toHaveBeenCalledTimes(1);+ expect(dispatchSpy).not.toHaveBeenCalled();+ });++ it('does not mutate the original opts object', () => {+ const opts = { id: 'menu-1' };+ const original = { ...opts };+ showMenu(opts);+ expect(opts).toEqual(original);+ });+});++// ---------------------------------------------------------------------------+// hideMenu+// ---------------------------------------------------------------------------++describe('hideMenu()', () => {+ let dispatchSpy;++ beforeEach(() => {+ dispatchSpy = jest.spyOn(window, 'dispatchEvent');+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('dispatches a MENU_HIDE event', () => {+ hideMenu();+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.type).toBe(MENU_HIDE);+ });++ it('includes type MENU_HIDE in the event detail', () => {+ hideMenu({ id: 'my-menu' });+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.detail.type).toBe(MENU_HIDE);+ });++ it('merges provided opts into the event detail', () => {+ hideMenu({ id: 'my-menu', reason: 'blur' });+ const dispatched = dispatchSpy.mock.calls[0][0];+ expect(dispatched.detail.id).toBe('my-menu');+ expect(dispatched.detail.reason).toBe('blur');+ });++ it('works with no arguments', () => {+ expect(() => hideMenu()).not.toThrow();+ });++ it('dispatches on a custom target when provided', () => {+ const customTarget = document.createElement('div');+ const customDispatchSpy = jest.spyOn(customTarget, 'dispatchEvent');++ hideMenu({}, customTarget);++ expect(customDispatchSpy).toHaveBeenCalledTimes(1);+ expect(dispatchSpy).not.toHaveBeenCalled();+ });++ it('does not mutate the original opts object', () => {+ const opts = { id: 'menu-1' };+ const original = { ...opts };+ hideMenu(opts);+ expect(opts).toEqual(original);+ });});diff --git a/web/js/util/context-menu/connectMenu.test.js b/web/js/util/context-menu/connectMenu.test.jsindex e1dfa48f3..d80b45af4 100644--- a/web/js/util/context-menu/connectMenu.test.js+++ b/web/js/util/context-menu/connectMenu.test.js@@ -1,3 +1,272 @@-test('connectMenu util test', () => {+/* eslint-disable react/prop-types */+import { render, act } from '@testing-library/react';+import connectMenu from './connectMenu';+import listener from './globalEventListener';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./globalEventListener', () => ({+ register: jest.fn(() => 'mock-listen-id'),+ unregister: jest.fn(),+}));++jest.mock('./ContextMenuTrigger', () => ({+ propTypes: {+ id: () => {},+ children: () => {},+ collect: () => {},+ },+}));++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const MENU_ID = 'test-menu';++// Simple child component that exposes its props via data-testid attributes+function ChildMenu({ id, trigger }) {+ return (+ <div data-testid="child">+ <span data-testid="id">{id}</span>+ <span data-testid="trigger">{trigger ? JSON.stringify(trigger) : 'null'}</span>+ </div>+ );+}++function createConnectedMenu(menuId = MENU_ID) {+ const Connected = connectMenu(menuId)(ChildMenu);+ return Connected;+}++// ---------------------------------------------------------------------------+// Factory / HOC structure+// ---------------------------------------------------------------------------++describe('connectMenu factory', () => {+ it('returns a function (connect) when called with a menuId', () => {+ const connect = connectMenu(MENU_ID);+ expect(typeof connect).toBe('function');+ });++ it('renders the Child component', () => {+ const Connected = createConnectedMenu();+ const { getByTestId } = render(<Connected />);+ expect(getByTestId('child')).toBeTruthy();+ });++ it('forwards menuId as the id prop to Child', () => {+ const Connected = createConnectedMenu();+ const { getByTestId } = render(<Connected />);+ expect(getByTestId('id').textContent).toBe(MENU_ID);+ });++ it('forwards additional props to Child', () => {+ function ChildWithExtra({ extra }) {+ return <div data-testid="extra">{extra}</div>;+ }+ const ConnectedExtra = connectMenu(MENU_ID)(ChildWithExtra);+ const { getByTestId } = render(<ConnectedExtra extra="hello" />);+ expect(getByTestId('extra').textContent).toBe('hello');+ });++ it('initialises trigger state as null', () => {+ const Connected = createConnectedMenu();+ const { getByTestId } = render(<Connected />);+ expect(getByTestId('trigger').textContent).toBe('null');+ });+});++// ---------------------------------------------------------------------------+// Lifecycle — listener registration+// ---------------------------------------------------------------------------++describe('ConnectMenu lifecycle', () => {+ beforeEach(() => jest.clearAllMocks());++ it('registers with the global listener on mount', () => {+ const Connected = createConnectedMenu();+ render(<Connected />);+ expect(listener.register).toHaveBeenCalledTimes(1);+ });++ it('passes handleShow and handleHide to listener.register', () => {+ const Connected = createConnectedMenu();+ render(<Connected />);+ const [showArg, hideArg] = listener.register.mock.calls[0];+ expect(typeof showArg).toBe('function');+ expect(typeof hideArg).toBe('function');+ });++ it('unregisters the listener on unmount', () => {+ const Connected = createConnectedMenu();+ const { unmount } = render(<Connected />);+ unmount();+ expect(listener.unregister).toHaveBeenCalledWith('mock-listen-id');+ });++ it('does not call unregister if listenId was never set', () => {+ listener.register.mockReturnValueOnce(null);+ const Connected = createConnectedMenu();+ const { unmount } = render(<Connected />);+ unmount();+ expect(listener.unregister).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------+// handleShow+// ---------------------------------------------------------------------------++describe('handleShow()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('updates trigger state when event id matches menuId', () => {+ const Connected = createConnectedMenu(MENU_ID);+ const { getByTestId } = render(<Connected />);++ const [handleShow] = listener.register.mock.calls[0];++ act(() => {+ handleShow({+ detail: {+ id: MENU_ID,+ data: { customProp: 'value' },+ },+ });+ });++ const trigger = JSON.parse(getByTestId('trigger').textContent);+ expect(trigger.customProp).toBe('value');+ });++ it('does not update state when event id does not match menuId', () => {+ const Connected = createConnectedMenu(MENU_ID);+ const { getByTestId } = render(<Connected />);++ const [handleShow] = listener.register.mock.calls[0];++ act(() => {+ handleShow({+ detail: {+ id: 'different-menu',+ data: { customProp: 'value' },+ },+ });+ });++ expect(getByTestId('trigger').textContent).toBe('null');+ });++ it('filters out ContextMenuTrigger propTypes keys from trigger data', () => {+ const Connected = createConnectedMenu(MENU_ID);+ const { getByTestId } = render(<Connected />);++ const [handleShow] = listener.register.mock.calls[0];++ act(() => {+ handleShow({+ detail: {+ id: MENU_ID,+ data: {+ // 'id' and 'collect' are in ContextMenuTrigger.propTypes → should be filtered+ id: 'should-be-removed',+ collect: 'should-be-removed',+ // custom prop → should be kept+ myCustomData: 'keep-me',+ },+ },+ });+ });++ const trigger = JSON.parse(getByTestId('trigger').textContent);+ expect(trigger.myCustomData).toBe('keep-me');+ expect(trigger.id).toBeUndefined();+ expect(trigger.collect).toBeUndefined();+ });++ it('filters out children key from trigger data', () => {+ const Connected = createConnectedMenu(MENU_ID);+ const { getByTestId } = render(<Connected />);++ const [handleShow] = listener.register.mock.calls[0];++ act(() => {+ handleShow({+ detail: {+ id: MENU_ID,+ data: {+ children: 'should-be-removed',+ myData: 'keep-me',+ },+ },+ });+ });++ const trigger = JSON.parse(getByTestId('trigger').textContent);+ expect(trigger.children).toBeUndefined();+ expect(trigger.myData).toBe('keep-me');+ });++ it('sets trigger to empty object when all data keys are filtered', () => {+ const Connected = createConnectedMenu(MENU_ID);+ const { getByTestId } = render(<Connected />);++ const [handleShow] = listener.register.mock.calls[0];++ act(() => {+ handleShow({+ detail: {+ id: MENU_ID,+ // only ignored keys+ data: { id: 'x', children: 'y', collect: 'z' },+ },+ });+ });++ const trigger = JSON.parse(getByTestId('trigger').textContent);+ expect(trigger).toEqual({});+ });+});++// ---------------------------------------------------------------------------+// handleHide+// ---------------------------------------------------------------------------++describe('handleHide()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('resets trigger state to null', () => {+ const Connected = createConnectedMenu(MENU_ID);+ const { getByTestId } = render(<Connected />);++ const [handleShow, handleHide] = listener.register.mock.calls[0];++ // First show the menu+ act(() => {+ handleShow({+ detail: { id: MENU_ID, data: { myProp: 'hello' } },+ });+ });++ expect(getByTestId('trigger').textContent).not.toBe('null');++ // Then hide it+ act(() => {+ handleHide();+ });++ expect(getByTestId('trigger').textContent).toBe('null');+ });++ it('does not throw when called before handleShow', () => {+ const Connected = createConnectedMenu(MENU_ID);+ render(<Connected />);++ const [, handleHide] = listener.register.mock.calls[0];++ expect(() => act(() => handleHide())).not.toThrow();+ });});diff --git a/web/js/util/context-menu/globalEventListener.test.js b/web/js/util/context-menu/globalEventListener.test.jsindex d03c894f0..5180e4283 100644--- a/web/js/util/context-menu/globalEventListener.test.js+++ b/web/js/util/context-menu/globalEventListener.test.js@@ -1,3 +1,272 @@-test('globalEventListener util test', () => {+import { MENU_SHOW, MENU_HIDE } from './actions';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('./actions', () => ({+ MENU_SHOW: 'REACT_CONTEXTMENU_SHOW',+ MENU_HIDE: 'REACT_CONTEXTMENU_HIDE',+}));++jest.mock('./helpers', () => ({+ uniqueId: jest.fn(),+ hasOwnProp: jest.fn((obj, key) =>+ Object.prototype.hasOwnProperty.call(obj, key),+ ),+ canUseDOM: true,+}));++// ---------------------------------------------------------------------------+// Helper — fresh singleton + fresh uniqueId mock per test+// ---------------------------------------------------------------------------++function getFreshListener() {+ let listener;+ let helpers;+ jest.isolateModules(() => {+ helpers = require('./helpers');+ listener = require('./globalEventListener').default;+ });+ return { listener, helpers };+}++// ---------------------------------------------------------------------------+// Construction / DOM listener registration+// ---------------------------------------------------------------------------++describe('GlobalEventListener construction', () => {+ beforeEach(() => jest.clearAllMocks());++ it('registers MENU_SHOW and MENU_HIDE on window when canUseDOM is true', () => {+ const addSpy = jest.spyOn(window, 'addEventListener');+ getFreshListener();+ const eventNames = addSpy.mock.calls.map(([name]) => name);+ expect(eventNames).toContain(MENU_SHOW);+ expect(eventNames).toContain(MENU_HIDE);+ addSpy.mockRestore();+ });++ it('does NOT register window listeners when canUseDOM is false', () => {+ jest.resetModules();+ jest.doMock('./helpers', () => ({+ uniqueId: jest.fn(),+ hasOwnProp: jest.fn((obj, key) =>+ Object.prototype.hasOwnProperty.call(obj, key),+ ),+ canUseDOM: false,+ }));++ const addSpy = jest.spyOn(window, 'addEventListener');+ jest.isolateModules(() => {+ require('./globalEventListener');+ });++ const eventNames = addSpy.mock.calls.map(([name]) => name);+ expect(eventNames).not.toContain(MENU_SHOW);+ expect(eventNames).not.toContain(MENU_HIDE);+ addSpy.mockRestore();++ jest.doMock('./helpers', () => ({+ uniqueId: jest.fn(),+ hasOwnProp: jest.fn((obj, key) =>+ Object.prototype.hasOwnProperty.call(obj, key),+ ),+ canUseDOM: true,+ }));+ jest.resetModules();+ });++ it('initialises with an empty callbacks object', () => {+ const { listener } = getFreshListener();+ expect(listener.callbacks).toEqual({});+ });+});++// ---------------------------------------------------------------------------+// register()+// ---------------------------------------------------------------------------++describe('register()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('returns the generated unique id', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ const id = listener.register(jest.fn(), jest.fn());+ expect(id).toBe('id-1');+ });++ it('stores show and hide callbacks under the returned id', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ const show = jest.fn();+ const hide = jest.fn();+ const id = listener.register(show, hide);+ expect(listener.callbacks[id].show).toBe(show);+ expect(listener.callbacks[id].hide).toBe(hide);+ });++ it('stores multiple registrations independently', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId+ .mockReturnValueOnce('id-1')+ .mockReturnValueOnce('id-2');++ const show1 = jest.fn();+ const show2 = jest.fn();+ listener.register(show1, jest.fn());+ listener.register(show2, jest.fn());++ expect(Object.keys(listener.callbacks)).toHaveLength(2);+ expect(listener.callbacks['id-1'].show).toBe(show1);+ expect(listener.callbacks['id-2'].show).toBe(show2);+ });+});++// ---------------------------------------------------------------------------+// unregister()+// ---------------------------------------------------------------------------++describe('unregister()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('removes the callback entry for the given id', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ const id = listener.register(jest.fn(), jest.fn());+ listener.unregister(id);+ expect(listener.callbacks[id]).toBeUndefined();+ });++ it('does nothing when id is null', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ listener.register(jest.fn(), jest.fn());+ expect(() => listener.unregister(null)).not.toThrow();+ expect(Object.keys(listener.callbacks)).toHaveLength(1);+ });++ it('does nothing when id is undefined', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ listener.register(jest.fn(), jest.fn());+ expect(() => listener.unregister(undefined)).not.toThrow();+ expect(Object.keys(listener.callbacks)).toHaveLength(1);+ });++ it('does nothing when id does not exist in callbacks', () => {+ const { listener } = getFreshListener();+ expect(() => listener.unregister('non-existent-id')).not.toThrow();+ });++ it('only removes the specified registration', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId+ .mockReturnValueOnce('id-1')+ .mockReturnValueOnce('id-2');++ listener.register(jest.fn(), jest.fn());+ listener.register(jest.fn(), jest.fn());+ listener.unregister('id-1');++ expect(listener.callbacks['id-1']).toBeUndefined();+ expect(listener.callbacks['id-2']).toBeDefined();+ });+});++// ---------------------------------------------------------------------------+// handleShowEvent()+// ---------------------------------------------------------------------------++describe('handleShowEvent()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls the show callback of every registered listener', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId+ .mockReturnValueOnce('id-1')+ .mockReturnValueOnce('id-2');++ const show1 = jest.fn();+ const show2 = jest.fn();+ listener.register(show1, jest.fn());+ listener.register(show2, jest.fn());++ const event = { detail: {} };+ listener.handleShowEvent(event);++ expect(show1).toHaveBeenCalledWith(event);+ expect(show2).toHaveBeenCalledWith(event);+ });++ it('does not call hide callbacks on a show event', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ const hide = jest.fn();+ listener.register(jest.fn(), hide);++ listener.handleShowEvent({ detail: {} });++ expect(hide).not.toHaveBeenCalled();+ });++ it('does not throw when there are no registered callbacks', () => {+ const { listener } = getFreshListener();+ expect(() => listener.handleShowEvent({ detail: {} })).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// handleHideEvent()+// ---------------------------------------------------------------------------++describe('handleHideEvent()', () => {+ beforeEach(() => jest.clearAllMocks());++ it('calls the hide callback of every registered listener', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId+ .mockReturnValueOnce('id-1')+ .mockReturnValueOnce('id-2');++ const hide1 = jest.fn();+ const hide2 = jest.fn();+ listener.register(jest.fn(), hide1);+ listener.register(jest.fn(), hide2);++ const event = { detail: {} };+ listener.handleHideEvent(event);++ expect(hide1).toHaveBeenCalledWith(event);+ expect(hide2).toHaveBeenCalledWith(event);+ });++ it('does not call show callbacks on a hide event', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ const show = jest.fn();+ listener.register(show, jest.fn());++ listener.handleHideEvent({ detail: {} });++ expect(show).not.toHaveBeenCalled();+ });++ it('does not call callbacks that have been unregistered', () => {+ const { listener, helpers } = getFreshListener();+ helpers.uniqueId.mockReturnValue('id-1');+ const hide = jest.fn();+ const id = listener.register(jest.fn(), hide);+ listener.unregister(id);++ listener.handleHideEvent({ detail: {} });++ expect(hide).not.toHaveBeenCalled();+ });++ it('does not throw when there are no registered callbacks', () => {+ const { listener } = getFreshListener();+ expect(() => listener.handleHideEvent({ detail: {} })).not.toThrow();+ });});diff --git a/web/js/util/context-menu/helpers.test.js b/web/js/util/context-menu/helpers.test.jsindex 37030d746..f068658d6 100644--- a/web/js/util/context-menu/helpers.test.js+++ b/web/js/util/context-menu/helpers.test.js@@ -1,3 +1,203 @@-test('helpers util test', () => {+import {+ callIfExists,+ hasOwnProp,+ uniqueId,+ cssClasses,+ store,+ canUseDOM,+} from './helpers'; // Update path as needed+// ---------------------------------------------------------------------------+// callIfExists+// ---------------------------------------------------------------------------++describe('callIfExists()', () => {+ it('calls the function when it is a function', () => {+ const fn = jest.fn();+ callIfExists(fn);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('passes all additional arguments to the function', () => {+ const fn = jest.fn();+ callIfExists(fn, 'a', 'b', 'c');+ expect(fn).toHaveBeenCalledWith('a', 'b', 'c');+ });++ it('returns the result of the function call', () => {+ const fn = jest.fn(() => 42);+ const result = callIfExists(fn);+ expect(result).toBe(42);+ });++ it('returns false when func is not a function', () => {+ expect(callIfExists(null)).toBe(false);+ expect(callIfExists(undefined)).toBe(false);+ expect(callIfExists(42)).toBe(false);+ expect(callIfExists('string')).toBe(false);+ expect(callIfExists({})).toBe(false);+ });++ it('does not throw when func is null', () => {+ expect(() => callIfExists(null)).not.toThrow();+ });++ it('does not throw when func is undefined', () => {+ expect(() => callIfExists(undefined)).not.toThrow();+ });++ it('handles functions that return falsy values', () => {+ expect(callIfExists(() => 0)).toBe(0);+ expect(callIfExists(() => '')).toBe('');+ expect(callIfExists(() => null)).toBe(null);+ expect(callIfExists(() => false)).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// hasOwnProp+// ---------------------------------------------------------------------------++describe('hasOwnProp()', () => {+ it('returns true for a direct own property', () => {+ const obj = { key: 'value' };+ expect(hasOwnProp(obj, 'key')).toBe(true);+ });++ it('returns false for an inherited property', () => {+ const parent = { inherited: true };+ const child = Object.create(parent);+ expect(hasOwnProp(child, 'inherited')).toBe(false);+ });++ it('returns false for a property that does not exist', () => {+ expect(hasOwnProp({}, 'missing')).toBe(false);+ });++ it('returns true for a property with an undefined value', () => {+ const obj = { key: undefined };+ expect(hasOwnProp(obj, 'key')).toBe(true);+ });++ it('returns true for a property with a falsy value', () => {+ const obj = { key: null };+ expect(hasOwnProp(obj, 'key')).toBe(true);+ });++ it('works correctly with objects that have a custom hasOwnProperty', () => {+ const obj = { hasOwnProperty: () => false, realProp: true };+ // Uses Object.prototype.hasOwnProperty so custom override is ignored+ expect(hasOwnProp(obj, 'realProp')).toBe(true);+ });+});++// ---------------------------------------------------------------------------+// uniqueId+// ---------------------------------------------------------------------------++describe('uniqueId()', () => {+ it('returns a string', () => {+ expect(typeof uniqueId()).toBe('string');+ });++ it('returns a non-empty string', () => {+ expect(uniqueId().length).toBeGreaterThan(0);+ });++ it('returns different values on successive calls', () => {+ const ids = new Set(Array.from({ length: 100 }, () => uniqueId()));+ // Allow for a tiny collision probability — at least 95 unique out of 100+ expect(ids.size).toBeGreaterThan(95);+ });++ it('returns a string derived from base-36', () => {+ const id = uniqueId();+ // base-36 characters: 0-9 and a-z+ expect(id).toMatch(/^[0-9a-z]+$/);+ });+});++// ---------------------------------------------------------------------------+// cssClasses+// ---------------------------------------------------------------------------++describe('cssClasses', () => {+ it('is an object', () => {+ expect(typeof cssClasses).toBe('object');+ });++ it('has the correct menu class', () => {+ expect(cssClasses.menu).toBe('react-contextmenu');+ });++ it('has the correct menuVisible class', () => {+ expect(cssClasses.menuVisible).toBe('react-contextmenu--visible');+ });++ it('has the correct menuWrapper class', () => {+ expect(cssClasses.menuWrapper).toBe('react-contextmenu-wrapper');+ });++ it('has the correct menuItem class', () => {+ expect(cssClasses.menuItem).toBe('react-contextmenu-item');+ });++ it('has the correct menuItemActive class', () => {+ expect(cssClasses.menuItemActive).toBe('react-contextmenu-item--active');+ });++ it('has the correct menuItemDisabled class', () => {+ expect(cssClasses.menuItemDisabled).toBe('react-contextmenu-item--disabled');+ });++ it('has the correct menuItemDivider class', () => {+ expect(cssClasses.menuItemDivider).toBe('react-contextmenu-item--divider');+ });++ it('has the correct menuItemSelected class', () => {+ expect(cssClasses.menuItemSelected).toBe('react-contextmenu-item--selected');+ });++ it('has the correct subMenu class', () => {+ expect(cssClasses.subMenu).toBe('react-contextmenu-submenu');+ });++ it('has exactly 9 class entries', () => {+ expect(Object.keys(cssClasses)).toHaveLength(9);+ });+});++// ---------------------------------------------------------------------------+// store+// ---------------------------------------------------------------------------++describe('store', () => {+ it('is an object', () => {+ expect(typeof store).toBe('object');+ });++ it('is initially empty', () => {+ expect(store).toEqual({});+ });++ it('can have properties assigned to it', () => {+ store.testKey = 'testValue';+ expect(store.testKey).toBe('testValue');+ delete store.testKey;+ });+});++// ---------------------------------------------------------------------------+// canUseDOM+// ---------------------------------------------------------------------------++describe('canUseDOM', () => {+ it('is a boolean', () => {+ expect(typeof canUseDOM).toBe('boolean');+ });++ it('is true in a jsdom environment (window and document are available)', () => {+ // Jest runs in jsdom by default, so window and document.createElement exist+ expect(canUseDOM).toBe(true);+ });});