Interactive interface for browsing global, full-resolution satellite imagery
Checking in more unit tests
Jason Hurley477e189e4632
diff --git a/web/js/components/util/button.test.js b/web/js/components/util/button.test.jsindex 5380b5858..32fa8b61a 100644--- a/web/js/components/util/button.test.js+++ b/web/js/components/util/button.test.js@@ -130,7 +130,6 @@ describe('Button', () => {const btn = screen.getByRole('button');const stopPropagation = jest.fn();fireEvent.mouseDown(btn, { stopPropagation });- // stopPropagation is synthetic — verify the button still exists and no error thrownexpect(btn).toBeInTheDocument();});});diff --git a/web/js/components/util/checkbox.test.js b/web/js/components/util/checkbox.test.jsindex d6b933464..a54d3d302 100644--- a/web/js/components/util/checkbox.test.js+++ b/web/js/components/util/checkbox.test.js@@ -1,3 +1,226 @@-test('checkbox component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import Checkbox from './checkbox';+jest.mock('@edsc/earthdata-react-icons/horizon-design-system/hds/ui', () => ({+ Check: ({ className, size }) => (+ <span data-testid="check-icon" className={className} data-size={size} />+ ),+}));++jest.mock('./hover-tooltip', () => function HoverTooltip({ target, labelText, placement }) {+ return (+ <div+ data-testid="hover-tooltip"+ data-target={target}+ data-label={labelText}+ data-placement={placement}+ />+ );+});++const defaultProps = {+ id: 'test-cb',+ checked: false,+ onCheck: jest.fn(),+};++const renderComponent = (props = {}) => render(+ <Checkbox {...defaultProps} {...props} />,+);++describe('Checkbox', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe('input element', () => {+ it('renders a checkbox input', () => {+ renderComponent();+ expect(screen.getByRole('checkbox')).toBeInTheDocument();+ });++ it('has type="checkbox"', () => {+ renderComponent();+ expect(screen.getByRole('checkbox')).toHaveAttribute('type', 'checkbox');+ });++ it('sets id on the input', () => {+ renderComponent({ id: 'my-cb' });+ expect(screen.getByRole('checkbox')).toHaveAttribute('id', 'my-cb');+ });++ it('sets name on the input', () => {+ renderComponent({ name: 'my-name' });+ expect(screen.getByRole('checkbox')).toHaveAttribute('name', 'my-name');+ });++ it('reflects checked=true', () => {+ renderComponent({ checked: true });+ expect(screen.getByRole('checkbox')).toBeChecked();+ });++ it('reflects checked=false', () => {+ renderComponent({ checked: false });+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ });++ it('applies classNames prop to input', () => {+ renderComponent({ classNames: 'extra-class' });+ expect(screen.getByRole('checkbox')).toHaveClass('extra-class');+ });+ });++ describe('wrapper div', () => {+ it('renders wrapper div with id "{id}-case"', () => {+ renderComponent({ id: 'cb1' });+ expect(document.getElementById('cb1-case')).toBeInTheDocument();+ });++ it('includes "wv-checkbox" in wrapper className', () => {+ renderComponent();+ expect(document.getElementById('test-cb-case')).toHaveClass('wv-checkbox');+ });++ it('adds "wv-checkbox-round" when isRound is true', () => {+ renderComponent({ isRound: true });+ expect(document.getElementById('test-cb-case').className).toContain('wv-checkbox-round');+ });++ it('omits "wv-checkbox-round" when isRound is false', () => {+ renderComponent({ isRound: false });+ expect(document.getElementById('test-cb-case').className).not.toContain('wv-checkbox-round');+ });++ it('adds "checked" class when checked is true', () => {+ renderComponent({ checked: true });+ expect(document.getElementById('test-cb-case').className).toContain('checked');+ });++ it('omits "checked" class when checked is false', () => {+ renderComponent({ checked: false });+ expect(document.getElementById('test-cb-case').className).not.toContain('checked');+ });++ it('adds "disabled" class when disabled is true', () => {+ renderComponent({ disabled: true });+ expect(document.getElementById('test-cb-case').className).toContain('disabled');+ });++ it('omits "disabled" class when disabled is false', () => {+ renderComponent({ disabled: false });+ expect(document.getElementById('test-cb-case').className).not.toContain('disabled');+ });++ it('includes color in wrapper className', () => {+ renderComponent({ color: 'blue' });+ expect(document.getElementById('test-cb-case').className).toContain('blue');+ });+ });++ describe('label', () => {+ it('renders a label pointing to the input id', () => {+ renderComponent({ id: 'cb-x', label: 'My Label' });+ const lbl = screen.getByText('My Label').closest('label');+ expect(lbl).toHaveAttribute('for', 'cb-x');+ });++ it('renders label text inside a span', () => {+ renderComponent({ label: 'Hello' });+ expect(screen.getByText('Hello').tagName).toBe('SPAN');+ });+ });++ describe('children', () => {+ it('renders children inside the wrapper', () => {+ renderComponent({ children: <span data-testid="child-node">child</span> });+ expect(screen.getByTestId('child-node')).toBeInTheDocument();+ });+ });++ describe('Check icon', () => {+ it('renders the Check icon when checked is true', () => {+ renderComponent({ checked: true });+ expect(screen.getByTestId('check-icon')).toBeInTheDocument();+ });++ it('does not render the Check icon when checked is false', () => {+ renderComponent({ checked: false });+ expect(screen.queryByTestId('check-icon')).not.toBeInTheDocument();+ });++ it('Check icon has class "check"', () => {+ renderComponent({ checked: true });+ expect(screen.getByTestId('check-icon')).toHaveClass('check');+ });+ });++ describe('onCheck handler', () => {+ it('calls onCheck when the checkbox changes', () => {+ const onCheck = jest.fn();+ renderComponent({ onCheck, disabled: false });+ fireEvent.click(screen.getByRole('checkbox'));+ expect(onCheck).toHaveBeenCalledTimes(1);+ });+ });++ describe('disabled tooltip behaviour', () => {+ it('does not render HoverTooltip when disabled is false', () => {+ renderComponent({ disabled: false, title: 'tip' });+ expect(screen.queryByTestId('hover-tooltip')).not.toBeInTheDocument();+ });++ it('does not render HoverTooltip when disabled but id is missing', () => {+ renderComponent({ disabled: true, title: 'tip', id: undefined });+ expect(screen.queryByTestId('hover-tooltip')).not.toBeInTheDocument();+ });++ it('does not render HoverTooltip when disabled and id present but title is missing', () => {+ renderComponent({ disabled: true, title: undefined });+ expect(screen.queryByTestId('hover-tooltip')).not.toBeInTheDocument();+ });++ it('renders HoverTooltip when disabled, id, and title are all set', () => {+ renderComponent({ disabled: true, id: 'cb2', title: 'my tip' });+ expect(screen.getByTestId('hover-tooltip')).toBeInTheDocument();+ });++ it('passes target="#<id>-case" to HoverTooltip', () => {+ renderComponent({ disabled: true, id: 'cb3', title: 'tip' });+ expect(screen.getByTestId('hover-tooltip')).toHaveAttribute('data-target', '#cb3-case');+ });++ it('passes title as labelText to HoverTooltip', () => {+ renderComponent({ disabled: true, id: 'cb4', title: 'my tooltip text' });+ expect(screen.getByTestId('hover-tooltip')).toHaveAttribute('data-label', 'my tooltip text');+ });++ it('passes tooltipPlacement to HoverTooltip', () => {+ renderComponent({+ disabled: true, id: 'cb5', title: 'tip', tooltipPlacement: 'top',+ });+ expect(screen.getByTestId('hover-tooltip')).toHaveAttribute('data-placement', 'top');+ });++ it('sets input title to empty string when showDisabledToolTip is true', () => {+ renderComponent({ disabled: true, id: 'cb6', title: 'my tip' });+ expect(screen.getByRole('checkbox')).toHaveAttribute('title', '');+ });++ it('sets input title to the title prop when showDisabledToolTip is false', () => {+ renderComponent({ disabled: false, id: 'cb7', title: 'my tip' });+ expect(screen.getByRole('checkbox')).toHaveAttribute('title', 'my tip');+ });++ it('onChange is a no-op when showDisabledToolTip is true', () => {+ const onCheck = jest.fn();+ renderComponent({+ disabled: true, id: 'cb8', title: 'tip', onCheck,+ });+ fireEvent.click(screen.getByRole('checkbox'));+ expect(onCheck).not.toHaveBeenCalled();+ });+ });});diff --git a/web/js/components/util/custom-tooltip.test.js b/web/js/components/util/custom-tooltip.test.jsindex 23db312aa..191decfd2 100644--- a/web/js/components/util/custom-tooltip.test.js+++ b/web/js/components/util/custom-tooltip.test.js@@ -1,3 +1,252 @@-test('custom-tooltip component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import CustomTooltip from './custom-tooltip';+const defaultProps = {+ id: 'evt1',+ text: 'Tooltip text',+ hideTooltip: false,+ isSelected: false,+};++const renderComponent = (props = {}) => render(+ <CustomTooltip {...defaultProps} {...props}>+ <span data-testid="child">hover me</span>+ </CustomTooltip>,+);++const getTooltip = (id = 'evt1') => document.getElementById(`tooltip-${id}`);+const getArrow = (id = 'evt1') => document.getElementById(`arrow-tooltip-${id}`);++const mockRect = (overrides = {}) => ({+ x: 100,+ y: 200,+ width: 80,+ height: 20,+ top: 200,+ left: 100,+ right: 180,+ bottom: 220,+ ...overrides,+});++beforeEach(() => {+ // Clean up any marker-container between tests+ const mc = document.getElementById('marker-container');+ if (mc) mc.remove();+});++afterEach(() => {+ const mc = document.getElementById('marker-container');+ if (mc) mc.remove();+});++describe('CustomTooltip', () => {+ describe('initialization (useEffect)', () => {+ it('renders the wrapper div', () => {+ renderComponent();+ expect(screen.getByTestId('child').parentElement.tagName).toBe('DIV');+ });++ it('creates tooltip div with id "tooltip-{id}"', () => {+ renderComponent();+ expect(getTooltip()).toBeInTheDocument();+ });++ it('tooltip div has class "events-tooltip"', () => {+ renderComponent();+ expect(getTooltip()).toHaveClass('events-tooltip');+ });++ it('tooltip div innerHTML equals the text prop', () => {+ renderComponent({ text: 'Hello World' });+ expect(document.getElementById('tooltip-evt1').innerHTML).toBe('Hello World');+ });++ it('creates arrow div with id "arrow-tooltip-{id}"', () => {+ renderComponent();+ expect(getArrow()).toBeInTheDocument();+ });++ it('arrow div has class "events-tooltip-arrow"', () => {+ renderComponent();+ expect(getArrow()).toHaveClass('events-tooltip-arrow');+ });++ it('creates marker-container and appends to body when absent', () => {+ renderComponent();+ const mc = document.getElementById('marker-container');+ expect(mc).toBeInTheDocument();+ expect(document.body.contains(mc)).toBe(true);+ });++ it('reuses existing marker-container instead of creating a new one', () => {+ const existing = document.createElement('div');+ existing.setAttribute('id', 'marker-container');+ document.body.appendChild(existing);++ renderComponent();++ const allMC = document.querySelectorAll('#marker-container');+ expect(allMC.length).toBe(1);+ });++ it('appends both tooltip and arrow to marker-container', () => {+ renderComponent();+ const mc = document.getElementById('marker-container');+ expect(mc.contains(getTooltip())).toBe(true);+ expect(mc.contains(getArrow())).toBe(true);+ });++ it('removes tooltip and arrow divs on unmount', () => {+ const { unmount } = renderComponent();+ act(() => { unmount(); });+ expect(getTooltip()).not.toBeInTheDocument();+ expect(getArrow()).not.toBeInTheDocument();+ });+ });++ describe('children', () => {+ it('renders children inside the wrapper', () => {+ renderComponent();+ expect(screen.getByTestId('child')).toBeInTheDocument();+ });+ });++ describe('handleOnEnter — mouseenter', () => {+ it('does nothing when hideTooltip is true', () => {+ renderComponent({ hideTooltip: true });+ const wrapper = screen.getByTestId('child').parentElement;+ // Should not throw+ fireEvent.mouseEnter(wrapper);+ expect(getTooltip().style.visibility).not.toBe('visible');+ });++ it('returns early when tooltip element is not found in DOM', () => {+ renderComponent();+ // Remove tooltip from DOM to simulate null case+ getTooltip().remove();+ const wrapper = screen.getByTestId('child').parentElement;+ expect(() => fireEvent.mouseEnter(wrapper)).not.toThrow();+ });++ it('sets tooltip visibility to "visible" on mouseenter', () => {+ renderComponent();+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect());+ fireEvent.mouseEnter(wrapper);+ expect(getTooltip().style.visibility).toBe('visible');+ });++ it('sets arrow visibility to "visible" on mouseenter', () => {+ renderComponent();+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect());+ fireEvent.mouseEnter(wrapper);+ expect(getArrow().style.visibility).toBe('visible');+ });++ it('positions tooltip using default (not selected) formula', () => {+ renderComponent({ isSelected: false });+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect({ x: 100, y: 200, height: 20, width: 80 }));+ jest.spyOn(getTooltip(), 'getBoundingClientRect').mockReturnValue(mockRect({ width: 60, height: 20, x: 70, y: 180 }));++ fireEvent.mouseEnter(wrapper);++ // Non-selected: tooltipTop = y - height/2 - 20 - 0 = 200 - 10 - 20 - 0 = 170px+ expect(getTooltip().style.top).toBe('170px');+ // tooltipLeft = x - width/2 + 13 = 100 - 30 + 13 = 83px+ expect(getTooltip().style.left).toBe('83px');+ });++ it('positions tooltip using isSelected formula', () => {+ renderComponent({ isSelected: true });+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect({ x: 100, y: 200, height: 20, width: 80 }));+ jest.spyOn(getTooltip(), 'getBoundingClientRect').mockReturnValue(mockRect({ width: 60, height: 20, x: 70, y: 180 }));++ fireEvent.mouseEnter(wrapper);++ // isSelected: tooltipTop = y - height/2 - 0 - 10 = 200 - 10 - 0 - 10 = 180px+ expect(getTooltip().style.top).toBe('180px');+ // tooltipLeft = x - width/2 + 17 = 100 - 30 + 17 = 87px+ expect(getTooltip().style.left).toBe('87px');+ });++ it('adds wrappedText offset of 10 when tooltip height > 30', () => {+ renderComponent({ isSelected: false });+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect({ x: 100, y: 200, height: 20, width: 80 }));+ // height > 30 → wrappedText = 10+ jest.spyOn(getTooltip(), 'getBoundingClientRect').mockReturnValue(mockRect({ width: 60, height: 40, x: 70, y: 150 }));++ fireEvent.mouseEnter(wrapper);++ // tooltipTop = 200 - 10 - 20 - 10 = 160px+ expect(getTooltip().style.top).toBe('160px');+ });++ it('positions the arrow relative to the (re-read) tooltip rect', () => {+ renderComponent();+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect());+ const tooltipEl = getTooltip();+ // First call returns initial rect; second (for arrow calc) returns updated rect+ jest.spyOn(tooltipEl, 'getBoundingClientRect')+ .mockReturnValueOnce(mockRect({ width: 60, height: 20, x: 70, y: 180 }))+ .mockReturnValueOnce(mockRect({ width: 60, height: 20, x: 70, y: 170 }));++ fireEvent.mouseEnter(wrapper);++ // arrowTop = y + 5 + wrappedText + 0 = 170 + 5 + 0 + 0 = 175px+ expect(getArrow().style.top).toBe('175px');+ // arrowLeft = x + width/2 - 10 = 70 + 30 - 10 = 90px+ expect(getArrow().style.left).toBe('90px');+ });++ it('adds extra 3px to arrow top when wrappedText > 0', () => {+ renderComponent({ isSelected: false });+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect({ x: 100, y: 200, height: 20, width: 80 }));+ const tooltipEl = getTooltip();+ // height > 30 → wrappedText = 10+ jest.spyOn(tooltipEl, 'getBoundingClientRect')+ .mockReturnValueOnce(mockRect({ width: 60, height: 40, x: 70, y: 150 }))+ .mockReturnValueOnce(mockRect({ width: 60, height: 40, x: 70, y: 160 }));++ fireEvent.mouseEnter(wrapper);++ // arrowTop = y + 5 + 10 + 3 = 160 + 5 + 10 + 3 = 178px+ expect(getArrow().style.top).toBe('178px');+ });+ });++ describe('handleOnLeave — mouseleave', () => {+ it('sets tooltip visibility to "hidden" on mouseleave', () => {+ renderComponent();+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect());+ fireEvent.mouseEnter(wrapper);+ fireEvent.mouseLeave(wrapper);+ expect(getTooltip().style.visibility).toBe('hidden');+ });++ it('sets arrow visibility to "hidden" on mouseleave', () => {+ renderComponent();+ const wrapper = screen.getByTestId('child').parentElement;+ jest.spyOn(wrapper, 'getBoundingClientRect').mockReturnValue(mockRect());+ fireEvent.mouseEnter(wrapper);+ fireEvent.mouseLeave(wrapper);+ expect(getArrow().style.visibility).toBe('hidden');+ });++ it('returns early without error when tooltip element is missing from DOM', () => {+ renderComponent();+ getTooltip().remove();+ const wrapper = screen.getByTestId('child').parentElement;+ expect(() => fireEvent.mouseLeave(wrapper)).not.toThrow();+ });+ });});diff --git a/web/js/components/util/debug.test.js b/web/js/components/util/debug.test.jsindex c536ba2d9..81f4d0939 100644--- a/web/js/components/util/debug.test.js+++ b/web/js/components/util/debug.test.js@@ -1,3 +1,43 @@-test('debug component test', () => {+import { render } from '@testing-library/react';+import '@testing-library/jest-dom';+import Debug from './debug';+// Suppress the expected error boundary console output for the throw test+const suppressError = () => {};++describe('Debug', () => {+ describe('normal render', () => {+ it('renders without throwing when showError is false', () => {+ expect(() => render(<Debug parameters={{ showError: false }} />)).not.toThrow();+ });++ it('renders without throwing when showError is absent', () => {+ expect(() => render(<Debug parameters={{}} />)).not.toThrow();+ });++ it('returns empty string (renders nothing visible)', () => {+ const { container } = render(<Debug parameters={{}} />);+ expect(container).toBeEmptyDOMElement();+ });+ });++ describe('error path', () => {+ it('throws an Error when showError is true', () => {+ const spy = jest.spyOn(console, 'error').mockImplementation(suppressError);+ expect(() => render(<Debug parameters={{ showError: true }} />)).toThrow('this is a test error');+ spy.mockRestore();+ });++ it('thrown error is an instance of Error', () => {+ const spy = jest.spyOn(console, 'error').mockImplementation(suppressError);+ let caught;+ try {+ render(<Debug parameters={{ showError: true }} />);+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(Error);+ spy.mockRestore();+ });+ });});diff --git a/web/js/components/util/detect-outer-click.test.js b/web/js/components/util/detect-outer-click.test.jsindex 5084a13e8..e794f2c6e 100644--- a/web/js/components/util/detect-outer-click.test.js+++ b/web/js/components/util/detect-outer-click.test.js@@ -1,3 +1,130 @@-test('detect-outer-click component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import OutsideAlerter from './detect-outer-click';+const defaultProps = {+ onClick: jest.fn(),+};++const renderComponent = (props = {}, children = <span data-testid="inner">inside</span>) => render(+ <OutsideAlerter {...defaultProps} {...props}>+ {children}+ </OutsideAlerter>,+);++beforeEach(() => {+ jest.clearAllMocks();+ const existing = document.getElementById('wv-map');+ if (existing) existing.remove();+});++afterEach(() => {+ const existing = document.getElementById('wv-map');+ if (existing) existing.remove();+});++describe('OutsideAlerter', () => {+ describe('render', () => {+ it('renders a wrapper div', () => {+ renderComponent();+ expect(screen.getByTestId('inner').parentElement.tagName).toBe('DIV');+ });++ it('renders children inside the wrapper', () => {+ renderComponent();+ expect(screen.getByTestId('inner')).toBeInTheDocument();+ });+ });++ describe('componentDidMount — event listeners', () => {+ it('adds mousedown listener to document on mount', () => {+ const addSpy = jest.spyOn(document, 'addEventListener');+ renderComponent();+ expect(addSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));+ addSpy.mockRestore();+ });++ it('adds touchstart listener to document on mount', () => {+ const addSpy = jest.spyOn(document, 'addEventListener');+ renderComponent();+ expect(addSpy).toHaveBeenCalledWith('touchstart', expect.any(Function));+ addSpy.mockRestore();+ });++ it('adds mousedown listener to #wv-map when it exists', () => {+ const mapEl = document.createElement('div');+ mapEl.setAttribute('id', 'wv-map');+ document.body.appendChild(mapEl);+ const mapAddSpy = jest.spyOn(mapEl, 'addEventListener');++ renderComponent();++ expect(mapAddSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));+ });++ it('does not throw when #wv-map is absent', () => {+ expect(() => renderComponent()).not.toThrow();+ });+ });++ describe('componentWillUnmount — event listeners', () => {+ it('removes mousedown listener from document on unmount', () => {+ const removeSpy = jest.spyOn(document, 'removeEventListener');+ const { unmount } = renderComponent();+ act(() => { unmount(); });+ expect(removeSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));+ removeSpy.mockRestore();+ });+ });++ describe('handleClickOutside', () => {+ it('calls onClick when mousedown fires outside the wrapper', () => {+ const onClick = jest.fn();+ renderComponent({ onClick });+ act(() => { document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); });+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('does not call onClick when mousedown fires inside the wrapper', () => {+ const onClick = jest.fn();+ renderComponent({ onClick });+ const inner = screen.getByTestId('inner');+ act(() => { inner.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); });+ expect(onClick).not.toHaveBeenCalled();+ });++ it('does not call onClick when disabled is true', () => {+ const onClick = jest.fn();+ renderComponent({ onClick, disabled: true });+ act(() => { document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); });+ expect(onClick).not.toHaveBeenCalled();+ });++ it('calls onClick on touchstart outside the wrapper', () => {+ const onClick = jest.fn();+ renderComponent({ onClick });+ act(() => { document.dispatchEvent(new TouchEvent('touchstart', { bubbles: true })); });+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('does not call onClick on touchstart when disabled', () => {+ const onClick = jest.fn();+ renderComponent({ onClick, disabled: true });+ act(() => { document.dispatchEvent(new TouchEvent('touchstart', { bubbles: true })); });+ expect(onClick).not.toHaveBeenCalled();+ });++ it('calls onClick via #wv-map mousedown when outside the wrapper', () => {+ const mapEl = document.createElement('div');+ mapEl.setAttribute('id', 'wv-map');+ document.body.appendChild(mapEl);++ const onClick = jest.fn();+ renderComponent({ onClick });++ act(() => { mapEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: false })); });+ expect(onClick).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/web/js/components/util/google-tag-manager.test.js b/web/js/components/util/google-tag-manager.test.jsindex 48c6277f4..630b6f05a 100644--- a/web/js/components/util/google-tag-manager.test.js+++ b/web/js/components/util/google-tag-manager.test.js@@ -1,3 +1,57 @@-test('google-tag-manager component test', () => {+import googleTagManager from './google-tag-manager';+describe('google-tag-manager module', () => {+ describe('module-level virtualPageView push', () => {+ it('pushes a virtualPageView event on import', () => {+ const entry = window.dataLayer.find((e) => e.event === 'virtualPageView');+ expect(entry).toBeDefined();+ });++ it('virtualPageView entry contains page_location', () => {+ const entry = window.dataLayer.find((e) => e.event === 'virtualPageView');+ expect(entry).toHaveProperty('page_location');+ });++ it('virtualPageView entry contains page_title', () => {+ const entry = window.dataLayer.find((e) => e.event === 'virtualPageView');+ expect(entry).toHaveProperty('page_title');+ });++ it('virtualPageView entry contains page_referrer', () => {+ const entry = window.dataLayer.find((e) => e.event === 'virtualPageView');+ expect(entry).toHaveProperty('page_referrer');+ });+ });++ describe('pushEvent()', () => {+ beforeEach(() => {+ window.dataLayer = [];+ });++ it('pushes the supplied event object onto dataLayer', () => {+ const event = { event: 'testEvent', value: 42 };+ googleTagManager.pushEvent(event);+ expect(window.dataLayer).toContainEqual(event);+ });++ it('pushes multiple events in order', () => {+ const e1 = { event: 'first' };+ const e2 = { event: 'second' };+ googleTagManager.pushEvent(e1);+ googleTagManager.pushEvent(e2);+ expect(window.dataLayer[0]).toEqual(e1);+ expect(window.dataLayer[1]).toEqual(e2);+ });++ it('does not push when dataLayer is undefined', () => {+ // Remove dataLayer from window to simulate undefined+ const saved = window.dataLayer;+ delete window.dataLayer;++ // dataLayer global is now undefined — pushEvent must not throw+ expect(() => googleTagManager.pushEvent({ event: 'x' })).not.toThrow();++ window.dataLayer = saved;+ });+ });});diff --git a/web/js/components/util/hover-tooltip.test.js b/web/js/components/util/hover-tooltip.test.jsindex 7cd882e2a..e602171b2 100644--- a/web/js/components/util/hover-tooltip.test.js+++ b/web/js/components/util/hover-tooltip.test.js@@ -1,3 +1,120 @@-test('hover-tooltip component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import HoverTooltip from './hover-tooltip';+jest.mock('reactstrap', () => ({+ UncontrolledTooltip: ({+ id, trigger, target, placement, delay, fade, innerClassName, children,+ }) => (+ <div+ data-testid="uncontrolled-tooltip"+ data-id={id}+ data-trigger={trigger}+ data-target={target}+ data-placement={placement}+ data-delay={JSON.stringify(delay)}+ data-fade={String(fade)}+ data-inner-classname={innerClassName}+ >+ {children}+ </div>+ ),+}));++const defaultProps = {+ target: 'some-element',+ labelText: 'Helpful hint',+};++const renderComponent = (props = {}) => render(+ <HoverTooltip {...defaultProps} {...props} />,+);++describe('HoverTooltip', () => {+ describe('when isMobile is falsy (default)', () => {+ it('renders the UncontrolledTooltip', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toBeInTheDocument();+ });++ it('passes target prop to UncontrolledTooltip', () => {+ renderComponent({ target: 'my-target' });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-target', 'my-target');+ });++ it('passes labelText as children to UncontrolledTooltip', () => {+ renderComponent({ labelText: 'Some label' });+ expect(screen.getByText('Some label')).toBeInTheDocument();+ });++ it('passes placement "bottom" when provided', () => {+ renderComponent({ placement: 'bottom' });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-placement', 'bottom');+ });++ it('passes custom placement when provided', () => {+ renderComponent({ placement: 'top' });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-placement', 'top');+ });++ it('passes delay { show: 50, hide: 0 } when provided', () => {+ renderComponent({ delay: { show: 50, hide: 0 } });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute(+ 'data-delay',+ JSON.stringify({ show: 50, hide: 0 }),+ );+ });++ it('passes custom delay when provided', () => {+ renderComponent({ delay: { show: 200, hide: 100 } });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute(+ 'data-delay',+ JSON.stringify({ show: 200, hide: 100 }),+ );+ });++ it('passes fade=true when provided', () => {+ renderComponent({ fade: true });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-fade', 'true');+ });++ it('passes fade=false when provided', () => {+ renderComponent({ fade: false });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-fade', 'false');+ });++ it('passes empty innerClassName when provided', () => {+ renderComponent({ innerClassName: '' });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-inner-classname', '');+ });++ it('passes custom innerClassName when provided', () => {+ renderComponent({ innerClassName: 'my-inner' });+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-inner-classname', 'my-inner');+ });++ it('sets trigger to "hover"', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-trigger', 'hover');+ });++ it('sets id to "center-align-tooltip"', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-id', 'center-align-tooltip');+ });+ });++ describe('when isMobile is true', () => {+ it('renders nothing', () => {+ const { container } = renderComponent({ isMobile: true });+ expect(container).toBeEmptyDOMElement();+ });++ it('does not render UncontrolledTooltip', () => {+ renderComponent({ isMobile: true });+ expect(screen.queryByTestId('uncontrolled-tooltip')).not.toBeInTheDocument();+ });+ });});diff --git a/web/js/components/util/icon-list.test.js b/web/js/components/util/icon-list.test.jsindex f33420687..caf7d05d1 100644--- a/web/js/components/util/icon-list.test.js+++ b/web/js/components/util/icon-list.test.js@@ -1,3 +1,253 @@-test('icon-list component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import IconList from './icon-list';+jest.mock('reactstrap', () => ({+ ListGroup: ({ className, children }) => (+ <ul data-testid="list-group" className={className}>{children}</ul>+ ),+ ListGroupItem: ({+ tag: Tag = 'div', active, disabled, id, className, href, target, onClick, children,+ }) => (+ <Tag+ data-testid="list-group-item"+ data-active={String(active)}+ data-disabled={String(disabled)}+ id={id}+ className={className}+ href={href}+ target={target}+ onClick={onClick}+ disabled={disabled}+ >+ {children}+ </Tag>+ ),+ Badge: ({ pill, children }) => (+ <span data-testid="badge" data-pill={String(pill)}>{children}</span>+ ),+}));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon, className }) => (+ <span data-testid="fa-icon" data-icon={icon} className={className} />+ ),+}));++const baseItem = { id: 'item1', text: 'Item One', key: 'key1' };++const renderComponent = (props = {}) => render(+ <IconList list={[baseItem]} size="medium" {...props} />,+);++describe('IconList', () => {+ describe('ListGroup wrapper', () => {+ it('renders the ListGroup', () => {+ renderComponent();+ expect(screen.getByTestId('list-group')).toBeInTheDocument();+ });++ it('applies listClass to the ListGroup', () => {+ renderComponent({ listClass: 'my-list' });+ expect(screen.getByTestId('list-group')).toHaveClass('my-list');+ });+ });++ describe('item rendering', () => {+ it('renders one ListGroupItem per non-hidden list entry', () => {+ renderComponent({ list: [baseItem, { id: 'item2', text: 'Two', key: 'key2' }] });+ expect(screen.getAllByTestId('list-group-item')).toHaveLength(2);+ });++ it('does not render hidden items', () => {+ renderComponent({ list: [{ ...baseItem, hidden: true }] });+ expect(screen.queryByTestId('list-group-item')).not.toBeInTheDocument();+ });++ it('renders item text', () => {+ renderComponent();+ expect(screen.getByText('Item One')).toBeInTheDocument();+ });++ it('sets item id from item.id', () => {+ renderComponent();+ expect(document.getElementById('item1')).toBeInTheDocument();+ });++ it('applies size class to item className', () => {+ renderComponent({ size: 'large' });+ expect(screen.getByTestId('list-group-item')).toHaveClass('large-item');+ });++ it('applies item.className alongside size class', () => {+ renderComponent({ list: [{ ...baseItem, className: 'custom-class' }] });+ expect(screen.getByTestId('list-group-item')).toHaveClass('custom-class');+ });+ });++ describe('active and disabled state', () => {+ it('marks item as active when key matches active prop', () => {+ renderComponent({ active: 'key1' });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-active', 'true');+ });++ it('does not mark item as active when key does not match', () => {+ renderComponent({ active: 'other' });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-active', 'false');+ });++ it('isActive is false when active prop is absent', () => {+ renderComponent();+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-active', 'false');+ });++ it('isActive is false when item has no key even if active prop is set', () => {+ renderComponent({ active: 'key1', list: [{ id: 'item1', text: 'No Key' }] });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-active', 'false');+ });++ it('marks item as disabled when key matches disabled prop', () => {+ renderComponent({ disabled: 'key1' });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-disabled', 'true');+ });++ it('does not mark item as disabled when key does not match', () => {+ renderComponent({ disabled: 'other' });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-disabled', 'false');+ });++ it('isDisabled is false when disabled prop is absent', () => {+ renderComponent();+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-disabled', 'false');+ });++ it('isDisabled is false when item has no key even if disabled prop is set', () => {+ renderComponent({ disabled: 'key1', list: [{ id: 'item1', text: 'No Key' }] });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('data-disabled', 'false');+ });+ });++ describe('tag — button vs anchor', () => {+ it('renders as a button when href is absent', () => {+ renderComponent();+ expect(screen.getByTestId('list-group-item').tagName).toBe('BUTTON');+ });++ it('renders as an anchor when href is provided', () => {+ renderComponent({ list: [{ ...baseItem, href: 'https://example.com' }] });+ expect(screen.getByTestId('list-group-item').tagName).toBe('A');+ });++ it('sets href attribute when provided', () => {+ renderComponent({ list: [{ ...baseItem, href: 'https://example.com' }] });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('href', 'https://example.com');+ });++ it('sets target="_blank" when href is provided', () => {+ renderComponent({ list: [{ ...baseItem, href: 'https://example.com' }] });+ expect(screen.getByTestId('list-group-item')).toHaveAttribute('target', '_blank');+ });++ it('does not set target when href is absent', () => {+ renderComponent();+ expect(screen.getByTestId('list-group-item')).not.toHaveAttribute('target');+ });+ });++ describe('onClick', () => {+ it('calls the list-level onClick with item key when clicked', () => {+ const onClick = jest.fn();+ renderComponent({ onClick });+ fireEvent.click(screen.getByTestId('list-group-item'));+ expect(onClick).toHaveBeenCalledWith('key1');+ });++ it('calls the list-level onClick with item id when key is absent', () => {+ const onClick = jest.fn();+ renderComponent({ onClick, list: [{ id: 'item1', text: 'Item' }] });+ fireEvent.click(screen.getByTestId('list-group-item'));+ expect(onClick).toHaveBeenCalledWith('item1');+ });++ it('prefers item.onClick over the list-level onClick', () => {+ const listOnClick = jest.fn();+ const itemOnClick = jest.fn();+ renderComponent({+ onClick: listOnClick,+ list: [{ ...baseItem, onClick: itemOnClick }],+ });+ fireEvent.click(screen.getByTestId('list-group-item'));+ expect(itemOnClick).toHaveBeenCalledTimes(1);+ expect(listOnClick).not.toHaveBeenCalled();+ });++ it('sets onClick to null when neither item.onClick nor list onClick is provided', () => {+ renderComponent({ onClick: undefined });+ // Clicking should not throw+ expect(() => fireEvent.click(screen.getByTestId('list-group-item'))).not.toThrow();+ });+ });++ describe('FontAwesomeIcon', () => {+ it('renders icon when iconName is provided', () => {+ renderComponent({ list: [{ ...baseItem, iconName: 'star' }] });+ expect(screen.getByTestId('fa-icon')).toBeInTheDocument();+ });++ it('does not render icon when iconName is absent', () => {+ renderComponent();+ expect(screen.queryByTestId('fa-icon')).not.toBeInTheDocument();+ });++ it('passes iconClass to the icon', () => {+ renderComponent({ list: [{ ...baseItem, iconName: 'star', iconClass: 'icon-red' }] });+ expect(screen.getByTestId('fa-icon')).toHaveClass('icon-red');+ });+ });++ describe('Badge', () => {+ it('renders badge when badge prop is provided on item', () => {+ renderComponent({ list: [{ ...baseItem, badge: '3' }] });+ expect(screen.getByTestId('badge')).toBeInTheDocument();+ });++ it('renders badge text content', () => {+ renderComponent({ list: [{ ...baseItem, badge: '42' }] });+ expect(screen.getByTestId('badge')).toHaveTextContent('42');+ });++ it('does not render badge when badge prop is absent', () => {+ renderComponent();+ expect(screen.queryByTestId('badge')).not.toBeInTheDocument();+ });+ });++ describe('key resolution', () => {+ it('uses item.key as the React key (no duplicate-key warning)', () => {+ expect(() => renderComponent({+ list: [+ { id: 'a', key: 'k1', text: 'A' },+ { id: 'b', key: 'k2', text: 'B' },+ ],+ })).not.toThrow();+ });++ it('renders without error when item has neither key nor id (falls back to empty string key)', () => {+ expect(() => renderComponent({ list: [{ text: 'No key or id' }] })).not.toThrow();+ });+ });++ describe('falsy fallbacks', () => {+ it('renders without error when item has no id (id falls back to empty string)', () => {+ renderComponent({ list: [{ key: 'k1', text: 'No id' }] });+ expect(screen.getByTestId('list-group-item')).toBeInTheDocument();+ });++ it('renders without error when item has no text (text falls back to empty string)', () => {+ renderComponent({ list: [{ id: 'x', key: 'k1' }] });+ expect(screen.getByTestId('list-group-item')).toBeInTheDocument();+ });+ });});diff --git a/web/js/components/util/image-crop.test.js b/web/js/components/util/image-crop.test.jsindex b2904ed8d..5adcd95b5 100644--- a/web/js/components/util/image-crop.test.js+++ b/web/js/components/util/image-crop.test.js@@ -1,3 +1,267 @@-test('image-crop component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import Crop from './image-crop';+// Capture latest ReactCrop props so tests can invoke callbacks directly+const reactCropProps = {};++jest.mock('react-image-crop', () => ({+ __esModule: true,+ default: (props) => {+ Object.assign(reactCropProps, props);+ return (+ <div+ data-testid="react-crop"+ data-background={props.style?.background}+ data-zindex={String(props.style?.zIndex)}+ data-keep-selection={String(props.keepSelection)}+ >+ {props.children}+ </div>+ );+ },+}));++// Render portal children inline so they appear in the normal DOM tree+jest.mock('react-dom', () => ({+ ...jest.requireActual('react-dom'),+ createPortal: (node) => node,+}));++const TRANSPARENT_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';++const defaultProps = {+ onChange: jest.fn(),+ onClose: jest.fn(),+ onDragStop: jest.fn(),+ x: 20,+ y: 10,+ width: 30,+ height: 10,+};++const renderComponent = (props = {}) => render(+ <Crop {...defaultProps} {...props} />,+);++beforeEach(() => {+ jest.clearAllMocks();+});++describe('Crop (image-crop)', () => {+ describe('render', () => {+ it('renders without throwing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the ReactCrop element', () => {+ renderComponent();+ expect(screen.getByTestId('react-crop')).toBeInTheDocument();+ });++ it('renders the transparent gif img', () => {+ renderComponent();+ expect(screen.getByRole('img')).toHaveAttribute('src', TRANSPARENT_GIF);+ });++ it('passes maxWidth and maxHeight to the img style', () => {+ renderComponent({ maxWidth: 500, maxHeight: 400 });+ const img = screen.getByRole('img');+ expect(img).toHaveStyle({ width: '500px', height: '400px' });+ });+ });++ describe('ReactCrop props', () => {+ it('passes keepSelection=true', () => {+ renderComponent({ keepSelection: true });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-keep-selection', 'true');+ });++ it('passes keepSelection=false when not set', () => {+ renderComponent({ keepSelection: false });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-keep-selection', 'false');+ });++ it('passes zIndex in style', () => {+ renderComponent({ zIndex: 10 });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-zindex', '10');+ });++ it('sets background to "none" when initial crop has width and height', () => {+ renderComponent({ width: 30, height: 10 });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'none');+ });++ it('sets background to rgba(0,0,0,0.5) when initial crop width is 0', () => {+ renderComponent({ width: 0, height: 10 });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'rgba(0, 0, 0, 0.5)');+ });++ it('sets background to rgba(0,0,0,0.5) when initial crop height is 0', () => {+ renderComponent({ width: 30, height: 0 });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'rgba(0, 0, 0, 0.5)');+ });+ });++ describe('useEffect — crop state syncs with props', () => {+ it('updates background to rgba after width prop changes to 0', () => {+ const { rerender } = renderComponent({ width: 30, height: 10 });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'none');++ act(() => {+ rerender(<Crop {...defaultProps} width={0} />);+ });++ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'rgba(0, 0, 0, 0.5)');+ });++ it('updates background to "none" after width prop changes from 0 to positive', () => {+ const { rerender } = renderComponent({ width: 0, height: 10 });+ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'rgba(0, 0, 0, 0.5)');++ act(() => {+ rerender(<Crop {...defaultProps} width={40} />);+ });++ expect(screen.getByTestId('react-crop')).toHaveAttribute('data-background', 'none');+ });+ });++ describe('onDrag (onChange)', () => {+ it('calls onChange when both width and height are truthy', () => {+ const onChange = jest.fn();+ renderComponent({ onChange });+ const boundaries = { x: 5, y: 5, width: 20, height: 15 };+ act(() => { reactCropProps.onChange(boundaries); });+ expect(onChange).toHaveBeenCalledWith(boundaries);+ });++ it('does not call onChange when width is 0', () => {+ const onChange = jest.fn();+ renderComponent({ onChange });+ act(() => { reactCropProps.onChange({ x: 5, y: 5, width: 0, height: 15 }); });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('does not call onChange when height is 0', () => {+ const onChange = jest.fn();+ renderComponent({ onChange });+ act(() => { reactCropProps.onChange({ x: 5, y: 5, width: 20, height: 0 }); });+ expect(onChange).not.toHaveBeenCalled();+ });+ });++ describe('onFinishDrag (onComplete)', () => {+ it('calls onDragStop when dimensions are positive and a value changed', () => {+ const onDragStop = jest.fn();+ // Initial prevCrop: {x:20, y:10, width:30, height:10}+ renderComponent({ onDragStop });+ const boundaries = { x: 5, y: 10, width: 30, height: 10 };+ act(() => { reactCropProps.onComplete(boundaries); });+ expect(onDragStop).toHaveBeenCalledWith(boundaries);+ });++ it('calls onClose when width is 0', () => {+ const onClose = jest.fn();+ renderComponent({ onClose });+ act(() => { reactCropProps.onComplete({ x: 5, y: 10, width: 0, height: 10 }); });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('calls onClose when height is 0', () => {+ const onClose = jest.fn();+ renderComponent({ onClose });+ act(() => { reactCropProps.onComplete({ x: 5, y: 10, width: 20, height: 0 }); });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('calls onClose when crop values are unchanged from initial', () => {+ const onClose = jest.fn();+ // Initial prevCrop: {x:20, y:10, width:30, height:10}+ renderComponent({ onClose });+ act(() => { reactCropProps.onComplete({ x: 20, y: 10, width: 30, height: 10 }); });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('does not call onDragStop when crop values are unchanged', () => {+ const onDragStop = jest.fn();+ renderComponent({ onDragStop });+ act(() => { reactCropProps.onComplete({ x: 20, y: 10, width: 30, height: 10 }); });+ expect(onDragStop).not.toHaveBeenCalled();+ });+ });++ describe('default parameter fallbacks', () => {+ it('renders with only onChange provided (all other props use defaults)', () => {+ expect(() => render(<Crop onChange={jest.fn()} />)).not.toThrow();+ });++ it('uses default onClose (() => {}) when onClose is not provided and close is triggered', () => {+ render(<Crop onChange={jest.fn()} onDragStop={jest.fn()} />);+ // width=0 triggers the onClose branch; default is () => {} so no throw+ expect(() => act(() => {+ reactCropProps.onComplete({ x: 20, y: 10, width: 0, height: 10 });+ })).not.toThrow();+ });++ it('uses default onDragStop (() => {}) when onDragStop is not provided and drag is detected', () => {+ render(<Crop onChange={jest.fn()} onClose={jest.fn()} />);+ // x differs from prevCrop initial (x=20) → triggers onDragStop branch+ expect(() => act(() => {+ reactCropProps.onComplete({ x: 5, y: 10, width: 30, height: 10 });+ })).not.toThrow();+ });+ });++ describe('showCoordinates / RenderCoordinates', () => {+ const coordProps = {+ showCoordinates: true,+ coordinates: { topRight: '10°N 20°E', bottomLeft: '5°S 15°W' },+ topRightStyle: { width: 80 },+ bottomLeftStyle: { width: 80 },+ };++ it('does not render coordinate divs when showCoordinates is false', () => {+ renderComponent({ showCoordinates: false });+ expect(document.getElementById('wv-image-top')).not.toBeInTheDocument();+ expect(document.getElementById('wv-image-bottom')).not.toBeInTheDocument();+ });++ it('renders both coordinate divs when showCoordinates=true and width >= 50', () => {+ renderComponent(coordProps);+ expect(document.getElementById('wv-image-top')).toBeInTheDocument();+ expect(document.getElementById('wv-image-bottom')).toBeInTheDocument();+ });++ it('renders topRight coordinate text', () => {+ renderComponent(coordProps);+ expect(screen.getByText('10°N 20°E')).toBeInTheDocument();+ });++ it('renders bottomLeft coordinate text', () => {+ renderComponent(coordProps);+ expect(screen.getByText('5°S 15°W')).toBeInTheDocument();+ });++ it('renders nothing when bottomLeftStyle.width < 50', () => {+ renderComponent({+ ...coordProps,+ topRightStyle: { width: 30 },+ bottomLeftStyle: { width: 30 },+ });+ expect(document.getElementById('wv-image-top')).not.toBeInTheDocument();+ expect(document.getElementById('wv-image-bottom')).not.toBeInTheDocument();+ });++ it('applies topRightStyle to the top coordinate div', () => {+ renderComponent(coordProps);+ expect(document.getElementById('wv-image-top')).toHaveStyle({ width: '80px' });+ });++ it('applies bottomLeftStyle to the bottom coordinate div', () => {+ renderComponent(coordProps);+ expect(document.getElementById('wv-image-bottom')).toHaveStyle({ width: '80px' });+ });+ });});diff --git a/web/js/components/util/monospace-date.test.js b/web/js/components/util/monospace-date.test.jsindex cc858e288..60ea57cb0 100644--- a/web/js/components/util/monospace-date.test.js+++ b/web/js/components/util/monospace-date.test.js@@ -1,3 +1,39 @@-test('monospace-date component test', () => {+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import MonospaceDate from './monospace-date';+describe('MonospaceDate', () => {+ it('renders a span with className "monospace"', () => {+ const { container } = render(<MonospaceDate />);+ expect(container.querySelector('.monospace')).toBeInTheDocument();+ });++ it('renders the date string', () => {+ render(<MonospaceDate date="2024-01-15" />);+ expect(screen.getByText('2024-01-15')).toBeInTheDocument();+ });++ it('renders children alongside the date', () => {+ render(<MonospaceDate date="2024-01-15"><span data-testid="child">icon</span></MonospaceDate>);+ expect(screen.getByTestId('child')).toBeInTheDocument();+ expect(screen.getByText('2024-01-15')).toBeInTheDocument();+ });++ it('renders with no date and no children without throwing', () => {+ expect(() => render(<MonospaceDate />)).not.toThrow();+ });++ it('renders children without a date', () => {+ render(<MonospaceDate><span data-testid="only-child">child</span></MonospaceDate>);+ expect(screen.getByTestId('only-child')).toBeInTheDocument();+ });++ it('renders children before date text in DOM order', () => {+ render(<MonospaceDate date="2024-06-05"><span data-testid="prefix">T:</span></MonospaceDate>);+ const span = screen.getByText('2024-06-05').closest('.monospace');+ const children = Array.from(span.childNodes);+ const childIndex = children.findIndex((n) => n.dataset?.testid === 'prefix');+ const dateIndex = children.findIndex((n) => n.textContent === '2024-06-05');+ expect(childIndex).toBeLessThan(dateIndex);+ });});diff --git a/web/js/components/util/scrollbar.test.js b/web/js/components/util/scrollbar.test.jsindex 814f11c60..f8df8d082 100644--- a/web/js/components/util/scrollbar.test.js+++ b/web/js/components/util/scrollbar.test.js@@ -1,3 +1,132 @@-test('scrollbar component test', () => {+/* eslint-disable react/prop-types */+import { render, screen, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import Scrollbars from './scrollbar';+let mockContentEl;+let mockContentWrapperEl;+let mockSkipRefAssignment = false;++jest.mock('simplebar-react', () => {+ const React = require('react');+ return {+ __esModule: true,+ default: React.forwardRef(({ children, style, className, autoHide }, ref) => {+ // useLayoutEffect runs before the parent's useEffect, ensuring ref.current+ // is populated before Scrollbars' toggle-class logic reads it.+ React.useLayoutEffect(() => {+ if (ref && !mockSkipRefAssignment && !ref.current) {+ mockContentEl = global.document.createElement('div');+ mockContentWrapperEl = global.document.createElement('div');+ ref.current = { contentEl: mockContentEl, contentWrapperEl: mockContentWrapperEl };+ }+ });+ return (+ <div+ data-testid="simplebar"+ data-auto-hide={String(autoHide)}+ style={style}+ className={className}+ >+ {children}+ </div>+ );+ }),+ };+});++// Make debounce a pass-through so the wrapped function executes synchronously.+jest.mock('lodash', () => ({+ debounce: (fn) => fn,+}));++function setOffsetHeight(el, value) {+ Object.defineProperty(el, 'offsetHeight', { configurable: true, get: () => value });+}++beforeEach(() => {+ mockContentEl = undefined;+ mockContentWrapperEl = undefined;+ mockSkipRefAssignment = false;+ jest.useFakeTimers();+});++afterEach(() => {+ jest.useRealTimers();+});++describe('Scrollbars', () => {+ describe('render', () => {+ it('renders without throwing', () => {+ expect(() => render(<Scrollbars />)).not.toThrow();+ });++ it('renders the SimpleBarReact wrapper', () => {+ render(<Scrollbars />);+ expect(screen.getByTestId('simplebar')).toBeInTheDocument();+ });++ it('renders children inside SimpleBarReact', () => {+ render(<Scrollbars><span data-testid="child">content</span></Scrollbars>);+ expect(screen.getByTestId('child')).toBeInTheDocument();+ });++ it('passes style prop to SimpleBarReact', () => {+ render(<Scrollbars style={{ height: 300 }} />);+ expect(screen.getByTestId('simplebar')).toHaveStyle({ height: '300px' });+ });++ it('passes className prop to SimpleBarReact', () => {+ render(<Scrollbars className="my-scroll" />);+ expect(screen.getByTestId('simplebar')).toHaveClass('my-scroll');+ });++ it('always passes autoHide={false} to SimpleBarReact', () => {+ render(<Scrollbars />);+ expect(screen.getByTestId('simplebar')).toHaveAttribute('data-auto-hide', 'false');+ });+ });++ describe('useEffect — scrollbar-visible class', () => {+ it('does not throw when ref.current is not yet set (early-return path)', () => {+ mockSkipRefAssignment = true;+ expect(() => render(<Scrollbars />)).not.toThrow();+ });++ it('adds scrollbar-visible when contentEl is taller than contentWrapperEl', () => {+ const { rerender } = render(<Scrollbars />);+ setOffsetHeight(mockContentEl, 200);+ setOffsetHeight(mockContentWrapperEl, 100);+ rerender(<Scrollbars />);+ expect(mockContentEl.classList.contains('scrollbar-visible')).toBe(true);+ });++ it('removes scrollbar-visible when contentEl is not taller than contentWrapperEl', () => {+ const { rerender } = render(<Scrollbars />);+ mockContentEl.classList.add('scrollbar-visible');+ setOffsetHeight(mockContentEl, 50);+ setOffsetHeight(mockContentWrapperEl, 100);+ rerender(<Scrollbars />);+ expect(mockContentEl.classList.contains('scrollbar-visible')).toBe(false);+ });++ it('adds scrollbar-visible after the 800ms setTimeout (taller case)', () => {+ const { rerender } = render(<Scrollbars />);+ setOffsetHeight(mockContentEl, 200);+ setOffsetHeight(mockContentWrapperEl, 100);+ rerender(<Scrollbars />);+ act(() => { jest.advanceTimersByTime(800); });+ expect(mockContentEl.classList.contains('scrollbar-visible')).toBe(true);+ });++ it('removes scrollbar-visible after the 800ms setTimeout (not-taller case)', () => {+ const { rerender } = render(<Scrollbars />);+ mockContentEl.classList.add('scrollbar-visible');+ setOffsetHeight(mockContentEl, 50);+ setOffsetHeight(mockContentWrapperEl, 200);+ rerender(<Scrollbars />);+ act(() => { jest.advanceTimersByTime(800); });+ expect(mockContentEl.classList.contains('scrollbar-visible')).toBe(false);+ });+ });});diff --git a/web/js/components/util/selector.test.js b/web/js/components/util/selector.test.jsindex 0867b0b2c..9842602e7 100644--- a/web/js/components/util/selector.test.js+++ b/web/js/components/util/selector.test.js@@ -1,3 +1,106 @@-test('selector component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import Selector from './selector';+const defaultOptions = {+ values: [+ { value: 'opt1', text: 'Option 1' },+ { value: 'opt2', text: 'Option 2' },+ { value: 'opt3', text: 'Option 3' },+ ],+};++const defaultProps = {+ id: 'test-selector',+ onChange: jest.fn(),+ optionName: 'myOption',+ optionArray: defaultOptions,+ value: 'opt1',+};++const renderComponent = (props = {}) => render(+ <Selector {...defaultProps} {...props} />,+);++beforeEach(() => {+ jest.clearAllMocks();+});++describe('Selector', () => {+ describe('rendering', () => {+ it('renders a select element', () => {+ renderComponent();+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ });++ it('applies the id prop to the select element', () => {+ renderComponent({ id: 'my-select' });+ expect(document.getElementById('my-select')).toBeInTheDocument();+ });++ it('sets the select value to the value prop', () => {+ renderComponent({ value: 'opt2' });+ expect(screen.getByRole('combobox')).toHaveValue('opt2');+ });++ it('renders the correct number of options', () => {+ renderComponent();+ expect(screen.getAllByRole('option')).toHaveLength(3);+ });++ it('renders each option with the correct value attribute', () => {+ renderComponent();+ const options = screen.getAllByRole('option');+ expect(options[0]).toHaveValue('opt1');+ expect(options[1]).toHaveValue('opt2');+ expect(options[2]).toHaveValue('opt3');+ });++ it('renders each option with the correct display text', () => {+ renderComponent();+ expect(screen.getByText('Option 1')).toBeInTheDocument();+ expect(screen.getByText('Option 2')).toBeInTheDocument();+ expect(screen.getByText('Option 3')).toBeInTheDocument();+ });++ it('renders with a single option', () => {+ renderComponent({+ optionArray: { values: [{ value: 'only', text: 'Only One' }] },+ value: 'only',+ });+ expect(screen.getAllByRole('option')).toHaveLength(1);+ expect(screen.getByText('Only One')).toBeInTheDocument();+ });++ it('renders with an empty options list', () => {+ renderComponent({ optionArray: { values: [] } });+ expect(screen.queryAllByRole('option')).toHaveLength(0);+ });+ });++ describe('onChange handler', () => {+ it('calls onChange with optionName and the selected value when changed', () => {+ const onChange = jest.fn();+ renderComponent({ onChange, optionName: 'myOption', value: 'opt1' });+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'opt2' } });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith('myOption', 'opt2');+ });++ it('passes the correct optionName from props', () => {+ const onChange = jest.fn();+ renderComponent({ onChange, optionName: 'differentOption' });+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'opt3' } });+ expect(onChange).toHaveBeenCalledWith('differentOption', 'opt3');+ });++ it('calls onChange each time the value changes', () => {+ const onChange = jest.fn();+ renderComponent({ onChange });+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'opt2' } });+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'opt3' } });+ expect(onChange).toHaveBeenCalledTimes(2);+ });+ });});diff --git a/web/js/components/util/swipe-to-delete.test.js b/web/js/components/util/swipe-to-delete.test.jsindex 7c14efe88..ccbad848e 100644--- a/web/js/components/util/swipe-to-delete.test.js+++ b/web/js/components/util/swipe-to-delete.test.js@@ -1,3 +1,336 @@-test('swipe-to-delete component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import SwipeToDelete from './swipe-to-delete';+// JSDOM 26.x ships without PointerEvent. Without this polyfill, fireEvent falls+// back to a plain Event whose pointerId is always undefined, causing the+// pointerIdRef mismatch that silently swallows onPointerUp/onPointerCancel calls.+if (typeof PointerEvent === 'undefined') {+ class PointerEventPolyfill extends MouseEvent {+ constructor(type, params = {}) {+ super(type, params);+ this.pointerId = params.pointerId ?? 0;+ this.width = params.width ?? 1;+ this.height = params.height ?? 1;+ this.pressure = params.pressure ?? 0;+ this.tangentialPressure = params.tangentialPressure ?? 0;+ this.tiltX = params.tiltX ?? 0;+ this.tiltY = params.tiltY ?? 0;+ this.twist = params.twist ?? 0;+ this.pointerType = params.pointerType ?? '';+ this.isPrimary = params.isPrimary ?? false;+ }+ }+ global.PointerEvent = PointerEventPolyfill;+}++const defaultProps = {+ children: <span>child content</span>,+ onDelete: jest.fn(),+ item: { id: 1 },+ deleteSwipe: 0.33,+};++const renderComponent = (props = {}) => {+ const merged = { ...defaultProps, ...props };+ const result = render(<SwipeToDelete {...merged}>{merged.children}</SwipeToDelete>);+ const div = result.container.firstChild;+ div.getBoundingClientRect = jest.fn(() => ({ width: 300 }));+ div.setPointerCapture = jest.fn();+ return { ...result, div };+};++// RTL v16 no longer wraps fireEvent in act(), so React 19 state updates+// (setTranslateX, setIsDragging) are not flushed before assertions run.+// Wrapping each helper in act() ensures the DOM reflects state after every event.+const pdown = (el, x, y, id = 1) => {+ act(() => { fireEvent.pointerDown(el, { pointerId: id, clientX: x, clientY: y }); });+};+const pmove = (el, x, y, id = 1) => {+ act(() => { fireEvent.pointerMove(el, { pointerId: id, clientX: x, clientY: y }); });+};+const pup = (el, id = 1) => act(() => { fireEvent.pointerUp(el, { pointerId: id }); });+const pcancel = (el, id = 1) => act(() => { fireEvent.pointerCancel(el, { pointerId: id }); });++beforeEach(() => {+ jest.clearAllMocks();+});++describe('SwipeToDelete', () => {+ describe('rendering', () => {+ it('renders children', () => {+ const { getByText } = renderComponent();+ expect(getByText('child content')).toBeInTheDocument();+ });++ it('renders a div wrapper', () => {+ const { div } = renderComponent();+ expect(div.tagName).toBe('DIV');+ });++ it('sets touchAction pan-y on the wrapper element', () => {+ const { div } = renderComponent();+ // toHaveStyle cannot verify touch-action via getComputedStyle in JSDOM+ expect(div.style.touchAction).toBe('pan-y');+ });++ it('starts with translateX(0px) transform', () => {+ const { div } = renderComponent();+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });++ it('starts with ease-out transition when not dragging', () => {+ const { div } = renderComponent();+ expect(div).toHaveStyle({ transition: 'transform 150ms ease-out' });+ });+ });++ describe('onPointerDown', () => {+ it('calls setPointerCapture with the pointer id', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0, 1);+ expect(div.setPointerCapture).toHaveBeenCalledWith(1);+ });++ it('ignores a second pointer while one is already tracked', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0, 1);+ pdown(div, 50, 0, 2);+ pmove(div, 100, 0, 2); // second pointer — ignored+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });++ it('does not throw when setPointerCapture is absent on the element', () => {+ const { div } = renderComponent();+ delete div.setPointerCapture;+ expect(() => pdown(div, 0, 0)).not.toThrow();+ });+ });++ describe('onPointerMove — jitter threshold', () => {+ it('ignores tiny movements (< 10px on both axes)', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, 5, 5);+ expect(div).toHaveStyle({ transform: 'translateX(0px)', transition: 'transform 150ms ease-out' });+ });++ it('ignores move events from a different pointer id', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0, 1);+ pmove(div, -50, 0, 2);+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });+ });++ describe('onPointerMove — horizontal swipe', () => {+ it('sets transition to "none" while dragging horizontally', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -20, 0);+ expect(div).toHaveStyle({ transition: 'none' });+ });++ it('updates translateX for a left swipe', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ expect(div).toHaveStyle({ transform: 'translateX(-50px)' });+ });++ it('clamps a right swipe to translateX(0px)', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, 50, 0);+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });++ it('calls e.preventDefault when the move event is cancelable', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -20, 0); // decide direction as horizontal first+ const moveEvent = new PointerEvent('pointermove', {+ pointerId: 1,+ clientX: -40,+ clientY: 0,+ cancelable: true,+ bubbles: true,+ });+ const preventSpy = jest.spyOn(moveEvent, 'preventDefault');+ act(() => { div.dispatchEvent(moveEvent); });+ expect(preventSpy).toHaveBeenCalled();+ });++ it('does not call e.preventDefault when the move event is not cancelable', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -20, 0);+ const moveEvent = new PointerEvent('pointermove', {+ pointerId: 1,+ clientX: -40,+ clientY: 0,+ cancelable: false,+ bubbles: true,+ });+ const preventSpy = jest.spyOn(moveEvent, 'preventDefault');+ act(() => { div.dispatchEvent(moveEvent); });+ expect(preventSpy).not.toHaveBeenCalled();+ });+ });++ describe('onPointerMove — vertical swipe', () => {+ it('does not translate when swipe is vertical', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, 0, 50);+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });++ it('does not set isDragging when swipe is vertical', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, 0, 50);+ expect(div).toHaveStyle({ transition: 'transform 150ms ease-out' });+ });+ });++ describe('onPointerUp — delete threshold', () => {+ it('calls onDelete when left swipe meets the threshold', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete, item: { id: 42 } });+ pdown(div, 0, 0);+ pmove(div, -100, 0); // |-100| = 100 >= 99+ pup(div);+ expect(onDelete).toHaveBeenCalledWith({ id: 42 });+ });++ it('does not call onDelete when swipe is below the threshold', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ pdown(div, 0, 0);+ pmove(div, -50, 0); // |-50| = 50 < 99+ pup(div);+ expect(onDelete).not.toHaveBeenCalled();+ });++ it('does not call onDelete for a vertical swipe', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ pdown(div, 0, 0);+ pmove(div, 0, 200);+ pup(div);+ expect(onDelete).not.toHaveBeenCalled();+ });++ it('does not call onDelete when getBoundingClientRect returns zero width', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ div.getBoundingClientRect = jest.fn(() => ({ width: 0 }));+ pdown(div, 0, 0);+ pmove(div, -300, 0);+ pup(div);+ expect(onDelete).not.toHaveBeenCalled();+ });++ it('does not call onDelete when deleteSwipe is 0', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete, deleteSwipe: 0 });+ pdown(div, 0, 0);+ pmove(div, -300, 0);+ pup(div);+ expect(onDelete).not.toHaveBeenCalled();+ });++ it('does not throw when onDelete is null', () => {+ const { div } = renderComponent({ onDelete: null });+ pdown(div, 0, 0);+ pmove(div, -200, 0);+ expect(() => pup(div)).not.toThrow();+ });++ it('resets translateX to 0 after pointer up', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ pup(div);+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });++ it('restores ease-out transition after pointer up', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ pup(div);+ expect(div).toHaveStyle({ transition: 'transform 150ms ease-out' });+ });++ it('ignores pointer up from a different pointer id', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ pdown(div, 0, 0, 1);+ pmove(div, -200, 0, 1);+ pup(div, 2); // wrong id — no delete+ expect(onDelete).not.toHaveBeenCalled();+ });++ it('allows a new gesture after one completes', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ pup(div); // below threshold+ pdown(div, 0, 0);+ pmove(div, -100, 0);+ pup(div); // above threshold+ expect(onDelete).toHaveBeenCalledTimes(1);+ });+ });++ describe('onPointerCancel', () => {+ it('resets translateX to 0 on cancel', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ pcancel(div);+ expect(div).toHaveStyle({ transform: 'translateX(0px)' });+ });++ it('restores ease-out transition on cancel', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ pcancel(div);+ expect(div).toHaveStyle({ transition: 'transform 150ms ease-out' });+ });++ it('ignores cancel from a different pointer id', () => {+ const { div } = renderComponent();+ pdown(div, 0, 0, 1);+ pmove(div, -50, 0, 1);+ pcancel(div, 2); // wrong id — gesture stays live+ expect(div).toHaveStyle({ transform: 'translateX(-50px)' });+ });++ it('does not call onDelete on cancel even when swipe exceeds threshold', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ pdown(div, 0, 0);+ pmove(div, -200, 0);+ pcancel(div);+ expect(onDelete).not.toHaveBeenCalled();+ });++ it('allows a new gesture after cancel', () => {+ const onDelete = jest.fn();+ const { div } = renderComponent({ onDelete });+ pdown(div, 0, 0);+ pmove(div, -50, 0);+ pcancel(div);+ pdown(div, 0, 0);+ pmove(div, -200, 0);+ pup(div);+ expect(onDelete).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/web/js/components/util/switch.test.js b/web/js/components/util/switch.test.jsindex a0b65c583..a32591da0 100644--- a/web/js/components/util/switch.test.js+++ b/web/js/components/util/switch.test.js@@ -1,3 +1,262 @@-test('switch component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import Switch from './switch';+jest.mock('reactstrap', () => ({+ Tooltip: ({+ children, isOpen, target, toggle, id,+ }) => (+ <div data-testid="tooltip-wrapper" id={id} aria-describedby={target}>+ {isOpen && <div data-testid="tooltip-content">{children}</div>}+ <button type="button" data-testid="tooltip-toggle" onClick={toggle}>toggle</button>+ </div>+ ),+}));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon, id, tabIndex }) => (+ <span data-testid={`fa-${icon}`} id={id} tabIndex={tabIndex} />+ ),+}));++const defaultProps = {+ id: 'test-switch',+ active: false,+ toggle: jest.fn(),+ label: 'Test Label',+};++const renderComponent = (props = {}) => render(+ <Switch {...defaultProps} {...props} />,+);++beforeEach(() => {+ jest.useFakeTimers();+ jest.clearAllMocks();+});++afterEach(() => {+ jest.runAllTimers();+ jest.useRealTimers();+});++describe('Switch', () => {+ describe('rendering', () => {+ it('renders the container div with react-switch class', () => {+ const { container } = renderComponent();+ expect(container.querySelector('.react-switch')).toBeInTheDocument();+ });++ it('renders the checkbox input', () => {+ renderComponent();+ expect(screen.getByRole('checkbox')).toBeInTheDocument();+ });++ it('applies the id prop to the checkbox input', () => {+ renderComponent({ id: 'my-switch' });+ expect(document.getElementById('my-switch')).toBeInTheDocument();+ });++ it('renders the label text', () => {+ renderComponent({ label: 'My Label' });+ expect(screen.getByText('My Label')).toBeInTheDocument();+ });++ it('checkbox is unchecked when active=false', () => {+ renderComponent({ active: false });+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ });++ it('checkbox is checked when active=true', () => {+ renderComponent({ active: true });+ expect(screen.getByRole('checkbox')).toBeChecked();+ });++ it('span has aria-checked=false when active=false', () => {+ renderComponent({ active: false });+ expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false');+ });++ it('span has aria-checked=true when active=true', () => {+ renderComponent({ active: true });+ expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'true');+ });+ });++ describe('containerClass', () => {+ it('includes react-switch by default', () => {+ const { container } = renderComponent();+ expect(container.querySelector('.react-switch')).toBeInTheDocument();+ });++ it('appends containerClassAddition when provided', () => {+ const { container } = renderComponent({ containerClassAddition: 'extra-class' });+ expect(container.querySelector('.extra-class')).toBeInTheDocument();+ });++ it('adds switch-thin-border class when border=true', () => {+ const { container } = renderComponent({ border: true });+ expect(container.querySelector('.switch-thin-border')).toBeInTheDocument();+ });++ it('does not add switch-thin-border class when border=false', () => {+ const { container } = renderComponent({ border: false });+ expect(container.querySelector('.switch-thin-border')).not.toBeInTheDocument();+ });+ });++ describe('color / style', () => {+ it('applies background color style when active=true and color is set', () => {+ renderComponent({ active: true, color: 'FF0000' });+ const label = document.querySelector('label.react-switch-label');+ expect(label).toHaveStyle({ backgroundColor: '#FF0000' });+ });++ it('applies default color #007BFF when active=true and no color prop', () => {+ renderComponent({ active: true });+ const label = document.querySelector('label.react-switch-label');+ expect(label).toHaveStyle({ backgroundColor: '#007BFF' });+ });++ it('does not apply background color style when active=false', () => {+ renderComponent({ active: false, color: 'FF0000' });+ const label = document.querySelector('label.react-switch-label');+ expect(label).not.toHaveStyle({ backgroundColor: '#FF0000' });+ });+ });++ describe('toggleSwitch via checkbox', () => {+ it('calls toggle prop after 200ms when checkbox changes', () => {+ const toggle = jest.fn();+ renderComponent({ toggle });+ act(() => { fireEvent.click(screen.getByRole('checkbox')); });+ expect(toggle).not.toHaveBeenCalled();+ act(() => { jest.advanceTimersByTime(200); });+ expect(toggle).toHaveBeenCalledTimes(1);+ });++ it('does not call toggle before 200ms', () => {+ const toggle = jest.fn();+ renderComponent({ toggle });+ act(() => { fireEvent.click(screen.getByRole('checkbox')); });+ act(() => { jest.advanceTimersByTime(199); });+ expect(toggle).not.toHaveBeenCalled();+ });++ it('flips the checked state immediately when checkbox changes', () => {+ renderComponent({ active: false });+ act(() => { fireEvent.click(screen.getByRole('checkbox')); });+ expect(screen.getByRole('checkbox')).toBeChecked();+ });++ it('flips checked state from true to false', () => {+ renderComponent({ active: true });+ act(() => { fireEvent.click(screen.getByRole('checkbox')); });+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ });+ });++ describe('toggleSwitch via label span', () => {+ it('calls toggle prop after 200ms when label text span is clicked', () => {+ const toggle = jest.fn();+ renderComponent({ toggle });+ act(() => { fireEvent.click(screen.getByRole('switch')); });+ expect(toggle).not.toHaveBeenCalled();+ act(() => { jest.advanceTimersByTime(200); });+ expect(toggle).toHaveBeenCalledTimes(1);+ });++ it('flips checked state when label text span is clicked', () => {+ renderComponent({ active: true });+ act(() => { fireEvent.click(screen.getByRole('switch')); });+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ });+ });++ describe('onKeyDown', () => {+ it('calls toggleSwitch on Enter key (keyCode 13)', () => {+ const toggle = jest.fn();+ renderComponent({ toggle });+ const label = document.querySelector('label.react-switch-label');+ act(() => { fireEvent.keyDown(label, { keyCode: 13 }); });+ act(() => { jest.advanceTimersByTime(200); });+ expect(toggle).toHaveBeenCalledTimes(1);+ });++ it('does not call toggleSwitch on other keys', () => {+ const toggle = jest.fn();+ renderComponent({ toggle });+ const label = document.querySelector('label.react-switch-label');+ act(() => { fireEvent.keyDown(label, { keyCode: 32 }); });+ act(() => { jest.advanceTimersByTime(200); });+ expect(toggle).not.toHaveBeenCalled();+ });++ it('flips checked state on Enter key press', () => {+ renderComponent({ active: false });+ const label = document.querySelector('label.react-switch-label');+ act(() => { fireEvent.keyDown(label, { keyCode: 13 }); });+ expect(screen.getByRole('checkbox')).toBeChecked();+ });+ });++ describe('useEffect — active prop sync', () => {+ it('updates checkbox to checked when active prop changes to true', () => {+ const { rerender } = renderComponent({ active: false });+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ act(() => { rerender(<Switch {...defaultProps} active />); });+ expect(screen.getByRole('checkbox')).toBeChecked();+ });++ it('updates checkbox to unchecked when active prop changes to false', () => {+ const { rerender } = renderComponent({ active: true });+ expect(screen.getByRole('checkbox')).toBeChecked();+ act(() => { rerender(<Switch {...defaultProps} active={false} />); });+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ });+ });++ describe('tooltip', () => {+ it('does not render the info-circle icon when tooltip prop is absent', () => {+ renderComponent();+ expect(screen.queryByTestId('fa-info-circle')).not.toBeInTheDocument();+ });++ it('renders the info-circle icon when tooltip prop is provided', () => {+ renderComponent({ tooltip: 'Helpful hint' });+ expect(screen.getByTestId('fa-info-circle')).toBeInTheDocument();+ });++ it('info-circle icon id is "<id>-switch-tooltip"', () => {+ renderComponent({ id: 'my-switch', tooltip: 'Hint' });+ expect(document.getElementById('my-switch-switch-tooltip')).toBeInTheDocument();+ });++ it('tooltip content is not visible by default', () => {+ renderComponent({ tooltip: 'Helpful hint' });+ expect(screen.queryByTestId('tooltip-content')).not.toBeInTheDocument();+ });++ it('tooltip content becomes visible after its toggle button is clicked', () => {+ renderComponent({ tooltip: 'Helpful hint' });+ act(() => { fireEvent.click(screen.getByTestId('tooltip-toggle')); });+ expect(screen.getByTestId('tooltip-content')).toBeInTheDocument();+ });++ it('tooltip content text is rendered when tooltip is open', () => {+ renderComponent({ tooltip: 'My tooltip text' });+ act(() => { fireEvent.click(screen.getByTestId('tooltip-toggle')); });+ expect(screen.getByText('My tooltip text')).toBeInTheDocument();+ });++ it('tooltip closes again after a second toggle click', () => {+ renderComponent({ tooltip: 'Helpful hint' });+ act(() => { fireEvent.click(screen.getByTestId('tooltip-toggle')); });+ expect(screen.getByTestId('tooltip-content')).toBeInTheDocument();+ act(() => { fireEvent.click(screen.getByTestId('tooltip-toggle')); });+ expect(screen.queryByTestId('tooltip-content')).not.toBeInTheDocument();+ });+ });});diff --git a/web/js/components/util/visibility-sensor.test.js b/web/js/components/util/visibility-sensor.test.jsindex e47290aa7..ca970da8d 100644--- a/web/js/components/util/visibility-sensor.test.js+++ b/web/js/components/util/visibility-sensor.test.js@@ -1,3 +1,217 @@-test('visibility-sensor component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import VisibilitySensor from './visibility-sensor';+// Helpers to capture and fire IntersectionObserver callbacks+let observerCallback;+let observerOptions;+let observeTarget;+const mockDisconnect = jest.fn();+const mockObserve = jest.fn((el) => { observeTarget = el; });++function MockIntersectionObserver(cb, options) {+ observerCallback = cb;+ observerOptions = options;+ return { observe: mockObserve, disconnect: mockDisconnect };+}++function fireIntersection(isIntersecting) {+ act(() => {+ observerCallback([{ isIntersecting }]);+ });+}++const defaultProps = {+ children: <span data-testid="child">child</span>,+};++const renderComponent = (props = {}) => render(+ <VisibilitySensor {...defaultProps} {...props} />,+);++beforeEach(() => {+ observerCallback = null;+ observerOptions = null;+ observeTarget = null;+ mockDisconnect.mockClear();+ mockObserve.mockClear();+ global.IntersectionObserver = MockIntersectionObserver;+});++afterEach(() => {+ delete global.IntersectionObserver;+});++describe('VisibilitySensor', () => {+ describe('rendering', () => {+ it('renders a wrapper div with display:contents style', () => {+ const { container } = renderComponent();+ const wrapper = container.firstChild;+ expect(wrapper.tagName).toBe('DIV');+ expect(wrapper).toHaveStyle({ display: 'contents' });+ });++ it('renders node children', () => {+ renderComponent();+ expect(screen.getByTestId('child')).toBeInTheDocument();+ });++ it('renders function children, passing isVisible', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="fn-child">{isVisible ? 'visible' : 'hidden'}</span>+ ),+ });+ expect(screen.getByTestId('fn-child')).toHaveTextContent('hidden');+ });+ });++ describe('IntersectionObserver setup', () => {+ it('creates an IntersectionObserver and observes the container element', () => {+ const { container } = renderComponent();+ expect(mockObserve).toHaveBeenCalledTimes(1);+ expect(observeTarget).toBe(container.firstChild);+ });++ it('uses threshold=1 by default (partialVisibility=false)', () => {+ renderComponent();+ expect(observerOptions.threshold).toBe(1);+ });++ it('uses threshold=0 when partialVisibility=true', () => {+ renderComponent({ partialVisibility: true });+ expect(observerOptions.threshold).toBe(0);+ });++ it('uses root=null by default (containment not provided)', () => {+ renderComponent();+ expect(observerOptions.root).toBeNull();+ });++ it('uses the provided containment element as root', () => {+ const containment = document.createElement('div');+ renderComponent({ containment });+ expect(observerOptions.root).toBe(containment);+ });++ it('disconnects the observer on unmount', () => {+ const { unmount } = renderComponent();+ unmount();+ expect(mockDisconnect).toHaveBeenCalledTimes(1);+ });+ });++ describe('visibility state', () => {+ it('isVisible starts as false', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="state">{String(isVisible)}</span>+ ),+ });+ expect(screen.getByTestId('state')).toHaveTextContent('false');+ });++ it('sets isVisible=true when entry.isIntersecting=true', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="state">{String(isVisible)}</span>+ ),+ });+ fireIntersection(true);+ expect(screen.getByTestId('state')).toHaveTextContent('true');+ });++ it('sets isVisible=false when entry.isIntersecting=false', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="state">{String(isVisible)}</span>+ ),+ });+ fireIntersection(true);+ fireIntersection(false);+ expect(screen.getByTestId('state')).toHaveTextContent('false');+ });++ it('passes updated isVisible to function children', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="fn-child">{isVisible ? 'visible' : 'hidden'}</span>+ ),+ });+ expect(screen.getByTestId('fn-child')).toHaveTextContent('hidden');+ fireIntersection(true);+ expect(screen.getByTestId('fn-child')).toHaveTextContent('visible');+ });+ });++ describe('IntersectionObserver callback edge cases', () => {+ it('handles empty entries array gracefully (isVisible stays false)', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="state">{String(isVisible)}</span>+ ),+ });+ act(() => { observerCallback([]); });+ expect(screen.getByTestId('state')).toHaveTextContent('false');+ });++ it('handles null entries gracefully', () => {+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="state">{String(isVisible)}</span>+ ),+ });+ act(() => { observerCallback(null); });+ expect(screen.getByTestId('state')).toHaveTextContent('false');+ });+ });++ describe('fallback when IntersectionObserver is unavailable', () => {+ it('sets isVisible=true immediately when IntersectionObserver is undefined', () => {+ delete global.IntersectionObserver;+ renderComponent({+ children: ({ isVisible }) => (+ <span data-testid="state">{String(isVisible)}</span>+ ),+ });+ expect(screen.getByTestId('state')).toHaveTextContent('true');+ });++ it('does not throw when IntersectionObserver is unavailable', () => {+ delete global.IntersectionObserver;+ expect(() => renderComponent()).not.toThrow();+ });+ });++ describe('re-render on prop changes', () => {+ it('recreates the observer when partialVisibility changes', () => {+ const { rerender } = renderComponent({ partialVisibility: false });+ expect(observerOptions.threshold).toBe(1);+ act(() => {+ rerender(+ <VisibilitySensor partialVisibility>+ <span>child</span>+ </VisibilitySensor>,+ );+ });+ expect(observerOptions.threshold).toBe(0);+ });++ it('recreates the observer when containment changes', () => {+ const root1 = document.createElement('div');+ const root2 = document.createElement('div');+ const { rerender } = renderComponent({ containment: root1 });+ expect(observerOptions.root).toBe(root1);+ act(() => {+ rerender(+ <VisibilitySensor containment={root2}>+ <span>child</span>+ </VisibilitySensor>,+ );+ });+ expect(observerOptions.root).toBe(root2);+ expect(mockDisconnect).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/web/js/components/util/wait.test.js b/web/js/components/util/wait.test.jsindex 577aec57c..4a978ae36 100644--- a/web/js/components/util/wait.test.js+++ b/web/js/components/util/wait.test.js@@ -1,3 +1,112 @@-test('wait component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import Wait from './wait';+jest.mock('./button', () => function MockButton({ text, onClick, id, className }) {+ return (+ <button+ type="button"+ data-testid="cancel-button"+ id={id}+ className={className}+ onClick={onClick}+ >+ {text}+ </button>+ );+});++const defaultProps = {+ statusText: 'Loading...',+ onCancel: jest.fn(),+};++const renderComponent = (props = {}) => render(+ <Wait {...defaultProps} {...props} />,+);++beforeEach(() => {+ jest.clearAllMocks();+});++describe('Wait', () => {+ describe('portal target', () => {+ it('renders into .wv-content when it exists in the document', () => {+ const wvContent = document.createElement('div');+ wvContent.className = 'wv-content';+ document.body.appendChild(wvContent);++ renderComponent();++ expect(wvContent.querySelector('.wv-wait-progress-overlay')).toBeInTheDocument();++ wvContent.remove();+ });++ it('falls back to document.body when .wv-content does not exist', () => {+ renderComponent();+ expect(document.body.querySelector('.wv-wait-progress-overlay')).toBeInTheDocument();+ });+ });++ describe('structure', () => {+ it('renders the overlay wrapper', () => {+ const { baseElement } = renderComponent();+ expect(baseElement.querySelector('.wv-wait-progress-overlay')).toBeInTheDocument();+ });++ it('renders an open dialog element', () => {+ renderComponent();+ const dialog = document.querySelector('.wv-wait-progress-dialog');+ expect(dialog).toBeInTheDocument();+ expect(dialog).toHaveAttribute('open');+ });++ it('renders the progress message container', () => {+ renderComponent();+ expect(document.querySelector('.wv-wait-progress-message')).toBeInTheDocument();+ });++ it('renders statusText inside the message span', () => {+ renderComponent({ statusText: 'Please wait...' });+ expect(screen.getByText('Please wait...')).toBeInTheDocument();+ });++ it('renders empty statusText when not provided', () => {+ renderComponent({ statusText: '' });+ expect(document.querySelector('.wv-wait-progress-message span').textContent).toBe('');+ });+ });++ describe('Cancel button — complete=false (default)', () => {+ it('renders the Cancel button when complete=false', () => {+ renderComponent({ complete: false });+ expect(screen.getByTestId('cancel-button')).toBeInTheDocument();+ });++ it('Cancel button has id="wv-wait-cancel-button"', () => {+ renderComponent({ complete: false });+ expect(document.getElementById('wv-wait-cancel-button')).toBeInTheDocument();+ });++ it('Cancel button has class "wv-button gray"', () => {+ renderComponent({ complete: false });+ expect(screen.getByTestId('cancel-button')).toHaveClass('wv-button', 'gray');+ });++ it('calls onCancel when Cancel button is clicked', () => {+ const onCancel = jest.fn();+ renderComponent({ complete: false, onCancel });+ fireEvent.click(screen.getByTestId('cancel-button'));+ expect(onCancel).toHaveBeenCalledTimes(1);+ });+ });++ describe('Cancel button — complete=true', () => {+ it('does not render the Cancel button when complete=true', () => {+ renderComponent({ complete: true });+ expect(screen.queryByTestId('cancel-button')).not.toBeInTheDocument();+ });+ });});diff --git a/web/js/components/vector-metadata/table.test.js b/web/js/components/vector-metadata/table.test.jsindex 8311b71db..f9c9eece3 100644--- a/web/js/components/vector-metadata/table.test.js+++ b/web/js/components/vector-metadata/table.test.js@@ -1,10 +1,18 @@+/* eslint-disable react/prop-types */import { act } from 'react';import renderer from 'react-test-renderer';+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';import VectorMetaTable from './table';+// Isolate VectorMetaTooltip so Description-branch tests don't pull in fontawesome/reactstrap+jest.mock('./tooltip', () => function MockVectorMetaTooltip({ id, description }) {+ return <span data-testid="vector-tooltip" data-id={id}>{description}</span>;+});++// ─── keep console quiet about react-test-renderer deprecation ────────────────let consoleErrorSpy;let originalConsoleError;-beforeAll(() => {originalConsoleError = console.error;consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation((...args) => {@@ -12,20 +20,18 @@ beforeAll(() => {originalConsoleError.call(console, ...args);});});-afterAll(() => {if (consoleErrorSpy) consoleErrorSpy.mockRestore();});+// ─── snapshot tests (existing) ───────────────────────────────────────────────let component;beforeEach(() => {act(() => {component = renderer.create(<VectorMetaTablemetaArray={[{- features: {- GRAND_ID: 4886,- },+ features: { GRAND_ID: 4886 },legend: [{ Identifier: 'GRAND_ID' }],featureTitle: 'Choclococha',}]}@@ -37,22 +43,16 @@ beforeEach(() => {test('Check that there is not popup', () => {expect(component.toJSON()).toMatchSnapshot();});+test('If there is a valuemap, use valuemap', () => {act(() => {component = renderer.create(<VectorMetaTablemetaArray={[{- features: {- GRAND_ID: 4886,- Urborrur: 'U',- },+ features: { GRAND_ID: 4886, Urborrur: 'U' },legend: [- {- Identifier: 'GRAND_ID',- }, {- Identifier: 'Urborrur',- ValueMap: { U: 'Urban', R: 'Rural' },- },+ { Identifier: 'GRAND_ID' },+ { Identifier: 'Urborrur', ValueMap: { U: 'Urban', R: 'Rural' } },],featureTitle: 'Choclococha',}]}@@ -61,3 +61,241 @@ test('If there is a valuemap, use valuemap', () => {});expect(component.toJSON()).toMatchSnapshot();});++// ─── shouldComponentUpdate ───────────────────────────────────────────────────+describe('shouldComponentUpdate', () => {+ const baseMetaArray = (val) => [{+ features: { NAME: val },+ legend: [{ Identifier: 'NAME' }],+ featureTitle: 'Feature',+ }];++ it('prevents re-render when id and title both match', () => {+ const { rerender } = render(+ <VectorMetaTable id={1} title="dam" metaArray={baseMetaArray('Alpha')} />,+ );+ expect(screen.getByText('Alpha')).toBeInTheDocument();++ rerender(<VectorMetaTable id={1} title="dam" metaArray={baseMetaArray('Beta')} />);+ // shouldComponentUpdate returned false — output unchanged+ expect(screen.getByText('Alpha')).toBeInTheDocument();+ expect(screen.queryByText('Beta')).not.toBeInTheDocument();+ });++ it('allows re-render when id changes', () => {+ const { rerender } = render(+ <VectorMetaTable id={1} title="dam" metaArray={baseMetaArray('Alpha')} />,+ );+ rerender(<VectorMetaTable id={2} title="dam" metaArray={baseMetaArray('Beta')} />);+ expect(screen.getByText('Beta')).toBeInTheDocument();+ });++ it('allows re-render when title changes', () => {+ const { rerender } = render(+ <VectorMetaTable id={1} title="dam" metaArray={baseMetaArray('Alpha')} />,+ );+ rerender(<VectorMetaTable id={1} title="lake" metaArray={baseMetaArray('Beta')} />);+ expect(screen.getByText('Beta')).toBeInTheDocument();+ });++ it('allows re-render when id is not set', () => {+ const { rerender } = render(+ <VectorMetaTable title="dam" metaArray={baseMetaArray('Alpha')} />,+ );+ rerender(<VectorMetaTable title="dam" metaArray={baseMetaArray('Beta')} />);+ expect(screen.getByText('Beta')).toBeInTheDocument();+ });++ it('allows re-render when title is not set', () => {+ const { rerender } = render(+ <VectorMetaTable id={1} metaArray={baseMetaArray('Alpha')} />,+ );+ rerender(<VectorMetaTable id={1} metaArray={baseMetaArray('Beta')} />);+ expect(screen.getByText('Beta')).toBeInTheDocument();+ });+});++// ─── render branches ─────────────────────────────────────────────────────────+describe('VectorMetaTable render', () => {+ it('uses featureTitle as the table header', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { ID: 1 },+ legend: [{ Identifier: 'ID' }],+ featureTitle: 'My Dam',+ }]}+ />,+ );+ expect(screen.getByRole('columnheader')).toHaveTextContent('My Dam');+ });++ it('falls back to "obj.title <index+1>" when featureTitle is absent', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { ID: 1 },+ legend: [{ Identifier: 'ID' }],+ title: 'River',+ }]}+ />,+ );+ expect(screen.getByRole('columnheader')).toHaveTextContent('River 1');+ });++ it('renders the Identifier as cell label when Title is absent', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { GRAND_ID: 42 },+ legend: [{ Identifier: 'GRAND_ID' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.getByText('GRAND_ID')).toBeInTheDocument();+ });++ it('renders Title as cell label when Title is present', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { GRAND_ID: 42 },+ legend: [{ Identifier: 'GRAND_ID', Title: 'Dam ID' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.getByText('Dam ID')).toBeInTheDocument();+ });++ it('formats integer feature values with toLocaleString when DataType=int and Function≠Identify', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { AREA: 1234567 },+ legend: [{ Identifier: 'AREA', DataType: 'int', Function: 'Style' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.getByText((1234567).toLocaleString('en'))).toBeInTheDocument();+ });++ it('does not format integer when Function=Identify', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { AREA: 1234567 },+ legend: [{ Identifier: 'AREA', DataType: 'int', Function: 'Identify' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ // raw numeric value (not locale-formatted), rendered as-is via metaFeaturesIdentifierValue+ expect(screen.getByText('1234567')).toBeInTheDocument();+ });++ it('skips row entirely when feature value is null/missing', () => {+ const { container } = render(+ <VectorMetaTable+ metaArray={[{+ features: {},+ legend: [{ Identifier: 'MISSING_FIELD' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(container.querySelectorAll('tbody tr')).toHaveLength(0);+ });++ it('renders Description tooltip when Description is present', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { NAME: 'Foo' },+ legend: [{ Identifier: 'NAME', Description: 'The feature name' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.getByTestId('vector-tooltip')).toBeInTheDocument();+ expect(screen.getByTestId('vector-tooltip')).toHaveTextContent('The feature name');+ });++ it('does not render a Description tooltip when Description is absent', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { NAME: 'Foo' },+ legend: [{ Identifier: 'NAME' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.queryByTestId('vector-tooltip')).not.toBeInTheDocument();+ });++ it('renders Units next to the value when Units is set', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { AREA: 100 },+ legend: [{ Identifier: 'AREA', Units: 'km²' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.getByText('km²')).toBeInTheDocument();+ });++ it('does not render a Units span when Units is absent', () => {+ const { container } = render(+ <VectorMetaTable+ metaArray={[{+ features: { AREA: 100 },+ legend: [{ Identifier: 'AREA' }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ // Only one <span> (the value itself), no units span+ const spans = container.querySelectorAll('td span');+ expect(spans).toHaveLength(1);+ });++ it('renders multiple metaArray entries as separate tables', () => {+ render(+ <VectorMetaTable+ metaArray={[+ {+ features: { ID: 1 },+ legend: [{ Identifier: 'ID' }],+ featureTitle: 'Dam A',+ },+ {+ features: { ID: 2 },+ legend: [{ Identifier: 'ID' }],+ featureTitle: 'Dam B',+ },+ ]}+ />,+ );+ expect(screen.getByText('Dam A')).toBeInTheDocument();+ expect(screen.getByText('Dam B')).toBeInTheDocument();+ });++ it('renders ValueMap lookup value instead of raw feature value', () => {+ render(+ <VectorMetaTable+ metaArray={[{+ features: { STATUS: 'U' },+ legend: [{ Identifier: 'STATUS', ValueMap: { U: 'Urban', R: 'Rural' } }],+ featureTitle: 'Feature',+ }]}+ />,+ );+ expect(screen.getByText('Urban')).toBeInTheDocument();+ expect(screen.queryByText('U')).not.toBeInTheDocument();+ });+});diff --git a/web/js/components/vector-metadata/tooltip.test.js b/web/js/components/vector-metadata/tooltip.test.jsindex dcf728a69..0896d2f9a 100644--- a/web/js/components/vector-metadata/tooltip.test.js+++ b/web/js/components/vector-metadata/tooltip.test.js@@ -1,3 +1,127 @@-test('tooltip component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import VectorMetaTooltip from './tooltip';+jest.mock('reactstrap', () => ({+ Tooltip: ({+ isOpen, target, dangerouslySetInnerHTML, id, toggle,+ }) => (+ <div data-testid="tooltip-wrapper" data-open={String(isOpen)} data-target={target} id={id}>+ { }+ <div data-testid="tooltip" dangerouslySetInnerHTML={dangerouslySetInnerHTML} />+ <button type="button" data-testid="tooltip-toggle-btn" onClick={toggle}>toggle</button>+ </div>+ ),+}));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon, className }) => (+ <span data-testid={`fa-${icon}`} className={className} />+ ),+}));++jest.mock('../../util/util', () => ({+ __esModule: true,+ default: { cleanId: (str) => str.replace(/\W/g, '_') },+}));++const defaultProps = {+ id: 'row-0',+ index: 0,+ description: 'Feature description text',+};++const renderComponent = (props = {}) => render(+ <VectorMetaTooltip {...defaultProps} {...props} />,+);++describe('VectorMetaTooltip', () => {+ describe('rendering', () => {+ it('renders the outer container div', () => {+ const { container } = renderComponent();+ expect(container.querySelector('.vector-info-tooltip-case')).toBeInTheDocument();+ });++ it('renders the info icon', () => {+ renderComponent();+ expect(screen.getByTestId('fa-info')).toBeInTheDocument();+ });++ it('info icon has vector-info-icon class', () => {+ renderComponent();+ expect(screen.getByTestId('fa-info')).toHaveClass('vector-info-icon');+ });++ it('info icon has cursor-pointer class', () => {+ renderComponent();+ expect(screen.getByTestId('fa-info')).toHaveClass('cursor-pointer');+ });++ it('computes the element id from util.cleanId', () => {+ renderComponent({ id: 'row-1', index: 2 });+ // cleanId("tooltiprow-12") → "tooltiprow_12"+ expect(document.getElementById('tooltiprow_12')).toBeInTheDocument();+ });++ it('renders the Tooltip with the description via dangerouslySetInnerHTML', () => {+ renderComponent({ description: '<b>Bold description</b>' });+ const tooltip = screen.getByTestId('tooltip');+ expect(tooltip.innerHTML).toContain('<b>Bold description</b>');+ });++ it('Tooltip target matches the sub-case element id', () => {+ renderComponent({ id: 'row-0', index: 0 });+ const elId = 'tooltiprow_00';+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-target', elId);+ });+ });++ describe('initial state', () => {+ it('tooltip is closed by default', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'false');+ });+ });++ describe('mouseEnter', () => {+ it('opens the tooltip on mouseEnter', () => {+ renderComponent();+ fireEvent.mouseEnter(document.querySelector('.vector-info-tooltip-case'));+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'true');+ });+ });++ describe('mouseLeave', () => {+ it('closes the tooltip on mouseLeave', () => {+ renderComponent();+ fireEvent.mouseEnter(document.querySelector('.vector-info-tooltip-case'));+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'true');+ fireEvent.mouseLeave(document.querySelector('.vector-info-tooltip-case'));+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'false');+ });+ });++ describe('state transitions via mouse events', () => {+ it('full open/close cycle: enter → open, leave → closed, enter → open again', () => {+ renderComponent();+ const wrapper = document.querySelector('.vector-info-tooltip-case');+ fireEvent.mouseEnter(wrapper);+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'true');+ fireEvent.mouseLeave(wrapper);+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'false');+ fireEvent.mouseEnter(wrapper);+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'true');+ });++ it('re-render with new description does not reset open state', () => {+ const { rerender } = renderComponent({ description: 'First' });+ const wrapper = document.querySelector('.vector-info-tooltip-case');+ fireEvent.mouseEnter(wrapper);+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'true');+ rerender(<VectorMetaTooltip {...defaultProps} description="Second" />);+ expect(screen.getByTestId('tooltip-wrapper')).toHaveAttribute('data-open', 'true');+ });+ });});