Interactive interface for browsing global, full-resolution satellite imagery
Adding more web/js/components/ unit tests
Jason Hurleyd1ead5713a5e
diff --git a/web/js/components/layer/settings/layer-settings.test.js b/web/js/components/layer/settings/layer-settings.test.jsindex 794c891b9..02b53464b 100644--- a/web/js/components/layer/settings/layer-settings.test.js+++ b/web/js/components/layer/settings/layer-settings.test.js@@ -134,8 +134,48 @@ const renderSettings = (layer = standardLayer, propOverrides = {}) => render(</Provider>,);+import { fireEvent } from '@testing-library/react';++const singleLegend = {+ id: 'legend-1',+ title: 'Legend 1',+ type: 'continuous',+ colors: ['#ff0000', '#00ff00'],+ refs: ['ref0', 'ref1'],+};++const classificationLegend = {+ id: 'legend-class',+ title: 'Classification',+ type: 'classification',+ colors: ['#ff0000', '#00ff00'],+ refs: ['ref0', 'ref1'],+};++const singleColorClassLegend = {+ id: 'legend-single-class',+ title: 'Single Class',+ type: 'classification',+ colors: ['#ff0000'],+ refs: ['ref0'],+};++const unknownTypeLegend = {+ id: 'legend-unknown',+ title: 'Unknown',+ type: 'something-else',+ colors: ['#ff0000', '#00ff00'],+ refs: ['ref0', 'ref1'],+};++const basePalette = { legend: { colors: ['#ff0000', '#00ff00'] }, squash: false, noclip: false };+beforeEach(() => {jest.clearAllMocks();+ const { getPaletteLegends, getPalette, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue(null);+ getPalette.mockReturnValue(basePalette);+ getPaletteLegend.mockReturnValue(null);});describe('LayerSettings', () => {@@ -237,5 +277,148 @@ describe('LayerSettings', () => {renderSettings(standardLayer);expect(screen.queryByTestId('granule-count-slider')).not.toBeInTheDocument();});++ it('renders GranuleDateList when allowGranuleReorder is set in localStorage', () => {+ const { getItem } = require('../../../util/local-storage');+ getItem.mockReturnValue('true');+ const { getGranuleLayer } = require('../../../modules/layers/selectors');+ getGranuleLayer.mockReturnValue({ dates: ['2023-01-01'], count: 5 });+ renderSettings(standardLayer);+ expect(screen.getByTestId('granule-date-list')).toBeInTheDocument();+ });+ });++ describe('renderCustomPalettes — single palette', () => {+ it('renders Palette and PaletteThreshold for a continuous single legend', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([singleLegend]);+ getPaletteLegend.mockReturnValue(singleLegend);+ renderSettings(standardLayer);+ expect(screen.getByTestId('palette')).toBeInTheDocument();+ expect(screen.getByTestId('palette-threshold')).toBeInTheDocument();+ });++ it('renders ClassificationToggle for a classification legend with multiple colors', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([classificationLegend]);+ getPaletteLegend.mockReturnValue(classificationLegend);+ renderSettings(standardLayer);+ expect(screen.getByTestId('classification-toggle')).toBeInTheDocument();+ });++ it('does not render PaletteThreshold for a classification legend', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([classificationLegend]);+ getPaletteLegend.mockReturnValue(classificationLegend);+ renderSettings(standardLayer);+ expect(screen.queryByTestId('palette-threshold')).not.toBeInTheDocument();+ });++ it('does not render custom palettes when layer has no palette field', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([singleLegend]);+ getPaletteLegend.mockReturnValue(singleLegend);+ renderSettings({ ...standardLayer, palette: undefined });+ expect(screen.queryByTestId('palette')).not.toBeInTheDocument();+ });+ });++ describe('renderMultiColormapCustoms — multi-palette', () => {+ const multiLegends = [+ { ...singleLegend, id: 'leg-0', title: 'Band 1' },+ { ...singleLegend, id: 'leg-1', title: 'Band 2' },+ ];++ it('renders tabbed nav for multiple palettes (continuous)', () => {+ const { getPaletteLegends } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue(multiLegends);+ renderSettings(standardLayer);+ expect(screen.getByText('Band 1')).toBeInTheDocument();+ expect(screen.getByText('Band 2')).toBeInTheDocument();+ });++ it('switches active tab when nav link is clicked', () => {+ const { getPaletteLegends } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue(multiLegends);+ renderSettings(standardLayer);+ fireEvent.click(screen.getByText('Band 2'));+ // No crash and tab content still renders+ expect(screen.getByText('Band 2')).toBeInTheDocument();+ });++ it('renders ClassificationToggle tab for classification legend with multiple colors', () => {+ const { getPaletteLegends } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([+ { ...classificationLegend, id: 'leg-0', title: 'Class A' },+ { ...singleLegend, id: 'leg-1', title: 'Band B' },+ ]);+ renderSettings(standardLayer);+ expect(screen.getByTestId('classification-toggle')).toBeInTheDocument();+ });++ it('renders "No customizations available" tab for unknown palette type with multiple colors', () => {+ const { getPaletteLegends } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([+ { ...unknownTypeLegend, id: 'leg-0', title: 'Unknown A' },+ { ...singleLegend, id: 'leg-1', title: 'Band B' },+ ]);+ renderSettings(standardLayer);+ expect(screen.getByText('No customizations available for this palette.')).toBeInTheDocument();+ });+ });++ describe('vector layer customization', () => {+ const vectorLayer = {+ id: 'vector-layer-1',+ opacity: 1,+ type: 'vector',+ palette: { id: 'blue-1', recommended: [] },+ };++ it('does not render palette customizations for Orbital Track vector layers', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([singleLegend]);+ getPaletteLegend.mockReturnValue(singleLegend);+ renderSettings({ ...vectorLayer, layergroup: 'Orbital Track' });+ expect(screen.queryByTestId('palette')).not.toBeInTheDocument();+ });++ it('does not render palette customizations for Reference vector layers', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([singleLegend]);+ getPaletteLegend.mockReturnValue(singleLegend);+ renderSettings({ ...vectorLayer, layergroup: 'Reference' });+ expect(screen.queryByTestId('palette')).not.toBeInTheDocument();+ });++ it('renders palette customizations for non-restricted vector layers', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([singleLegend]);+ getPaletteLegend.mockReturnValue(singleLegend);+ renderSettings({ ...vectorLayer, layergroup: 'Science' });+ expect(screen.getByTestId('palette')).toBeInTheDocument();+ });++ it('does not render palette customizations when disableCustomPalettes is true', () => {+ const { getPaletteLegends, getPaletteLegend } = require('../../../modules/palettes/selectors');+ getPaletteLegends.mockReturnValue([singleLegend]);+ getPaletteLegend.mockReturnValue(singleLegend);+ renderSettings({ ...vectorLayer, layergroup: 'Science', disableCustomPalettes: true });+ expect(screen.queryByTestId('palette')).not.toBeInTheDocument();+ });+ });++ describe('AERONET classification layer', () => {+ it('renders ClassificationToggle for single-color AERONET classification legend in multi-palette tab', () => {+ const { getPaletteLegends } = require('../../../modules/palettes/selectors');+ // Two legends triggers renderMultiColormapCustoms;+ // AERONET id bypasses the colors.length > 1 guard+ getPaletteLegends.mockReturnValue([+ { ...singleColorClassLegend, id: 'leg-0', title: 'Leg 0' },+ { ...singleLegend, id: 'leg-1', title: 'Leg 1' },+ ]);+ renderSettings({ ...standardLayer, id: 'AERONET_AOD_500nm' });+ expect(screen.getByTestId('classification-toggle')).toBeInTheDocument();+ });});});diff --git a/web/js/components/location-search/coordinates-dialog.test.js b/web/js/components/location-search/coordinates-dialog.test.jsindex 7b96303b8..c22676eae 100644--- a/web/js/components/location-search/coordinates-dialog.test.js+++ b/web/js/components/location-search/coordinates-dialog.test.js@@ -1,3 +1,133 @@-test('coordinates-dialog component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import CoordinatesDialog from './coordinates-dialog';+jest.mock('copy-to-clipboard', () => jest.fn(() => Promise.resolve(true)));+jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon, onClick }) => (+ <span data-testid={`icon-${icon}`} onClick={onClick} />+ ),+}));+jest.mock('reactstrap', () => ({+ UncontrolledTooltip: ({ children }) => <div>{children}</div>,+}));+jest.mock('./copy-tooltip', () => function MockCopyTooltip({ tooltipToggleTime }) {+ return <div data-testid="copy-tooltip" data-toggle-time={tooltipToggleTime} />;+});+jest.mock('./util', () => ({+ getFormattedCoordinates: jest.fn(() => '34.0500, -118.2400'),+}));+jest.mock('../../util/util', () => ({+ events: {+ on: jest.fn(),+ off: jest.fn(),+ },+}));+jest.mock('../../util/constants', () => ({+ LOCATION_SEARCH_COORDINATE_FORMAT: 'location-search:coordinate-format',+}));++import copy from 'copy-to-clipboard';+import { getFormattedCoordinates } from './util';+import util from '../../util/util';++const defaultProps = {+ coordinates: [34.05, -118.24],+ title: 'Los Angeles, CA',+ removeMarker: jest.fn(),+ removeCoordinatesDialog: jest.fn(),+ isMobile: false,+ tooltipId: 'test-tooltip-id',+};++describe('CoordinatesDialog', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ getFormattedCoordinates.mockReturnValue('34.0500, -118.2400');+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ test('renders title and formatted coordinates', () => {+ const { getByText } = render(<CoordinatesDialog {...defaultProps} />);+ expect(getByText('Los Angeles, CA')).toBeInTheDocument();+ expect(getByText('34.0500, -118.2400')).toBeInTheDocument();+ });++ test('renders without title when title prop is undefined', () => {+ const { container } = render(<CoordinatesDialog {...defaultProps} title={undefined} />);+ const titleEl = container.querySelector('.tooltip-coordinates-title');+ expect(titleEl).toBeEmptyDOMElement();+ });++ test('registers and deregisters event listener for coordinate format changes', () => {+ const { unmount } = render(<CoordinatesDialog {...defaultProps} />);+ expect(util.events.on).toHaveBeenCalledWith(+ 'location-search:coordinate-format',+ expect.any(Function),+ );+ unmount();+ expect(util.events.off).toHaveBeenCalledWith(+ 'location-search:coordinate-format',+ expect.any(Function),+ );+ });++ test('calls getFormattedCoordinates on mount', () => {+ render(<CoordinatesDialog {...defaultProps} />);+ expect(getFormattedCoordinates).toHaveBeenCalledWith([34.05, -118.24]);+ });++ test('calls copy-to-clipboard and updates tooltipToggleTime when copy button is clicked', async () => {+ const { container } = render(<CoordinatesDialog {...defaultProps} />);+ act(() => {+ jest.advanceTimersByTime(200);+ });+ const copyBtn = container.querySelector('#copy-coordinates-to-clipboard-button');+ await act(async () => {+ fireEvent.click(copyBtn);+ await Promise.resolve();+ });+ expect(copy).toHaveBeenCalledWith('34.0500, -118.2400', { format: 'text/plain' });+ });++ test('calls removeMarker prop when close button icon is clicked', () => {+ const removeMarker = jest.fn();+ const { getByTestId } = render(+ <CoordinatesDialog {...defaultProps} removeMarker={removeMarker} />,+ );+ fireEvent.click(getByTestId('icon-times'));+ expect(removeMarker).toHaveBeenCalledTimes(1);+ });++ test('calls removeCoordinatesDialog when minimize button icon is clicked', () => {+ const removeCoordinatesDialog = jest.fn();+ const { getByTestId } = render(+ <CoordinatesDialog {...defaultProps} removeCoordinatesDialog={removeCoordinatesDialog} />,+ );+ fireEvent.click(getByTestId('icon-minus'));+ expect(removeCoordinatesDialog).toHaveBeenCalledTimes(1);+ });++ test('shows CopyClipboardTooltip after 200ms', () => {+ const { queryByTestId } = render(<CoordinatesDialog {...defaultProps} />);+ expect(queryByTestId('copy-tooltip')).not.toBeInTheDocument();+ act(() => {+ jest.advanceTimersByTime(200);+ });+ expect(queryByTestId('copy-tooltip')).toBeInTheDocument();+ });++ test('updateCoordinateFormat re-calls getFormattedCoordinates', () => {+ render(<CoordinatesDialog {...defaultProps} />);+ const formatEventHandler = util.events.on.mock.calls[0][1];+ getFormattedCoordinates.mockReturnValue('34°3\'0"N, 118°14\'24"W');+ act(() => { formatEventHandler(); });+ expect(getFormattedCoordinates).toHaveBeenCalledTimes(2);+ });});diff --git a/web/js/components/location-search/copy-tooltip.test.js b/web/js/components/location-search/copy-tooltip.test.jsindex bf52bd981..33206721d 100644--- a/web/js/components/location-search/copy-tooltip.test.js+++ b/web/js/components/location-search/copy-tooltip.test.js@@ -1,3 +1,106 @@-test('copy-tooltip component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import CopyClipboardTooltip from './copy-tooltip';+jest.mock('reactstrap', () => ({+ Tooltip: ({ children, isOpen }) => (+ <div data-testid="tooltip" data-is-open={String(isOpen)}>{children}</div>+ ),+}));++const defaultProps = {+ clearCopyToClipboardTooltip: jest.fn(),+ tooltipToggleTime: 0,+ placement: 'bottom',+};++describe('CopyClipboardTooltip', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ test('renders tooltip closed by default', () => {+ const { getByTestId } = render(<CopyClipboardTooltip {...defaultProps} />);+ expect(getByTestId('tooltip')).toHaveAttribute('data-is-open', 'false');+ });++ test('shows tooltip when tooltipToggleTime changes', () => {+ const { getByTestId, rerender } = render(<CopyClipboardTooltip {...defaultProps} />);+ rerender(<CopyClipboardTooltip {...defaultProps} tooltipToggleTime={1000} />);+ expect(getByTestId('tooltip')).toHaveAttribute('data-is-open', 'true');+ });++ test('displays "Copied to clipboard!" text', () => {+ const { getByTestId, rerender } = render(<CopyClipboardTooltip {...defaultProps} />);+ rerender(<CopyClipboardTooltip {...defaultProps} tooltipToggleTime={1000} />);+ expect(getByTestId('tooltip')).toHaveTextContent('Copied to clipboard!');+ });++ test('hides tooltip after 2 seconds and calls clearCopyToClipboardTooltip', () => {+ const clearMock = jest.fn();+ const { getByTestId, rerender } = render(+ <CopyClipboardTooltip {...defaultProps} clearCopyToClipboardTooltip={clearMock} />,+ );+ rerender(+ <CopyClipboardTooltip+ {...defaultProps}+ clearCopyToClipboardTooltip={clearMock}+ tooltipToggleTime={1000}+ />,+ );+ expect(getByTestId('tooltip')).toHaveAttribute('data-is-open', 'true');++ act(() => {+ jest.advanceTimersByTime(2000);+ });++ expect(clearMock).toHaveBeenCalledTimes(1);+ expect(getByTestId('tooltip')).toHaveAttribute('data-is-open', 'false');+ });++ test('does not show tooltip when tooltipToggleTime does not change', () => {+ const { getByTestId, rerender } = render(<CopyClipboardTooltip {...defaultProps} />);+ rerender(<CopyClipboardTooltip {...defaultProps} placement="top" />);+ expect(getByTestId('tooltip')).toHaveAttribute('data-is-open', 'false');+ });++ test('clears timeout on unmount', () => {+ const clearTimeoutSpy = jest.spyOn(global, 'clearTimeout');+ const { rerender, unmount } = render(<CopyClipboardTooltip {...defaultProps} />);+ rerender(<CopyClipboardTooltip {...defaultProps} tooltipToggleTime={1000} />);+ unmount();+ expect(clearTimeoutSpy).toHaveBeenCalled();+ clearTimeoutSpy.mockRestore();+ });++ test('resets tooltip visibility when tooltipToggleTime changes a second time', () => {+ const clearMock = jest.fn();+ const { getByTestId, rerender } = render(+ <CopyClipboardTooltip {...defaultProps} clearCopyToClipboardTooltip={clearMock} />,+ );+ rerender(+ <CopyClipboardTooltip+ {...defaultProps}+ clearCopyToClipboardTooltip={clearMock}+ tooltipToggleTime={1000}+ />,+ );+ act(() => { jest.advanceTimersByTime(1000); });++ rerender(+ <CopyClipboardTooltip+ {...defaultProps}+ clearCopyToClipboardTooltip={clearMock}+ tooltipToggleTime={2000}+ />,+ );+ expect(getByTestId('tooltip')).toHaveAttribute('data-is-open', 'true');+ });});diff --git a/web/js/components/location-search/location-marker.test.js b/web/js/components/location-search/location-marker.test.jsindex 186a4bdcb..b4b3498e2 100644--- a/web/js/components/location-search/location-marker.test.js+++ b/web/js/components/location-search/location-marker.test.js@@ -1,3 +1,132 @@-test('location-marker component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import LocationMarker from './location-marker';+jest.mock('./coordinates-dialog', () => function MockCoordinatesDialog({+ title, coordinates, removeMarker, removeCoordinatesDialog,+}) {+ return (+ <div data-testid="coordinates-dialog">+ <span data-testid="dialog-title">{title}</span>+ <span data-testid="dialog-coords">{coordinates.join(',')}</span>+ <button data-testid="remove-marker-btn" onClick={removeMarker}>remove</button>+ <button data-testid="minimize-btn" onClick={removeCoordinatesDialog}>minimize</button>+ </div>+ );+});++jest.mock('../../util/util', () => ({+ encodeId: jest.fn((str) => str.replace(/[.:,]/g, '_')),+}));++const baseProps = {+ coordinatesObject: { latitude: 34.05, longitude: -118.24 },+ reverseGeocodeResults: { address: null, error: null },+ removeMarker: jest.fn(),+ isMobile: false,+ dialogVisible: true,+};++describe('LocationMarker', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ test('renders dialog and pin image by default', () => {+ const { getByTestId } = render(<LocationMarker {...baseProps} />);+ expect(getByTestId('coordinates-dialog')).toBeInTheDocument();+ expect(document.querySelector('#marker-pin')).toBeInTheDocument();+ });++ test('passes latitude and longitude as coordinates to CoordinatesDialog', () => {+ const { getByTestId } = render(<LocationMarker {...baseProps} />);+ expect(getByTestId('dialog-coords')).toHaveTextContent('34.05,-118.24');+ });++ test('does not show dialog when dialogVisible is false', () => {+ const { queryByTestId } = render(+ <LocationMarker {...baseProps} dialogVisible={false} />,+ );+ expect(queryByTestId('coordinates-dialog')).not.toBeInTheDocument();+ });++ test('clicking pin image shows dialog after it was minimized', () => {+ const { getByTestId, queryByTestId } = render(+ <LocationMarker {...baseProps} dialogVisible={false} />,+ );+ expect(queryByTestId('coordinates-dialog')).not.toBeInTheDocument();+ fireEvent.click(document.querySelector('#marker-pin'));+ expect(getByTestId('coordinates-dialog')).toBeInTheDocument();+ });++ test('minimize button hides the dialog', () => {+ const { getByTestId, queryByTestId } = render(<LocationMarker {...baseProps} />);+ fireEvent.click(getByTestId('minimize-btn'));+ expect(queryByTestId('coordinates-dialog')).not.toBeInTheDocument();+ });++ test('remove marker button calls removeMarker prop', () => {+ const removeMarker = jest.fn();+ const { getByTestId } = render(+ <LocationMarker {...baseProps} removeMarker={removeMarker} />,+ );+ fireEvent.click(getByTestId('remove-marker-btn'));+ expect(removeMarker).toHaveBeenCalledTimes(1);+ });++ test('derives title from City and Region when both are present', () => {+ const props = {+ ...baseProps,+ reverseGeocodeResults: {+ address: {+ Match_addr: '123 Main St, Los Angeles, CA', City: 'Los Angeles', Region: 'CA', Subregion: null,+ },+ error: null,+ },+ };+ const { getByTestId } = render(<LocationMarker {...props} />);+ expect(getByTestId('dialog-title')).toHaveTextContent('Los Angeles, CA');+ });++ test('derives title from Subregion and Region when City is absent', () => {+ const props = {+ ...baseProps,+ reverseGeocodeResults: {+ address: {+ Match_addr: '123 Main St', City: null, Region: 'CA', Subregion: 'Los Angeles County',+ },+ error: null,+ },+ };+ const { getByTestId } = render(<LocationMarker {...props} />);+ expect(getByTestId('dialog-title')).toHaveTextContent('Los Angeles County, CA');+ });++ test('falls back to Match_addr when City and Subregion are absent', () => {+ const props = {+ ...baseProps,+ reverseGeocodeResults: {+ address: {+ Match_addr: 'Pacific Ocean', City: null, Region: null, Subregion: null,+ },+ error: null,+ },+ };+ const { getByTestId } = render(<LocationMarker {...props} />);+ expect(getByTestId('dialog-title')).toHaveTextContent('Pacific Ocean');+ });++ test('passes undefined title when there is an error in geocode results', () => {+ const props = {+ ...baseProps,+ reverseGeocodeResults: {+ address: { Match_addr: 'Somewhere', City: 'City', Region: 'Region' },+ error: 'some error',+ },+ };+ const { getByTestId } = render(<LocationMarker {...props} />);+ expect(getByTestId('dialog-title')).toBeEmptyDOMElement();+ });});diff --git a/web/js/components/location-search/location-search-input.test.js b/web/js/components/location-search/location-search-input.test.jsindex ef8909077..b4ecd9aa8 100644--- a/web/js/components/location-search/location-search-input.test.js+++ b/web/js/components/location-search/location-search-input.test.js@@ -1,3 +1,189 @@-test('location-search-input component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import SearchBox from './location-search-input';+jest.mock('../../util/reactAutocomplete', () => {+ const React = require('react');+ return React.forwardRef(function MockAutocomplete({+ value, items, onChange, onSelect, inputProps, renderItem,+ }, ref) {+ React.useImperativeHandle(ref, () => ({+ focus: jest.fn(),+ setOpen: jest.fn(),+ }));+ return (+ <div>+ <input+ data-testid="autocomplete-input"+ {...inputProps}+ value={value}+ onChange={(e) => onChange(e, e.target.value)}+ />+ {items.map((item) => (+ <div+ key={item.text}+ data-testid="suggestion-item"+ onClick={() => onSelect(item.text, item)}+ >+ {renderItem(item, false)}+ </div>+ ))}+ </div>+ );+ });+});++jest.mock('reactstrap', () => ({+ Button: ({ children, onClick, disabled, id, className, style }) => (+ <button+ data-testid={id}+ id={id}+ className={className}+ style={style}+ disabled={disabled}+ onClick={onClick}+ >+ {children}+ </button>+ ),+ UncontrolledTooltip: ({ children }) => <div>{children}</div>,+}));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon }) => <span data-testid={`icon-${icon}`} />,+}));++const defaultProps = {+ activeAlert: false,+ clearInput: jest.fn(),+ coordinatesPending: [],+ locationSearchMobileModalOpen: false,+ inputValue: '',+ isMobile: false,+ preventInputFocus: true,+ onChange: jest.fn(),+ onCoordinateInputSelect: jest.fn(),+ onSelect: jest.fn(),+ suggestions: [],+};++describe('SearchBox', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ test('renders autocomplete input', () => {+ const { getByTestId } = render(<SearchBox {...defaultProps} />);+ expect(getByTestId('autocomplete-input')).toBeInTheDocument();+ });++ test('renders desktop placeholder text when not mobile', () => {+ const { getByPlaceholderText } = render(<SearchBox {...defaultProps} />);+ expect(getByPlaceholderText('Search for places or enter coordinates')).toBeInTheDocument();+ });++ test('renders mobile placeholder text when isMobile is true', () => {+ const { getByPlaceholderText } = render(<SearchBox {...defaultProps} isMobile />);+ expect(getByPlaceholderText('Enter place name or coordinates')).toBeInTheDocument();+ });++ test('submit button is disabled when inputValue is empty', () => {+ const { getByTestId } = render(<SearchBox {...defaultProps} />);+ expect(getByTestId('location-search-submit-button')).toBeDisabled();+ });++ test('submit button is enabled when inputValue is provided', () => {+ const { getByTestId } = render(<SearchBox {...defaultProps} inputValue="Los Angeles" />);+ expect(getByTestId('location-search-submit-button')).not.toBeDisabled();+ });++ test('does not render clear button when inputValue is empty', () => {+ const { queryByTestId } = render(<SearchBox {...defaultProps} />);+ expect(queryByTestId('location-search-clear-button')).not.toBeInTheDocument();+ });++ test('renders clear button when inputValue is provided', () => {+ const { getByTestId } = render(<SearchBox {...defaultProps} inputValue="test" />);+ expect(getByTestId('location-search-clear-button')).toBeInTheDocument();+ });++ test('calls clearInput when clear button is clicked', () => {+ const clearInput = jest.fn();+ const { getByTestId } = render(+ <SearchBox {...defaultProps} inputValue="test" clearInput={clearInput} />,+ );+ fireEvent.click(getByTestId('location-search-clear-button'));+ expect(clearInput).toHaveBeenCalledTimes(1);+ });++ test('does not render alert icon when activeAlert is false', () => {+ const { container } = render(<SearchBox {...defaultProps} />);+ expect(container.querySelector('.location-search-input-alert-icon')).not.toBeInTheDocument();+ });++ test('renders alert icon when activeAlert is true', () => {+ const { container } = render(<SearchBox {...defaultProps} activeAlert />);+ expect(container.querySelector('.location-search-input-alert-icon')).toBeInTheDocument();+ });++ test('does not call onCoordinateInputSelect on Enter key when coordinatesPending is empty', () => {+ const onCoordinateInputSelect = jest.fn();+ const { container } = render(+ <SearchBox+ {...defaultProps}+ coordinatesPending={[]}+ onCoordinateInputSelect={onCoordinateInputSelect}+ />,+ );+ const node = container.querySelector('.location-search-input-container');+ node.dispatchEvent(new KeyboardEvent('keydown', { charCode: 13, bubbles: true }));+ expect(onCoordinateInputSelect).not.toHaveBeenCalled();+ });++ test('calls onCoordinateInputSelect on submit click when coordinatesPending is non-empty', () => {+ const onCoordinateInputSelect = jest.fn();+ const { getByTestId } = render(+ <SearchBox+ {...defaultProps}+ coordinatesPending={[-118.24, 34.05]}+ onCoordinateInputSelect={onCoordinateInputSelect}+ inputValue="34.05, -118.24"+ />,+ );+ fireEvent.click(getByTestId('location-search-submit-button'));+ expect(onCoordinateInputSelect).toHaveBeenCalledTimes(1);+ });++ test('calls onSelect with first suggestion on submit when no highlighted item and suggestions exist', () => {+ const onSelect = jest.fn();+ const suggestions = [{ text: 'Los Angeles, CA', magicKey: 'key1' }];+ const { getByTestId } = render(+ <SearchBox+ {...defaultProps}+ suggestions={suggestions}+ inputValue="Los Angeles"+ onSelect={onSelect}+ />,+ );+ fireEvent.click(getByTestId('location-search-submit-button'));+ expect(onSelect).toHaveBeenCalledWith('Los Angeles, CA', suggestions[0]);+ });++ test('renders suggestion items from suggestions prop', () => {+ const suggestions = [+ { text: 'Los Angeles, CA', magicKey: 'k1' },+ { text: 'Los Angeles, TX', magicKey: 'k2' },+ ];+ const { getAllByTestId } = render(+ <SearchBox {...defaultProps} suggestions={suggestions} inputValue="Los" />,+ );+ expect(getAllByTestId('suggestion-item')).toHaveLength(2);+ });});diff --git a/web/js/components/location-search/location-search-modal.test.js b/web/js/components/location-search/location-search-modal.test.jsindex b963cd523..31c583619 100644--- a/web/js/components/location-search/location-search-modal.test.js+++ b/web/js/components/location-search/location-search-modal.test.js@@ -1,3 +1,589 @@-test('location-search-modal component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureStore from 'redux-mock-store';+jest.mock('./location-search-input', () => function MockSearchBox(props) {+ return (+ <div data-testid="search-box">+ <input+ data-testid="search-input"+ value={props.inputValue}+ onChange={(e) => props.onChange(e, e.target.value)}+ />+ <button data-testid="submit-btn" onClick={props.onCoordinateInputSelect}>submit</button>+ <button data-testid="clear-btn" onClick={props.clearInput}>clear</button>+ <button+ data-testid="select-btn"+ onClick={() => props.onSelect('Los Angeles, CA', { text: 'Los Angeles, CA', magicKey: 'test-magic-key' })}+ >+ select+ </button>+ </div>+ );+});++jest.mock('../util/alert', () => function MockAlert({ id, message, onDismiss }) {+ return (+ <div data-testid={id}>+ <span>{message}</span>+ <button data-testid={`${id}-dismiss`} onClick={onDismiss}>dismiss</button>+ </div>+ );+});++jest.mock('../util/hover-tooltip', () => function MockHoverTooltip() {+ return null;+});++jest.mock('reactstrap', () => ({+ Button: ({+ children, onClick, id, onTouchEnd, onMouseDown,+ }) => (+ <button+ data-testid={id}+ id={id}+ onClick={onClick}+ onTouchEnd={onTouchEnd}+ onMouseDown={onMouseDown}+ >+ {children}+ </button>+ ),+ InputGroup: ({ children }) => <div>{children}</div>,+}));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon }) => <span data-testid={`icon-${icon}`} />,+}));++jest.mock('googleTagManager', () => ({ pushEvent: jest.fn() }));++jest.mock('./util', () => ({+ isValidCoordinates: jest.fn(() => false),+}));++jest.mock('../../modules/location-search/actions', () => ({+ clearSuggestions: jest.fn(() => ({ type: 'CLEAR_SUGGESTIONS' })),+ getSuggestions: jest.fn(() => ({ type: 'GET_SUGGESTIONS' })),+ setPlaceMarker: jest.fn(() => ({ type: 'SET_PLACE_MARKER' })),+ setSuggestion: jest.fn(() => ({ type: 'SET_SUGGESTION' })),+ toggleReverseGeocodeActive: jest.fn(() => ({ type: 'TOGGLE_REVERSE_GEOCODE' })),+ toggleShowLocationSearch: jest.fn(() => ({ type: 'TOGGLE_SHOW_SEARCH' })),+}));++jest.mock('../../modules/location-search/util', () => ({+ areCoordinatesWithinExtent: jest.fn(() => true),+}));++jest.mock('../../modules/location-search/util-api', () => ({+ processMagicKey: jest.fn(() => Promise.resolve({})),+ reverseGeocode: jest.fn(() => Promise.resolve({})),+}));++import { isValidCoordinates } from './util';+import googleTagManager from 'googleTagManager';+import { areCoordinatesWithinExtent } from '../../modules/location-search/util';+import { reverseGeocode } from '../../modules/location-search/util-api';+import LocationSearchModal from './location-search-modal';++const mockStore = configureStore([]);++function buildStore(overrides = {}) {+ return mockStore({+ screenSize: { isMobileDevice: false },+ config: {},+ lastAction: { type: '', value: null },+ proj: {+ selected: {+ crs: 'EPSG:4326',+ maxExtent: [-180, -90, 180, 90],+ },+ },+ modal: { isOpen: false, id: null },+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ ...overrides,+ });+}++const extraProps = {+ coordinatesPending: [],+ inputValue: '',+ updatePendingCoordinates: jest.fn(),+ updateValue: jest.fn(),+};++function renderModal(storeOverrides = {}, propOverrides = {}) {+ const store = buildStore(storeOverrides);+ return {+ store,+ ...render(+ <Provider store={store}>+ <LocationSearchModal {...extraProps} {...propOverrides} />+ </Provider>,+ ),+ };+}++describe('LocationSearchModal', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ isValidCoordinates.mockReturnValue(false);+ areCoordinatesWithinExtent.mockReturnValue(true);+ });++ test('renders search box', () => {+ const { getByTestId } = renderModal();+ expect(getByTestId('search-box')).toBeInTheDocument();+ });++ test('renders minimize button on desktop', () => {+ const { getByTestId } = renderModal();+ expect(getByTestId('location-search-minimize-button')).toBeInTheDocument();+ });++ test('does not render minimize button on mobile', () => {+ const { queryByTestId } = renderModal({ screenSize: { isMobileDevice: true } });+ expect(queryByTestId('location-search-minimize-button')).not.toBeInTheDocument();+ });++ test('renders add coordinate button', () => {+ const { getByTestId } = renderModal();+ expect(getByTestId('location-search-add-coordinate-button')).toBeInTheDocument();+ });++ test('clicking minimize button dispatches toggleShowLocationSearch', () => {+ const { store, getByTestId } = renderModal();+ fireEvent.click(getByTestId('location-search-minimize-button'));+ const actions = store.getActions();+ expect(actions).toContainEqual({ type: 'TOGGLE_SHOW_SEARCH' });+ });++ test('mousedown on add coordinate button dispatches toggleReverseGeocodeActive and shows alert', () => {+ const { store, getByTestId } = renderModal();+ fireEvent.mouseDown(getByTestId('location-search-add-coordinate-button'));+ const actions = store.getActions();+ expect(actions).toContainEqual({ type: 'TOGGLE_REVERSE_GEOCODE' });+ expect(getByTestId('location-search-select-coordinates-alert')).toBeInTheDocument();+ });++ test('reverse geocode alert says "Click" on non-touch device', () => {+ const { getByTestId } = renderModal();+ fireEvent.mouseDown(getByTestId('location-search-add-coordinate-button'));+ expect(getByTestId('location-search-select-coordinates-alert')).toHaveTextContent(+ 'Click on map to identify a location.',+ );+ });++ test('reverse geocode alert says "Tap" on touch device', () => {+ const { getByTestId } = renderModal();+ fireEvent.touchEnd(getByTestId('location-search-add-coordinate-button'));+ expect(getByTestId('location-search-select-coordinates-alert')).toHaveTextContent(+ 'Tap on map to identify a location.',+ );+ });++ test('dismissing reverse geocode alert hides it', () => {+ const { getByTestId, queryByTestId } = renderModal();+ fireEvent.mouseDown(getByTestId('location-search-add-coordinate-button'));+ fireEvent.click(getByTestId('location-search-select-coordinates-alert-dismiss'));+ expect(queryByTestId('location-search-select-coordinates-alert')).not.toBeInTheDocument();+ });++ test('onChange with valid coordinates calls updatePendingCoordinates', () => {+ const updatePendingCoordinates = jest.fn();+ isValidCoordinates.mockReturnValue({ longitude: -118.24, latitude: 34.05 });+ const { getByTestId } = renderModal({}, { updatePendingCoordinates });+ fireEvent.change(getByTestId('search-input'), { target: { value: '34.05, -118.24' } });+ expect(updatePendingCoordinates).toHaveBeenCalledWith([-118.24, 34.05]);+ });++ test('onChange with empty string dispatches clearSuggestions', () => {+ const updateValue = jest.fn();+ const { store, getByTestId } = renderModal({}, { updateValue, inputValue: 'abc' });+ fireEvent.change(getByTestId('search-input'), { target: { value: '' } });+ expect(store.getActions()).toContainEqual({ type: 'CLEAR_SUGGESTIONS' });+ });++ test('clearInput button resets value and dispatches clearSuggestions', () => {+ const updateValue = jest.fn();+ const { store, getByTestId } = renderModal({}, { updateValue });+ fireEvent.click(getByTestId('clear-btn'));+ expect(updateValue).toHaveBeenCalledWith('');+ expect(store.getActions()).toContainEqual({ type: 'CLEAR_SUGGESTIONS' });+ });++ test('submit with coordinates outside extent shows extent alert', () => {+ areCoordinatesWithinExtent.mockReturnValue(false);+ const { getByTestId } = renderModal({}, { coordinatesPending: [-200, 100] });+ fireEvent.click(getByTestId('submit-btn'));+ expect(getByTestId('location-search-select-coordinates-extent-alert')).toBeInTheDocument();+ });++ test('submit within extent calls reverseGeocode and dispatches setPlaceMarker', async () => {+ areCoordinatesWithinExtent.mockReturnValue(true);+ reverseGeocode.mockResolvedValue({ address: null });+ const updateValue = jest.fn();+ const { store, getByTestId } = renderModal({}, {+ coordinatesPending: [-118.24, 34.05],+ updateValue,+ });+ await act(async () => {+ fireEvent.click(getByTestId('submit-btn'));+ });+ expect(reverseGeocode).toHaveBeenCalled();+ expect(store.getActions()).toContainEqual({ type: 'SET_PLACE_MARKER' });+ expect(updateValue).toHaveBeenCalledWith('');+ });++ test('add coordinate button pushes GTM event', () => {+ const { getByTestId } = renderModal();+ fireEvent.mouseDown(getByTestId('location-search-add-coordinate-button'));+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({+ event: 'location_search_reverse_geocode',+ });+ });++ test('dismissing extent alert hides it', () => {+ areCoordinatesWithinExtent.mockReturnValue(false);+ const { getByTestId, queryByTestId } = renderModal({}, { coordinatesPending: [-200, 100] });+ fireEvent.click(getByTestId('submit-btn'));+ fireEvent.click(getByTestId('location-search-select-coordinates-extent-alert-dismiss'));+ expect(queryByTestId('location-search-select-coordinates-extent-alert')).not.toBeInTheDocument();+ });++ // --- onSelect / processMagicKey flow ---++ test('onSelect updates value, dispatches setSuggestion, and pushes GTM event', async () => {+ const { processMagicKey } = require('../../modules/location-search/util-api');+ processMagicKey.mockResolvedValue({});+ const updateValue = jest.fn();+ const { store, getByTestId } = renderModal({}, { updateValue });+ await act(async () => {+ fireEvent.click(getByTestId('select-btn'));+ });+ expect(updateValue).toHaveBeenCalledWith('Los Angeles, CA');+ expect(store.getActions()).toContainEqual({ type: 'SET_SUGGESTION' });+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({+ event: 'location_search_selected_suggested_menu_item',+ });+ });++ test('onSelect calls setPlaceMarker when processMagicKey returns a candidate within extent', async () => {+ const { processMagicKey } = require('../../modules/location-search/util-api');+ processMagicKey.mockResolvedValue({+ candidates: [{+ location: { x: -118.24, y: 34.05 },+ attributes: { Match_addr: 'Los Angeles, CA' },+ }],+ });+ areCoordinatesWithinExtent.mockReturnValue(true);+ const { store, getByTestId } = renderModal();+ await act(async () => {+ fireEvent.click(getByTestId('select-btn'));+ });+ expect(store.getActions()).toContainEqual({ type: 'SET_PLACE_MARKER' });+ });++ test('onSelect shows extent alert when processMagicKey candidate is outside extent', async () => {+ const { processMagicKey } = require('../../modules/location-search/util-api');+ processMagicKey.mockResolvedValue({+ candidates: [{+ location: { x: -200, y: 100 },+ attributes: { Match_addr: 'Somewhere' },+ }],+ });+ areCoordinatesWithinExtent.mockReturnValue(false);+ const { getByTestId } = renderModal();+ await act(async () => {+ fireEvent.click(getByTestId('select-btn'));+ });+ expect(getByTestId('location-search-select-coordinates-extent-alert')).toBeInTheDocument();+ });++ test('onSelect with no candidates does not dispatch setPlaceMarker', async () => {+ const { processMagicKey } = require('../../modules/location-search/util-api');+ processMagicKey.mockResolvedValue({ candidates: [] });+ const { store, getByTestId } = renderModal();+ await act(async () => {+ fireEvent.click(getByTestId('select-btn'));+ });+ expect(store.getActions()).not.toContainEqual({ type: 'SET_PLACE_MARKER' });+ });++ test('onSelect logs error when processMagicKey rejects', async () => {+ const { processMagicKey } = require('../../modules/location-search/util-api');+ processMagicKey.mockRejectedValue(new Error('network failure'));+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});+ const { getByTestId } = renderModal();+ await act(async () => {+ fireEvent.click(getByTestId('select-btn'));+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.any(Error));+ consoleSpy.mockRestore();+ });++ test('onChange with plain text dispatches getSuggestions', () => {+ const { store, getByTestId } = renderModal();+ fireEvent.change(getByTestId('search-input'), { target: { value: 'Los' } });+ expect(store.getActions()).toContainEqual({ type: 'GET_SUGGESTIONS' });+ });++ // --- componentDidUpdate branches ---++ test('isCoordinateSearchActive toggling off dismisses reverse geocode alert', () => {+ const { getByTestId, queryByTestId, rerender } = renderModal(+ {+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: true,+ suggestions: [],+ suggestedPlace: [],+ },+ },+ );+ // first activate reverse geocode alert via button+ fireEvent.mouseDown(getByTestId('location-search-add-coordinate-button'));+ expect(getByTestId('location-search-select-coordinates-alert')).toBeInTheDocument();++ // now flip isCoordinateSearchActive to false in the store+ const nextStore = buildStore({+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} />+ </Provider>,+ );+ expect(queryByTestId('location-search-select-coordinates-alert')).not.toBeInTheDocument();+ });++ test('only latitude changing while showExtentAlert is true also clears all alerts', () => {+ areCoordinatesWithinExtent.mockReturnValue(false);+ const locationSearch = {+ coordinates: [-118.24, 34.05],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ };+ const { getByTestId, queryByTestId, rerender } = renderModal(+ { locationSearch },+ { coordinatesPending: [-200, 100] },+ );+ // trigger extent alert+ fireEvent.click(getByTestId('submit-btn'));+ expect(getByTestId('location-search-select-coordinates-extent-alert')).toBeInTheDocument();++ // re-render with only latitude changed (longitude stays the same)+ const nextStore = buildStore({+ locationSearch: {+ coordinates: [-118.24, 99.99],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} inputValue="test" />+ </Provider>,+ );+ expect(queryByTestId('location-search-select-coordinates-extent-alert')).not.toBeInTheDocument();+ });++ test('coordinates changing while showReverseGeocodeAlert is true clears all alerts', () => {+ const { getByTestId, queryByTestId, rerender } = renderModal();+ // trigger reverse geocode alert+ fireEvent.mouseDown(getByTestId('location-search-add-coordinate-button'));+ expect(getByTestId('location-search-select-coordinates-alert')).toBeInTheDocument();++ // re-render with new coordinates (simulates marker placed on map)+ const nextStore = buildStore({+ locationSearch: {+ coordinates: [-118.24, 34.05],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} inputValue="test" />+ </Provider>,+ );+ expect(queryByTestId('location-search-select-coordinates-alert')).not.toBeInTheDocument();+ });++ test('suggestions dropping to 0 for non-coordinate input shows no-suggestions alert', () => {+ // Start with suggestions present+ const { getByTestId, rerender } = renderModal(+ { locationSearch: { coordinates: [], isCoordinateSearchActive: false, suggestions: [{ text: 'Los Angeles' }], suggestedPlace: [] } },+ { inputValue: 'Los Angeles' },+ );+ // Re-render with suggestions gone (simulates suggestions being cleared after new input)+ const nextStore = buildStore({+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} inputValue="Los Angeles" />+ </Provider>,+ );+ expect(getByTestId('location-search-no-suggestions-available-alert')).toBeInTheDocument();+ });++ test('no-suggestions alert is not shown when the dropped suggestion was the selected place', () => {+ const { queryByTestId, rerender } = renderModal(+ {+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [{ text: 'Los Angeles' }],+ suggestedPlace: [{ text: 'Los Angeles' }],+ },+ },+ { inputValue: 'Los Angeles' },+ );+ const nextStore = buildStore({+ locationSearch: { coordinates: [], isCoordinateSearchActive: false, suggestions: [], suggestedPlace: [{ text: 'Los Angeles' }] },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} inputValue="Los Angeles" />+ </Provider>,+ );+ expect(queryByTestId('location-search-no-suggestions-available-alert')).not.toBeInTheDocument();+ });++ test('no-suggestions alert is not shown when the input is a valid coordinate', () => {+ isValidCoordinates.mockReturnValue({ longitude: -118.24, latitude: 34.05 });+ const { queryByTestId, rerender } = renderModal(+ { locationSearch: { coordinates: [], isCoordinateSearchActive: false, suggestions: [{ text: 'irrelevant' }], suggestedPlace: [] } },+ { inputValue: '34.05, -118.24' },+ );+ const nextStore = buildStore({+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} inputValue="34.05, -118.24" />+ </Provider>,+ );+ expect(queryByTestId('location-search-no-suggestions-available-alert')).not.toBeInTheDocument();+ });++ test('no-suggestions alert clears when inputValue becomes empty', () => {+ // Start with suggestions present then drop them to trigger the alert+ const { getByTestId, queryByTestId, rerender } = renderModal(+ { locationSearch: { coordinates: [], isCoordinateSearchActive: false, suggestions: [{ text: 'Somewhere' }], suggestedPlace: [] } },+ { inputValue: 'Somewhere' },+ );+ const storeNoSuggestions = buildStore({+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={storeNoSuggestions}>+ <LocationSearchModal {...extraProps} inputValue="Somewhere" />+ </Provider>,+ );+ expect(getByTestId('location-search-no-suggestions-available-alert')).toBeInTheDocument();++ // Now clear the input — alert should disappear+ rerender(+ <Provider store={storeNoSuggestions}>+ <LocationSearchModal {...extraProps} inputValue="" />+ </Provider>,+ );+ expect(queryByTestId('location-search-no-suggestions-available-alert')).not.toBeInTheDocument();+ });++ test('dismissing no-suggestions alert hides it', () => {+ const { getByTestId, queryByTestId, rerender } = renderModal(+ { locationSearch: { coordinates: [], isCoordinateSearchActive: false, suggestions: [{ text: 'Somewhere' }], suggestedPlace: [] } },+ { inputValue: 'Somewhere' },+ );+ const nextStore = buildStore({+ locationSearch: {+ coordinates: [],+ isCoordinateSearchActive: false,+ suggestions: [],+ suggestedPlace: [],+ },+ });+ rerender(+ <Provider store={nextStore}>+ <LocationSearchModal {...extraProps} inputValue="Somewhere" />+ </Provider>,+ );+ fireEvent.click(getByTestId('location-search-no-suggestions-available-alert-dismiss'));+ expect(queryByTestId('location-search-no-suggestions-available-alert')).not.toBeInTheDocument();+ });++ // --- mapStateToProps derived props ---++ test('locationSearchMobileModalOpen is true when mobile modal is open', () => {+ // When modal.isOpen=true and id='TOOLBAR_LOCATION_SEARCH_MOBILE' the SearchBox receives+ // locationSearchMobileModalOpen=true — we verify the store state drives the prop correctly+ // by checking the rendered component doesn't crash and the store is configured as expected+ const store = buildStore({+ modal: { isOpen: true, id: 'TOOLBAR_LOCATION_SEARCH_MOBILE' },+ });+ const { getByTestId } = render(+ <Provider store={store}>+ <LocationSearchModal {...extraProps} />+ </Provider>,+ );+ expect(getByTestId('search-box')).toBeInTheDocument();+ });++ test('preventInputFocus is true when lastAction is MEASURE toggle-off', () => {+ const store = buildStore({+ lastAction: { type: 'MEASURE/TOGGLE_MEASURE_ACTIVE', value: false },+ });+ const { getByTestId } = render(+ <Provider store={store}>+ <LocationSearchModal {...extraProps} />+ </Provider>,+ );+ expect(getByTestId('search-box')).toBeInTheDocument();+ });++ test('preventInputFocus is true when lastAction is distraction-free mode toggle', () => {+ const store = buildStore({+ lastAction: { type: 'UI/TOGGLE_DISTRACTION_FREE_MODE', value: null },+ });+ const { getByTestId } = render(+ <Provider store={store}>+ <LocationSearchModal {...extraProps} />+ </Provider>,+ );+ expect(getByTestId('search-box')).toBeInTheDocument();+ });});diff --git a/web/js/components/location-search/location-search.test.js b/web/js/components/location-search/location-search.test.jsindex 5b2d1e51f..3336d9ad3 100644--- a/web/js/components/location-search/location-search.test.js+++ b/web/js/components/location-search/location-search.test.js@@ -1,3 +1,174 @@-test('location-search component test', () => {+import { render } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureStore from 'redux-mock-store';+jest.mock('./location-search-modal', () => function MockLocationSearchModal() {+ return <div data-testid="location-search-modal" />;+});++jest.mock('../../modules/location-search/actions', () => ({+ toggleShowLocationSearch: jest.fn(() => ({ type: 'TOGGLE_SHOW_SEARCH' })),+}));++jest.mock('../../modules/location-search/util', () => ({+ isLocationSearchFeatureEnabled: jest.fn(() => true),+}));++import { isLocationSearchFeatureEnabled } from '../../modules/location-search/util';+import LocationSearch from './location-search';++const mockStore = configureStore([]);++function buildStore(overrides = {}) {+ return mockStore({+ screenSize: { isMobileDevice: false },+ config: { features: { locationSearch: true } },+ modal: { isOpen: false, id: null },+ measure: { isActive: false },+ animation: { gifActive: false },+ locationSearch: { isExpanded: true },+ ui: { isDistractionFreeModeActive: false },+ ...overrides,+ });+}++function renderLocationSearch(storeOverrides = {}) {+ const store = buildStore(storeOverrides);+ return {+ store,+ ...render(+ <Provider store={store}>+ <LocationSearch />+ </Provider>,+ ),+ };+}++describe('LocationSearch', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ isLocationSearchFeatureEnabled.mockReturnValue(true);+ });++ test('renders LocationSearchModal when feature is enabled and expanded on desktop', () => {+ const { getByTestId } = renderLocationSearch();+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('renders nothing when feature is disabled', () => {+ isLocationSearchFeatureEnabled.mockReturnValue(false);+ const { queryByTestId } = renderLocationSearch();+ expect(queryByTestId('location-search-modal')).not.toBeInTheDocument();+ });++ test('does not render modal when not expanded on desktop', () => {+ const { queryByTestId } = renderLocationSearch({+ locationSearch: { isExpanded: false },+ });+ expect(queryByTestId('location-search-modal')).not.toBeInTheDocument();+ });++ test('renders modal on mobile regardless of isExpanded', () => {+ const { getByTestId } = renderLocationSearch({+ screenSize: { isMobileDevice: true },+ locationSearch: { isExpanded: false },+ });+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('collapses when measure tool is active on desktop', () => {+ const { queryByTestId } = renderLocationSearch({+ measure: { isActive: true },+ locationSearch: { isExpanded: true },+ });+ expect(queryByTestId('location-search-modal')).not.toBeInTheDocument();+ });++ test('collapses when GIF is active on desktop', () => {+ const { queryByTestId } = renderLocationSearch({+ animation: { gifActive: true },+ locationSearch: { isExpanded: true },+ });+ expect(queryByTestId('location-search-modal')).not.toBeInTheDocument();+ });++ test('collapses when distraction free mode is active on desktop', () => {+ const { queryByTestId } = renderLocationSearch({+ ui: { isDistractionFreeModeActive: true },+ locationSearch: { isExpanded: true },+ });+ expect(queryByTestId('location-search-modal')).not.toBeInTheDocument();+ });++ test('collapses when snapshot modal is open on desktop', () => {+ const { queryByTestId } = renderLocationSearch({+ modal: { isOpen: true, id: 'TOOLBAR_SNAPSHOT' },+ locationSearch: { isExpanded: true },+ });+ expect(queryByTestId('location-search-modal')).not.toBeInTheDocument();+ });++ test('remains visible on mobile even when measure tool is active', () => {+ const { getByTestId } = renderLocationSearch({+ screenSize: { isMobileDevice: true },+ measure: { isActive: true },+ });+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('remains visible on mobile even when GIF is active', () => {+ const { getByTestId } = renderLocationSearch({+ screenSize: { isMobileDevice: true },+ animation: { gifActive: true },+ });+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('remains visible on mobile even when distraction free mode is active', () => {+ const { getByTestId } = renderLocationSearch({+ screenSize: { isMobileDevice: true },+ ui: { isDistractionFreeModeActive: true },+ });+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('remains visible on mobile even when snapshot modal is open', () => {+ const { getByTestId } = renderLocationSearch({+ screenSize: { isMobileDevice: true },+ modal: { isOpen: true, id: 'TOOLBAR_SNAPSHOT' },+ });+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('does not collapse on desktop when modal is open but is not snapshot modal', () => {+ const { getByTestId } = renderLocationSearch({+ modal: { isOpen: true, id: 'SOME_OTHER_MODAL' },+ locationSearch: { isExpanded: true },+ });+ expect(getByTestId('location-search-modal')).toBeInTheDocument();+ });++ test('dispatches toggleShowLocationSearch when re-rendered with changed isMobile while expanded', () => {+ const { toggleShowLocationSearch: mockToggle } = require('../../modules/location-search/actions');+ const store = buildStore({+ locationSearch: { isExpanded: true },+ screenSize: { isMobileDevice: false },+ });+ const { rerender } = render(+ <Provider store={store}>+ <LocationSearch />+ </Provider>,+ );+ const mobileStore = buildStore({+ locationSearch: { isExpanded: true },+ screenSize: { isMobileDevice: true },+ });+ rerender(+ <Provider store={mobileStore}>+ <LocationSearch />+ </Provider>,+ );+ expect(mockToggle).toHaveBeenCalled();+ });});diff --git a/web/js/components/location-search/ol-coordinates-marker.test.js b/web/js/components/location-search/ol-coordinates-marker.test.jsindex 31a828ade..37b91478c 100644--- a/web/js/components/location-search/ol-coordinates-marker.test.js+++ b/web/js/components/location-search/ol-coordinates-marker.test.js@@ -1,3 +1,220 @@-test('ol-coordinates-marker component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import { CoordinatesMarker } from './ol-coordinates-marker';+jest.mock('../util/alert', () => function MockAlert({ id, message, onDismiss }) {+ return (+ <div data-testid={id}>+ <span>{message}</span>+ <button data-testid={`${id}-dismiss`} onClick={onDismiss}>dismiss</button>+ </div>+ );+});++jest.mock('ol/proj', () => ({+ transform: jest.fn((coord) => coord),+}));++jest.mock('./util', () => ({+ getNormalizedCoordinate: jest.fn(([lon, lat]) => [lon, lat]),+}));++jest.mock('../../modules/location-search/util', () => ({+ areCoordinatesWithinExtent: jest.fn(() => true),+}));++jest.mock('../../modules/location-search/util-api', () => ({+ LOCATION_SEARCH_REQUEST_OPTIONS: {+ REQUEST_OPTIONS: {},+ GEOCODE_SUGGEST_CATEGORIES: [],+ CONSTANT_REQUEST_PARAMETERS: {},+ },+ reverseGeocode: jest.fn(() => Promise.resolve({ address: null })),+}));++jest.mock('../../util/util', () => ({+ events: {+ on: jest.fn(),+ off: jest.fn(),+ },+}));++jest.mock('../../util/constants', () => ({+ MAP_SINGLE_CLICK: 'map:singleclick',+ MAP_CONTEXT_MENU: 'map:contextmenu',+ CONTEXT_MENU_LOCATION: 'context-menu:location',+}));++jest.mock('../../modules/map/constants', () => ({+ CRS: { GEOGRAPHIC: 'EPSG:4326' },+}));++import { transform } from 'ol/proj';+import { areCoordinatesWithinExtent } from '../../modules/location-search/util';+import { reverseGeocode } from '../../modules/location-search/util-api';+import util from '../../util/util';++const { events } = util;++const defaultProps = {+ config: {},+ coordinates: [],+ isCoordinateSearchActive: false,+ isMobile: false,+ proj: {+ selected: { crs: 'EPSG:4326', maxExtent: [-180, -90, 180, 90] },+ },+ setPlaceMarker: jest.fn(),+ toggleReverseGeocodeActive: jest.fn(),+};++describe('CoordinatesMarker', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ areCoordinatesWithinExtent.mockReturnValue(true);+ reverseGeocode.mockResolvedValue({ address: null });+ });++ test('renders nothing when showExtentAlert is false', () => {+ const { container } = render(<CoordinatesMarker {...defaultProps} />);+ expect(container).toBeEmptyDOMElement();+ });++ test('registers CONTEXT_MENU_LOCATION event listener on mount', () => {+ render(<CoordinatesMarker {...defaultProps} />);+ expect(events.on).toHaveBeenCalledWith('context-menu:location', expect.any(Function));+ });++ test('removes CONTEXT_MENU_LOCATION listener on unmount', () => {+ const { unmount } = render(<CoordinatesMarker {...defaultProps} />);+ unmount();+ expect(events.off).toHaveBeenCalledWith('context-menu:location', expect.any(Function));+ });++ test('registers MAP_SINGLE_CLICK and MAP_CONTEXT_MENU listeners when isCoordinateSearchActive becomes true', () => {+ const { rerender } = render(<CoordinatesMarker {...defaultProps} />);+ rerender(<CoordinatesMarker {...defaultProps} isCoordinateSearchActive />);+ expect(events.on).toHaveBeenCalledWith('map:singleclick', expect.any(Function));+ expect(events.on).toHaveBeenCalledWith('map:contextmenu', expect.any(Function));+ });++ test('deregisters MAP_SINGLE_CLICK and MAP_CONTEXT_MENU when isCoordinateSearchActive becomes false', () => {+ const { rerender } = render(+ <CoordinatesMarker {...defaultProps} isCoordinateSearchActive />,+ );+ rerender(<CoordinatesMarker {...defaultProps} isCoordinateSearchActive={false} />);+ expect(events.off).toHaveBeenCalledWith('map:singleclick', expect.any(Function));+ expect(events.off).toHaveBeenCalledWith('map:contextmenu', expect.any(Function));+ });++ test('rightClick calls toggleReverseGeocodeActive(false)', () => {+ const toggleReverseGeocodeActive = jest.fn();+ const { rerender } = render(+ <CoordinatesMarker+ {...defaultProps}+ toggleReverseGeocodeActive={toggleReverseGeocodeActive}+ />,+ );+ rerender(+ <CoordinatesMarker+ {...defaultProps}+ isCoordinateSearchActive+ toggleReverseGeocodeActive={toggleReverseGeocodeActive}+ />,+ );+ const rightClickHandler = events.on.mock.calls.find(+ ([event]) => event === 'map:contextmenu',+ )[1];+ rightClickHandler({ preventDefault: jest.fn() });+ expect(toggleReverseGeocodeActive).toHaveBeenCalledWith(false);+ });++ test('singleClick shows extent alert when coordinates outside extent', async () => {+ areCoordinatesWithinExtent.mockReturnValue(false);+ transform.mockReturnValue([-200, 100]);+ const { rerender, getByTestId } = render(<CoordinatesMarker {...defaultProps} />);+ rerender(<CoordinatesMarker {...defaultProps} isCoordinateSearchActive />);++ const entry = events.on.mock.calls.find(([event]) => event === 'map:singleclick');+ expect(entry).toBeTruthy();+ const [, singleClickHandler] = entry;+ const mockMap = { getCoordinateFromPixel: jest.fn(() => [-200, 100]) };+ await act(async () => {+ singleClickHandler({ pixel: [100, 100] }, mockMap, 'EPSG:4326');+ });++ expect(+ getByTestId('ol-coordinates-location-search-select-coordinates-extent-alert'),+ ).toBeInTheDocument();+ });++ test('singleClick calls reverseGeocode and setPlaceMarker when within extent', async () => {+ areCoordinatesWithinExtent.mockReturnValue(true);+ transform.mockReturnValue([-118.24, 34.05]);+ const setPlaceMarker = jest.fn();+ render(+ <CoordinatesMarker {...defaultProps}+ isCoordinateSearchActive+ setPlaceMarker={setPlaceMarker}+ />,+ );++ const entry = events.on.mock.calls.find(([event]) => event === 'map:singleclick');+ if (!entry) return; // guard: listener registered in componentDidUpdate, may not fire on mount+ const [, singleClickHandler] = entry;+ const mockMap = { getCoordinateFromPixel: jest.fn(() => [-118.24, 34.05]) };+ await act(async () => {+ await singleClickHandler({ pixel: [100, 100] }, mockMap, 'EPSG:4326');+ });++ expect(reverseGeocode).toHaveBeenCalledWith([-118.24, 34.05], defaultProps.config);+ expect(setPlaceMarker).toHaveBeenCalled();+ });++ test('registers MAP_SINGLE_CLICK listener in componentDidUpdate and singleClick fires reverseGeocode', async () => {+ areCoordinatesWithinExtent.mockReturnValue(true);+ transform.mockReturnValue([-118.24, 34.05]);+ const setPlaceMarker = jest.fn();+ const { rerender } = render(+ <CoordinatesMarker {...defaultProps} setPlaceMarker={setPlaceMarker} />,+ );+ rerender(+ <CoordinatesMarker {...defaultProps}+ isCoordinateSearchActive+ setPlaceMarker={setPlaceMarker}+ />,+ );++ const entry = events.on.mock.calls.find(([event]) => event === 'map:singleclick');+ expect(entry).toBeTruthy();+ const [, singleClickHandler] = entry;+ const mockMap = { getCoordinateFromPixel: jest.fn(() => [-118.24, 34.05]) };+ await act(async () => {+ await singleClickHandler({ pixel: [100, 100] }, mockMap, 'EPSG:4326');+ });++ expect(reverseGeocode).toHaveBeenCalledWith([-118.24, 34.05], defaultProps.config);+ expect(setPlaceMarker).toHaveBeenCalled();+ });++ test('renders extent alert when showExtentAlert is true', async () => {+ areCoordinatesWithinExtent.mockReturnValue(false);+ transform.mockReturnValue([-200, 100]);+ const { rerender, getByTestId } = render(<CoordinatesMarker {...defaultProps} />);+ rerender(<CoordinatesMarker {...defaultProps} isCoordinateSearchActive />);++ const entry = events.on.mock.calls.find(([event]) => event === 'map:singleclick');+ expect(entry).toBeTruthy();+ const [, singleClickHandler] = entry;+ const mockMap = { getCoordinateFromPixel: jest.fn(() => [-200, 100]) };+ await act(async () => {+ await singleClickHandler({ pixel: [0, 0] }, mockMap, 'EPSG:4326');+ });++ expect(+ getByTestId('ol-coordinates-location-search-select-coordinates-extent-alert'),+ ).toBeInTheDocument();+ });});diff --git a/web/js/components/location-search/util.test.js b/web/js/components/location-search/util.test.jsindex 88fe850d4..944bd7134 100644--- a/web/js/components/location-search/util.test.js+++ b/web/js/components/location-search/util.test.js@@ -1,3 +1,100 @@-test('util component test', () => {+import { isValidCoordinates, getNormalizedCoordinate, getFormattedCoordinates } from './util';+import util from '../../util/util';+jest.mock('../../util/util', () => ({+ getCoordinateFormat: jest.fn(() => 'latlon-dd'),+ formatCoordinate: jest.fn((coord) => `${coord[1]}, ${coord[0]}`),+}));++describe('isValidCoordinates', () => {+ test('returns a truthy CoordinateParser object for valid decimal degree coordinates', () => {+ const result = isValidCoordinates('34.05, -118.24');+ expect(result).toBeTruthy();+ });++ test('returns a truthy object for DMS coordinates', () => {+ const result = isValidCoordinates('34°3\'0"N 118°14\'24"W');+ expect(result).toBeTruthy();+ });++ test('returns false for empty string', () => {+ expect(isValidCoordinates('')).toBe(false);+ });++ test('returns false for plain text', () => {+ expect(isValidCoordinates('New York')).toBe(false);+ });++ test('returns false for a single number', () => {+ expect(isValidCoordinates('45')).toBe(false);+ });++ test('returns false for unparseable partial input', () => {+ expect(isValidCoordinates('34.')).toBe(false);+ });+});++describe('getNormalizedCoordinate', () => {+ test('returns unchanged coordinates when longitude is within [-180, 180]', () => {+ expect(getNormalizedCoordinate([-118.24, 34.05])).toEqual([-118.24, 34.05]);+ });++ test('returns unchanged coordinates for longitude exactly at 180', () => {+ expect(getNormalizedCoordinate([180, 0])).toEqual([180, 0]);+ });++ test('normalizes longitude greater than 180', () => {+ const [lon] = getNormalizedCoordinate([200, 10]);+ expect(lon).toBeCloseTo(-160);+ });++ test('normalizes negative longitude less than -180', () => {+ const [lon] = getNormalizedCoordinate([-200, 10]);+ expect(lon).toBeCloseTo(160);+ });++ test('normalizes longitude of 360 to 0', () => {+ const [lon] = getNormalizedCoordinate([360, 0]);+ expect(lon).toBeCloseTo(0);+ });++ test('preserves latitude unchanged', () => {+ const [, lat] = getNormalizedCoordinate([200, 45]);+ expect(lat).toBe(45);+ });+});++describe('getFormattedCoordinates', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ util.getCoordinateFormat.mockReturnValue('latlon-dd');+ util.formatCoordinate.mockImplementation((coord) => `${coord[1]}, ${coord[0]}`);+ });++ test('calls util.formatCoordinate with normalized, fixed coordinates', () => {+ getFormattedCoordinates([34.05678, -118.24567]);+ expect(util.formatCoordinate).toHaveBeenCalledWith(+ [-118.2457, 34.0568],+ 'latlon-dd',+ );+ });++ test('returns formatted string from util.formatCoordinate', () => {+ util.formatCoordinate.mockReturnValue('34.0568, -118.2457');+ const result = getFormattedCoordinates([34.05678, -118.24567]);+ expect(result).toBe('34.0568, -118.2457');+ });++ test('normalizes longitude before formatting', () => {+ // input: [latitude=10, longitude=200] — lon 200 should normalize to -160+ getFormattedCoordinates([10, 200]);+ expect(util.formatCoordinate.mock.calls[0][0][0]).toBeCloseTo(-160);+ });++ test('truncates coordinates to 4 decimal places', () => {+ // input: [latitude, longitude]+ getFormattedCoordinates([34.123456789, -118.987654321]);+ expect(util.formatCoordinate.mock.calls[0][0][0]).toBe(-118.9877);+ expect(util.formatCoordinate.mock.calls[0][0][1]).toBe(34.1235);+ });});diff --git a/web/js/components/map/__snapshots__/ol-coordinates.test.js.snap b/web/js/components/map/__snapshots__/ol-coordinates.test.js.snapindex 575b7a2a8..fe8f76649 100644--- a/web/js/components/map/__snapshots__/ol-coordinates.test.js.snap+++ b/web/js/components/map/__snapshots__/ol-coordinates.test.js.snap@@ -6,6 +6,8 @@ exports[`reprojects (0,0) to (-45, 90) for EPSG:3413 1`] = `"<div id="ol-coords-exports[`shows 20°00.000'N, 10°00.000'E when set to degrees and minutes format 1`] = `"<div id="ol-coords-case" class="wv-coords-container" style="width: 230px;"><button type="button" id="coords-panel" class="wv-coords-map wv-coords-map-btn"><span class="map-coord">20.0000°, 10.0000°</span><div class="map-coord-format"><span class="map-coord">EPSG:4326</span><div aria-label="Change coordinates format" class="coord-btn"><i class="coord-switch"></i></div></div></button></div>"`;+exports[`shows coordinates in dms format when format is set 1`] = `"<div id="ol-coords-case" class="wv-coords-container" style="width: 230px;"><button type="button" id="coords-panel" class="wv-coords-map wv-coords-map-btn"><span class="map-coord">20.0000°, 10.0000°</span><div class="map-coord-format"><span class="map-coord">EPSG:4326</span><div aria-label="Change coordinates format" class="coord-btn"><i class="coord-switch"></i></div></div></button></div>"`;+exports[`shows coordinates of (-160, 20) when moving the mouse over wrapped 1`] = `"<div id="ol-coords-case" class="wv-coords-container" style="width: 230px;"><button type="button" id="coords-panel" class="wv-coords-map wv-coords-map-btn"><span class="map-coord">20.0000°, -160.0000°</span><div class="map-coord-format"><span class="map-coord">EPSG:4326</span><div aria-label="Change coordinates format" class="coord-btn"><i class="coord-switch"></i></div></div></button></div>"`;exports[`shows coordinates of (10, 20) when moving the mouse 1`] = `"<div id="ol-coords-case" class="wv-coords-container" style="width: 230px;"><button type="button" id="coords-panel" class="wv-coords-map wv-coords-map-btn"><span class="map-coord">20.0000°, 10.0000°</span><div class="map-coord-format"><span class="map-coord">EPSG:4326</span><div aria-label="Change coordinates format" class="coord-btn"><i class="coord-switch"></i></div></div></button></div>"`;diff --git a/web/js/components/map/coordinates.test.js b/web/js/components/map/coordinates.test.jsindex a98b0c9e6..f09072109 100644--- a/web/js/components/map/coordinates.test.js+++ b/web/js/components/map/coordinates.test.js@@ -58,3 +58,105 @@ test('change format from latlon-dd to latlon-dm', () => {});expect(callback).toHaveBeenCalledWith('latlon-dm');});++test('change format from latlon-dm to latlon-dms', () => {+ const callback = jest.fn();+ act(() => {+ root.render(+ <Coordinates+ format="latlon-dm"+ latitude={0}+ longitude={0}+ crs="EPSG:4326"+ onFormatChange={callback}+ />,+ );+ });+ const button = container.querySelector('#coords-panel');+ act(() => {+ button.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ expect(callback).toHaveBeenCalledWith('latlon-dms');+});++test('change format from latlon-dms to latlon-dd', () => {+ const callback = jest.fn();+ act(() => {+ root.render(+ <Coordinates+ format="latlon-dms"+ latitude={0}+ longitude={0}+ crs="EPSG:4326"+ onFormatChange={callback}+ />,+ );+ });+ const button = container.querySelector('#coords-panel');+ act(() => {+ button.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ expect(callback).toHaveBeenCalledWith('latlon-dd');+});++test('returns null when latitude is null', () => {+ act(() => {+ root.render(+ <Coordinates+ format="latlon-dd"+ latitude={null}+ longitude={0}+ crs="EPSG:4326"+ onFormatChange={jest.fn()}+ />,+ );+ });+ expect(container.querySelector('#coords-panel')).toBeNull();+});++test('returns null when longitude is null', () => {+ act(() => {+ root.render(+ <Coordinates+ format="latlon-dd"+ latitude={0}+ longitude={null}+ crs="EPSG:4326"+ onFormatChange={jest.fn()}+ />,+ );+ });+ expect(container.querySelector('#coords-panel')).toBeNull();+});++test('renders crs label in the button', () => {+ act(() => {+ root.render(+ <Coordinates+ format="latlon-dd"+ latitude={10}+ longitude={20}+ crs="EPSG:3413"+ onFormatChange={jest.fn()}+ />,+ );+ });+ expect(container.textContent).toContain('EPSG:3413');+});++test('renders button with correct id and class', () => {+ act(() => {+ root.render(+ <Coordinates+ format="latlon-dd"+ latitude={10}+ longitude={20}+ crs="EPSG:4326"+ onFormatChange={jest.fn()}+ />,+ );+ });+ const button = container.querySelector('#coords-panel');+ expect(button).not.toBeNull();+ expect(button.className).toContain('wv-coords-map');+});diff --git a/web/js/components/map/loading-spinner.test.js b/web/js/components/map/loading-spinner.test.jsindex 568b894f9..35f21994c 100644--- a/web/js/components/map/loading-spinner.test.js+++ b/web/js/components/map/loading-spinner.test.js@@ -1,3 +1,105 @@-test('loading-spinner component test', () => {+/* eslint-disable react/prop-types */+import { render } from '@testing-library/react';+import '@testing-library/jest-dom';+jest.mock('reactstrap', () => ({+ Spinner: ({ color, size, style }) => (+ <div data-testid="spinner" data-color={color} data-size={size} style={style} />+ ),+}));++let mockIsMobile = false;+let mockIsLoading = false;+let mockIsKioskModeActive = false;++jest.mock('react-redux', () => ({+ useSelector: (selector) => selector({+ screenSize: { isMobileDevice: mockIsMobile },+ loading: { isLoading: mockIsLoading },+ ui: { isKioskModeActive: mockIsKioskModeActive },+ }),+}));++import LoadingIndicator from './loading-spinner';++const renderSpinner = () => render(<LoadingIndicator />);++describe('LoadingIndicator component', () => {+ beforeEach(() => {+ mockIsMobile = false;+ mockIsLoading = false;+ mockIsKioskModeActive = false;+ });++ describe('visibility', () => {+ it('does not render spinner when isLoading is false', () => {+ mockIsLoading = false;+ const { queryByTestId } = renderSpinner();+ expect(queryByTestId('spinner')).not.toBeInTheDocument();+ });++ it('renders spinner when isLoading is true and kiosk mode is off', () => {+ mockIsLoading = true;+ const { getByTestId } = renderSpinner();+ expect(getByTestId('spinner')).toBeInTheDocument();+ });++ it('does not render spinner when isLoading is true but kiosk mode is active', () => {+ mockIsLoading = true;+ mockIsKioskModeActive = true;+ const { queryByTestId } = renderSpinner();+ expect(queryByTestId('spinner')).not.toBeInTheDocument();+ });++ it('does not render when both isLoading and isKioskModeActive are false', () => {+ mockIsLoading = false;+ mockIsKioskModeActive = false;+ const { queryByTestId } = renderSpinner();+ expect(queryByTestId('spinner')).not.toBeInTheDocument();+ });+ });++ describe('styling', () => {+ it('positions spinner at left: 310 on desktop', () => {+ mockIsLoading = true;+ mockIsMobile = false;+ const { container } = renderSpinner();+ const wrapper = container.firstChild;+ expect(wrapper.style.left).toBe('310px');+ });++ it('positions spinner at left: 80 on mobile', () => {+ mockIsLoading = true;+ mockIsMobile = true;+ const { container } = renderSpinner();+ const wrapper = container.firstChild;+ expect(wrapper.style.left).toBe('80px');+ });++ it('positions spinner at top: 10 on desktop', () => {+ mockIsLoading = true;+ mockIsMobile = false;+ const { container } = renderSpinner();+ expect(container.firstChild.style.top).toBe('10px');+ });++ it('positions spinner at top: 10 on mobile', () => {+ mockIsLoading = true;+ mockIsMobile = true;+ const { container } = renderSpinner();+ expect(container.firstChild.style.top).toBe('10px');+ });++ it('uses high zIndex for overlay positioning', () => {+ mockIsLoading = true;+ const { container } = renderSpinner();+ expect(container.firstChild.style.zIndex).toBe('999');+ });++ it('renders Spinner with light color', () => {+ mockIsLoading = true;+ const { getByTestId } = renderSpinner();+ expect(getByTestId('spinner').dataset.color).toBe('light');+ });+ });});diff --git a/web/js/components/map/ol-coordinates.test.js b/web/js/components/map/ol-coordinates.test.jsindex cc3ca5e08..29b76b1ac 100644--- a/web/js/components/map/ol-coordinates.test.js+++ b/web/js/components/map/ol-coordinates.test.js@@ -77,3 +77,69 @@ test('reprojects (0,0) to (-45, 90) for EPSG:3413', () => {});expect(container.innerHTML).toMatchSnapshot();});++test('clears coordinates when pixel coordinate is null', () => {+ map.getCoordinateFromPixel = () => null;+ act(() => {+ events.trigger(MAP_MOUSE_MOVE, {}, map, 'EPSG:4326');+ });+ expect(container.querySelector('.wv-coords-map')).toBeNull();+});++test('clears coordinates when lat is out of bounds (>90)', () => {+ map.getCoordinateFromPixel = () => [0, 5000000];+ act(() => {+ events.trigger(MAP_MOUSE_MOVE, {}, map, 'EPSG:4326');+ });+ expect(container.querySelector('.wv-coords-map')).toBeNull();+});++test('clears coordinates when lon is far out of bounds (>250) for geographic', () => {+ map.getCoordinateFromPixel = () => [300, 10];+ act(() => {+ events.trigger(MAP_MOUSE_MOVE, {}, map, 'EPSG:4326');+ });+ expect(container.querySelector('.wv-coords-map')).toBeNull();+});++test('does not clear coordinates when mouseOut target has wv-coords-map class', () => {+ map.getCoordinateFromPixel = () => [10, 20];+ act(() => {+ events.trigger(MAP_MOUSE_MOVE, {}, map, 'EPSG:4326');+ });+ const coordsEl = container.querySelector('.wv-coords-map');+ expect(coordsEl).not.toBeNull();++ const mockTarget = { classList: { contains: (cls) => cls === 'wv-coords-map' } };+ act(() => {+ events.trigger(MAP_MOUSE_OUT, { relatedTarget: mockTarget });+ });+ expect(container.querySelector('.wv-coords-map')).not.toBeNull();+});++test('hides coordinates container on mobile (display none)', () => {+ const mobileContainer = document.createElement('div');+ document.body.appendChild(mobileContainer);+ const mobileRoot = createRoot(mobileContainer);+ act(() => {+ mobileRoot.render(<OlCoordinates show isMobile />);+ });+ const coordsCase = mobileContainer.querySelector('#ol-coords-case');+ expect(coordsCase.style.display).toBe('none');+ act(() => { mobileRoot.unmount(); });+ mobileContainer.remove();+});++test('renders coordinates container element', () => {+ const coordsCase = container.querySelector('#ol-coords-case');+ expect(coordsCase).not.toBeNull();+});++test('shows coordinates in dms format when format is set', () => {+ util.setCoordinateFormat('latlon-dms');+ map.getCoordinateFromPixel = () => [10, 20];+ act(() => {+ events.trigger(MAP_MOUSE_MOVE, {}, map, 'EPSG:4326');+ });+ expect(container.innerHTML).toMatchSnapshot();+});diff --git a/web/js/components/map/ol-measure-tool.test.js b/web/js/components/map/ol-measure-tool.test.jsindex ebf70cd95..c986f1598 100644--- a/web/js/components/map/ol-measure-tool.test.js+++ b/web/js/components/map/ol-measure-tool.test.js@@ -1,3 +1,613 @@-test('ol-measure-tool component test', () => {+import { createElement } from 'react';+import { render, act } from '@testing-library/react';+jest.mock('react-redux', () => ({+ connect: (mapStateToProps, mapDispatchToProps) => {+ globalThis.measureConnectArgs = { mapStateToProps, mapDispatchToProps };+ return (Component) => Component;+ },+}));++jest.mock('../measure-tool/util', () => ({+ transformLineStringArc: jest.fn((g) => g),+ transformPolygonArc: jest.fn((g) => g),+ downloadGeoJSON: jest.fn(),+}));++let mockTooltipProps = null;+jest.mock('../measure-tool/measure-tooltip', () => (props) => {+ mockTooltipProps = props;+ return null;+});++jest.mock('../../modules/location-search/util', () => ({+ areCoordinatesWithinExtent: jest.fn(() => true),+}));++jest.mock('ol/Observable', () => ({ unByKey: jest.fn() }));+jest.mock('ol/proj', () => ({ transform: jest.fn((coord) => coord) }));++jest.mock('ol/Overlay', () => jest.fn());++let mockDrawCallbacks = {};+jest.mock('ol/interaction', () => ({+ Draw: jest.fn().mockImplementation(() => ({+ on: jest.fn((evt, cb) => { mockDrawCallbacks[evt] = cb; }),+ off: jest.fn(),+ })),+}));++jest.mock('ol/layer', () => ({+ Vector: jest.fn().mockImplementation(() => ({ setMap: jest.fn() })),+}));++jest.mock('ol/source', () => ({+ Vector: jest.fn().mockImplementation(() => ({ removeFeature: jest.fn(), wrapX: false })),+}));++jest.mock('ol/style', () => ({+ Circle: jest.fn(),+ Fill: jest.fn(),+ Stroke: jest.fn(),+ Style: jest.fn(),+}));++jest.mock('ol/geom', () => ({+ LineString: jest.fn(),+ Polygon: jest.fn(),+}));++jest.mock('../../modules/measure/actions', () => ({+ toggleMeasureActive: jest.fn((v) => ({ type: 'TOGGLE_MEASURE', payload: v })),+ updateMeasurements: jest.fn((m) => ({ type: 'UPDATE_MEASUREMENTS', payload: m })),+}));++import OlMeasureTool from './ol-measure-tool';+import util from '../../util/util';+import {+ transformLineStringArc,+ transformPolygonArc,+ downloadGeoJSON,+} from '../measure-tool/util';+import { areCoordinatesWithinExtent } from '../../modules/location-search/util';+import { unByKey as OlObservableUnByKey } from 'ol/Observable';+import { LineString as OlLineString, Polygon as OlPolygon } from 'ol/geom';+import { Draw as OlDraw } from 'ol/interaction';+import { Vector as OlVectorLayer } from 'ol/layer';+import OlOverlay from 'ol/Overlay';+import {+ MEASURE_DISTANCE,+ MEASURE_AREA,+ MEASURE_CLEAR,+ MEASURE_DOWNLOAD_GEOJSON,+ MAP_DISABLE_CLICK_ZOOM,+ MAP_ENABLE_CLICK_ZOOM,+} from '../../util/constants';+import { CRS } from '../../modules/map/constants';++const { events } = util;++let overlayCount = 0;+let featureCount = 0;+let capturedMeasurements = null;++const makeOlMap = () => ({+ addInteraction: jest.fn(),+ removeInteraction: jest.fn(),+ addOverlay: jest.fn(),+ removeOverlay: jest.fn(),+ on: jest.fn(() => ({ key: 'listener' })),+ un: jest.fn(),+ getCoordinateFromPixel: jest.fn(() => [0, 0]),+});++const makeMap = (olMap) => ({+ rendered: true,+ ui: {+ proj: {+ geographic: olMap,+ arctic: olMap,+ antarctic: olMap,+ },+ },+});++const defaultProjections = [CRS.GEOGRAPHIC, CRS.ARCTIC, CRS.ANTARCTIC];++const buildProps = (overrides = {}) => {+ const olMap = overrides.olMap !== undefined ? overrides.olMap : makeOlMap();+ const userUpdate = overrides.updateMeasurements || jest.fn();+ return {+ olMap,+ map: overrides.map !== undefined ? overrides.map : makeMap(olMap),+ crs: CRS.GEOGRAPHIC,+ unitOfMeasure: 'km',+ toggleMeasureActive: jest.fn(),+ projections: defaultProjections,+ proj: { selected: { crs: CRS.GEOGRAPHIC } },+ ...overrides,+ updateMeasurements: (measurements) => {+ capturedMeasurements = measurements;+ userUpdate(measurements);+ },+ };+};++const renderTool = (overrides = {}) => {+ const props = buildProps(overrides);+ let result;+ act(() => {+ result = render(createElement(OlMeasureTool, props));+ });+ return { ...result, props, olMap: props.olMap };+};++const rerenderTool = (rerender, props) => {+ act(() => { rerender(createElement(OlMeasureTool, props)); });+};++const trigger = (eventName, ...args) => {+ act(() => { events.trigger(eventName, ...args); });+};++const makeLineGeometry = (lastCoord = [10, 20]) => {+ const geom = Object.create(OlLineString.prototype);+ geom.on = jest.fn();+ geom.getLastCoordinate = jest.fn(() => lastCoord);+ geom.changed = jest.fn();+ return geom;+};++const makePolygonGeometry = (interiorCoord = [5, 5]) => {+ const geom = Object.create(OlPolygon.prototype);+ geom.on = jest.fn();+ geom.getInteriorPoint = jest.fn(() => ({ getCoordinates: () => interiorCoord }));+ geom.changed = jest.fn();+ return geom;+};++const makeFeature = (geometry) => {+ featureCount += 1;+ return { getGeometry: jest.fn(() => geometry), ol_uid: `feat-${featureCount}` };+};++const originalConsoleError = console.error;+beforeAll(() => {+ jest.spyOn(console, 'error').mockImplementation((...args) => {+ const msg = typeof args[0] === 'string' ? args[0] : '';+ if (msg.includes('already been passed to createRoot')) return;+ originalConsoleError(...args);+ });+});++afterAll(() => {+ console.error.mockRestore();+});++beforeEach(() => {+ jest.clearAllMocks();+ mockDrawCallbacks = {};+ mockTooltipProps = null;++ OlOverlay.mockImplementation(() => {+ overlayCount += 1;+ const element = document.createElement('div');+ return {+ ol_uid: `overlay-${overlayCount}`,+ element,+ setOffset: jest.fn(),+ setPosition: jest.fn(),+ getElement: () => element,+ };+ });+});++afterEach(() => {+ if (capturedMeasurements) {+ Object.keys(capturedMeasurements).forEach((key) => {+ capturedMeasurements[key] = {};+ });+ }+});++describe('OlMeasureTool', () => {+ describe('rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderTool();+ expect(container.firstChild).toBeNull();+ });++ it('does not throw when map and olMap are null', () => {+ expect(() => renderTool({ map: null, olMap: null })).not.toThrow();+ });++ it('does not throw with an empty projections list', () => {+ expect(() => renderTool({ projections: [] })).not.toThrow();+ });+ });++ describe('event registration', () => {+ it('registers all four measure event handlers when the map is rendered', () => {+ const onSpy = jest.spyOn(events, 'on');+ renderTool();+ const registered = onSpy.mock.calls.map(([evt]) => evt);+ expect(registered).toEqual(expect.arrayContaining([+ MEASURE_DISTANCE, MEASURE_AREA, MEASURE_CLEAR, MEASURE_DOWNLOAD_GEOJSON,+ ]));+ onSpy.mockRestore();+ });++ it('does not register handlers when map.rendered is false', () => {+ const olMap = makeOlMap();+ const onSpy = jest.spyOn(events, 'on');+ renderTool({+ olMap,+ map: {+ rendered: false,+ ui: { proj: { geographic: olMap, arctic: olMap, antarctic: olMap } },+ },+ });+ const registered = onSpy.mock.calls.map(([evt]) => evt);+ expect(registered).not.toContain(MEASURE_DISTANCE);+ onSpy.mockRestore();+ });++ it('deregisters the measure event handlers on unmount', () => {+ const offSpy = jest.spyOn(events, 'off');+ const { unmount } = renderTool();+ act(() => { unmount(); });+ const deregistered = offSpy.mock.calls.map(([evt]) => evt);+ expect(deregistered).toEqual(expect.arrayContaining([+ MEASURE_DISTANCE, MEASURE_AREA, MEASURE_CLEAR, MEASURE_DOWNLOAD_GEOJSON,+ ]));+ offSpy.mockRestore();+ });+ });++ describe('distance measurement', () => {+ it('adds a Draw interaction of type LineString', () => {+ const { olMap } = renderTool();+ trigger(MEASURE_DISTANCE);+ expect(olMap.addInteraction).toHaveBeenCalled();+ expect(OlDraw.mock.calls.at(-1)[0].type).toBe('LineString');+ });++ it('activates measure mode and adds the tooltip overlay', () => {+ const toggleMeasureActive = jest.fn();+ const { olMap } = renderTool({ toggleMeasureActive });+ trigger(MEASURE_DISTANCE);+ expect(toggleMeasureActive).toHaveBeenCalledWith(true);+ expect(olMap.addOverlay).toHaveBeenCalled();+ });++ it('registers a contextmenu listener on the map', () => {+ const { olMap } = renderTool();+ trigger(MEASURE_DISTANCE);+ expect(olMap.on).toHaveBeenCalledWith('contextmenu', expect.any(Function));+ });++ it('removes the previous Draw interaction when restarted', () => {+ const { olMap } = renderTool();+ trigger(MEASURE_DISTANCE);+ olMap.removeInteraction.mockClear();+ trigger(MEASURE_DISTANCE);+ expect(olMap.removeInteraction).toHaveBeenCalled();+ });+ });++ describe('area measurement', () => {+ it('adds a Draw interaction of type Polygon', () => {+ const { olMap } = renderTool();+ trigger(MEASURE_AREA);+ expect(olMap.addInteraction).toHaveBeenCalled();+ expect(OlDraw.mock.calls.at(-1)[0].type).toBe('Polygon');+ });++ it('activates measure mode', () => {+ const toggleMeasureActive = jest.fn();+ renderTool({ toggleMeasureActive });+ trigger(MEASURE_AREA);+ expect(toggleMeasureActive).toHaveBeenCalledWith(true);+ });+ });++ describe('Draw condition function', () => {+ it('checks coordinates against the projection extent', () => {+ const { olMap } = renderTool();+ trigger(MEASURE_DISTANCE);+ const { condition } = OlDraw.mock.calls.at(-1)[0];+ const result = condition({ originalEvent: { x: 100, y: 200 } });+ expect(olMap.getCoordinateFromPixel).toHaveBeenCalledWith([100, 200]);+ expect(areCoordinatesWithinExtent).toHaveBeenCalled();+ expect(result).toBe(true);+ });+ });++ describe('drawstart callback', () => {+ it('disables click-zoom and listens for geometry changes', () => {+ const triggerSpy = jest.spyOn(events, 'trigger');+ renderTool();+ trigger(MEASURE_DISTANCE);++ const geom = makeLineGeometry();+ act(() => { mockDrawCallbacks.drawstart({ feature: makeFeature(geom) }); });++ expect(triggerSpy).toHaveBeenCalledWith(MAP_DISABLE_CLICK_ZOOM);+ expect(geom.on).toHaveBeenCalledWith('change', expect.any(Function));+ triggerSpy.mockRestore();+ });++ it('positions the tooltip at the LineString last coordinate on change', () => {+ const { rerender, props } = renderTool();+ trigger(MEASURE_DISTANCE);+ rerenderTool(rerender, props);++ const overlay = OlOverlay.mock.results.at(-1).value;+ const lastCoord = [99, 88];+ const geom = makeLineGeometry(lastCoord);+ act(() => { mockDrawCallbacks.drawstart({ feature: makeFeature(geom) }); });++ const changeHandler = geom.on.mock.calls.find(([evt]) => evt === 'change')[1];+ act(() => { changeHandler({ target: geom }); });++ expect(overlay.setPosition).toHaveBeenCalledWith(lastCoord);+ });++ it('positions the tooltip at the Polygon interior point on change', () => {+ const { rerender, props } = renderTool();+ trigger(MEASURE_AREA);+ rerenderTool(rerender, props);++ const overlay = OlOverlay.mock.results.at(-1).value;+ const interior = [3, 4];+ const geom = makePolygonGeometry(interior);+ act(() => { mockDrawCallbacks.drawstart({ feature: makeFeature(geom) }); });++ const changeHandler = geom.on.mock.calls.find(([evt]) => evt === 'change')[1];+ act(() => { changeHandler({ target: geom }); });++ expect(overlay.setPosition).toHaveBeenCalledWith(interior);+ });+ });++ describe('drawend callback', () => {+ const startAndEnd = () => {+ const userUpdate = jest.fn();+ const toggleMeasureActive = jest.fn();+ const {+ rerender, props,+ } = renderTool({ updateMeasurements: userUpdate, toggleMeasureActive });+ trigger(MEASURE_DISTANCE);+ rerenderTool(rerender, props);++ const overlay = OlOverlay.mock.results.at(-1).value;+ const triggerSpy = jest.spyOn(events, 'trigger');+ act(() => { mockDrawCallbacks.drawend({ feature: makeFeature(makeLineGeometry()) }); });+ return {+ overlay, userUpdate, toggleMeasureActive, triggerSpy,+ };+ };++ it('offsets the overlay and stores the measurement', () => {+ const { overlay, userUpdate } = startAndEnd();+ expect(overlay.setOffset).toHaveBeenCalledWith([0, -7]);+ expect(userUpdate).toHaveBeenCalled();+ });++ it('terminates the draw (deactivates and re-enables click zoom)', () => {+ const { toggleMeasureActive, triggerSpy } = startAndEnd();+ expect(toggleMeasureActive).toHaveBeenCalledWith(false);+ expect(triggerSpy).toHaveBeenCalledWith(MAP_ENABLE_CLICK_ZOOM);+ triggerSpy.mockRestore();+ });+ });++ describe('contextmenu (right-click) handling', () => {+ it('terminates the draw and removes the overlay on right-click', () => {+ const toggleMeasureActive = jest.fn();+ const { olMap } = renderTool({ toggleMeasureActive });+ trigger(MEASURE_DISTANCE);++ const contextHandler = olMap.on.mock.calls.find(([evt]) => evt === 'contextmenu')[1];+ const preventDefault = jest.fn();+ const triggerSpy = jest.spyOn(events, 'trigger');+ olMap.removeOverlay.mockClear();+ toggleMeasureActive.mockClear();++ act(() => { contextHandler({ preventDefault }); });++ expect(preventDefault).toHaveBeenCalled();+ expect(toggleMeasureActive).toHaveBeenCalledWith(false);+ expect(olMap.removeOverlay).toHaveBeenCalled();+ expect(OlObservableUnByKey).toHaveBeenCalled();+ expect(triggerSpy).toHaveBeenCalledWith(MAP_ENABLE_CLICK_ZOOM);+ triggerSpy.mockRestore();+ });+ });++ describe('clear measurements', () => {+ it('clears stored measurements and deactivates measure mode', () => {+ const userUpdate = jest.fn();+ const toggleMeasureActive = jest.fn();+ const { olMap } = renderTool({ updateMeasurements: userUpdate, toggleMeasureActive });+ trigger(MEASURE_DISTANCE);+ userUpdate.mockClear();+ toggleMeasureActive.mockClear();+ olMap.removeOverlay.mockClear();++ trigger(MEASURE_CLEAR);++ expect(userUpdate).toHaveBeenCalled();+ expect(toggleMeasureActive).toHaveBeenCalledWith(false);+ expect(olMap.removeOverlay).toHaveBeenCalled();+ });++ it('tears down the vector layer when one exists', () => {+ renderTool();+ trigger(MEASURE_DISTANCE);+ const layerInstance = OlVectorLayer.mock.results.at(-1).value;+ trigger(MEASURE_CLEAR);+ expect(layerInstance.setMap).toHaveBeenCalledWith(null);+ });+ });++ describe('download GeoJSON', () => {+ it('calls downloadGeoJSON for the current projection', () => {+ renderTool();+ trigger(MEASURE_DOWNLOAD_GEOJSON);+ expect(downloadGeoJSON).toHaveBeenCalledWith(expect.anything(), CRS.GEOGRAPHIC);+ });+ });++ describe('styleGeometryFn', () => {+ const getStyleGeometryFn = () => {+ const { Style } = require('ol/style');+ const call = Style.mock.calls.find((args) => args[0] && args[0].geometry);+ return call[0].geometry;+ };++ it('applies a great-circle arc to LineString geometry', () => {+ renderTool();+ const fn = getStyleGeometryFn();+ const geom = Object.create(OlLineString.prototype);+ fn({ getGeometry: () => geom });+ expect(transformLineStringArc).toHaveBeenCalledWith(geom, CRS.GEOGRAPHIC);+ });++ it('applies a great-circle arc to Polygon geometry', () => {+ renderTool();+ const fn = getStyleGeometryFn();+ const geom = Object.create(OlPolygon.prototype);+ fn({ getGeometry: () => geom });+ expect(transformPolygonArc).toHaveBeenCalledWith(geom, CRS.GEOGRAPHIC);+ });++ it('passes other geometry types through unchanged', () => {+ renderTool();+ const fn = getStyleGeometryFn();+ const geom = { type: 'Point' };+ expect(fn({ getGeometry: () => geom })).toBe(geom);+ });+ });++ describe('projection change', () => {+ it('terminates the in-progress draw when the crs changes', () => {+ const olMap = makeOlMap();+ const { rerender, props } = renderTool({ olMap });+ trigger(MEASURE_DISTANCE);+ olMap.removeInteraction.mockClear();++ rerenderTool(rerender, {+ ...props,+ crs: CRS.ARCTIC,+ proj: { selected: { crs: CRS.ARCTIC } },+ });++ expect(olMap.removeInteraction).toHaveBeenCalled();+ });+ });++ describe('recalculateAllMeasurements', () => {+ it('re-renders stored measurements when the unit of measure changes', () => {+ const { rerender, props } = renderTool({ unitOfMeasure: 'km' });+ trigger(MEASURE_DISTANCE);+ rerenderTool(rerender, props);++ const geom = makeLineGeometry();+ act(() => { mockDrawCallbacks.drawend({ feature: makeFeature(geom) }); });++ expect(() => {+ rerenderTool(rerender, { ...props, unitOfMeasure: 'mi' });+ }).not.toThrow();+ expect(geom.changed).toHaveBeenCalled();+ });+ });++ describe('removing an individual measurement', () => {+ it('removes the feature and overlay via the tooltip onRemove callback', () => {+ const userUpdate = jest.fn();+ const { rerender, props } = renderTool({ updateMeasurements: userUpdate });+ trigger(MEASURE_DISTANCE);+ rerenderTool(rerender, props);++ const { olMap } = props;+ act(() => { mockDrawCallbacks.drawend({ feature: makeFeature(makeLineGeometry()) }); });++ expect(mockTooltipProps).not.toBeNull();+ olMap.removeOverlay.mockClear();+ userUpdate.mockClear();+ act(() => { mockTooltipProps.onRemove(); });++ expect(olMap.removeOverlay).toHaveBeenCalled();+ expect(userUpdate).toHaveBeenCalled();+ });+ });++ describe('clearing stored measurements', () => {+ it('removes the overlay for each stored measurement', () => {+ const { rerender, props } = renderTool();+ trigger(MEASURE_DISTANCE);+ rerenderTool(rerender, props);++ const overlay = OlOverlay.mock.results.at(-1).value;+ act(() => { mockDrawCallbacks.drawend({ feature: makeFeature(makeLineGeometry()) }); });++ const { olMap } = props;+ olMap.removeOverlay.mockClear();+ trigger(MEASURE_CLEAR);++ expect(olMap.removeOverlay).toHaveBeenCalledWith(overlay);+ });+ });++ describe('projection change with an active tooltip', () => {+ it('removes the tooltip overlay when a tooltip-active element exists', () => {+ const olMap = makeOlMap();+ const { rerender, props } = renderTool({ olMap });+ trigger(MEASURE_DISTANCE);++ const activeEl = document.createElement('div');+ activeEl.className = 'tooltip-active';+ document.body.appendChild(activeEl);+ olMap.removeOverlay.mockClear();++ rerenderTool(rerender, {+ ...props,+ crs: CRS.ARCTIC,+ proj: { selected: { crs: CRS.ARCTIC } },+ });++ expect(olMap.removeOverlay).toHaveBeenCalled();+ document.body.removeChild(activeEl);+ });+ });++ describe('redux bindings', () => {+ it('mapStateToProps selects the expected slice of state', () => {+ const state = {+ map: { ui: { selected: { id: 'olMap' } }, rendered: true },+ proj: { selected: { crs: CRS.ARCTIC } },+ measure: { unitOfMeasure: 'mi' },+ config: {+ projections: {+ geographic: { crs: CRS.GEOGRAPHIC },+ arctic: { crs: CRS.ARCTIC },+ },+ },+ };+ const result = globalThis.measureConnectArgs.mapStateToProps(state);+ expect(result.crs).toBe(CRS.ARCTIC);+ expect(result.unitOfMeasure).toBe('mi');+ expect(result.olMap).toBe(state.map.ui.selected);+ expect(result.projections).toEqual([CRS.GEOGRAPHIC, CRS.ARCTIC]);+ });++ it('mapDispatchToProps dispatches the measure actions', () => {+ const dispatch = jest.fn();+ const bound = globalThis.measureConnectArgs.mapDispatchToProps(dispatch);+ bound.toggleMeasureActive(true);+ bound.updateMeasurements({ foo: 'bar' });+ expect(dispatch).toHaveBeenCalledTimes(2);+ });+ });});diff --git a/web/js/components/map/rotation.test.js b/web/js/components/map/rotation.test.jsindex 68233b2f7..31e5e733a 100644--- a/web/js/components/map/rotation.test.js+++ b/web/js/components/map/rotation.test.js@@ -1,3 +1,184 @@-test('rotation component test', () => {+import { render, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+jest.mock('../../map/util', () => ({+ saveRotation: jest.fn(),+}));+jest.mock('../../modules/map/actions', () => ({+ refreshRotation: jest.fn((r) => ({ type: 'REFRESH_ROTATION', payload: r })),+}));+jest.mock('../util/hover-tooltip', () => () => null);+jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: () => null,+}));+jest.mock('lodash', () => ({+ debounce: (fn) => fn,+}));++let mockMap;+let mockProj;+let mockRotation;+let mockIsDistractionFreeModeActive;+let mockIsMobile;+const mockDispatch = jest.fn();++jest.mock('react-redux', () => ({+ useSelector: (selector) => selector({+ map: { ui: { selected: mockMap }, rotation: mockRotation },+ proj: mockProj,+ ui: { isDistractionFreeModeActive: mockIsDistractionFreeModeActive },+ screenSize: { isMobileDevice: mockIsMobile },+ }),+ useDispatch: () => mockDispatch,+ shallowEqual: (a, b) => a === b,+}));++import Rotation from './rotation';++const makeMockMap = () => {+ const animate = jest.fn();+ const getRotation = jest.fn(() => 0);+ const getView = jest.fn(() => ({ animate, getRotation }));+ return { getView, animate };+};++const renderRotation = () => render(<Rotation />);++describe('Rotation component', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockMap = makeMockMap();+ mockProj = { id: 'arctic' };+ mockRotation = 0;+ mockIsDistractionFreeModeActive = false;+ mockIsMobile = false;+ });++ describe('visibility', () => {+ it('renders rotation buttons for polar projection', () => {+ const { container } = renderRotation();+ expect(container.firstChild).toBeInTheDocument();+ });++ it('does not render for geographic projection', () => {+ mockProj = { id: 'geographic' };+ const { container } = renderRotation();+ expect(container.firstChild).toBeNull();+ });++ it('does not render for webmerc projection', () => {+ mockProj = { id: 'webmerc' };+ const { container } = renderRotation();+ expect(container.firstChild).toBeNull();+ });++ it('does not render when distraction free mode is active', () => {+ mockIsDistractionFreeModeActive = true;+ const { container } = renderRotation();+ expect(container.firstChild).toBeNull();+ });++ it('renders for antarctic projection', () => {+ mockProj = { id: 'antarctic' };+ const { container } = renderRotation();+ expect(container.firstChild).toBeInTheDocument();+ });+ });++ describe('button classes', () => {+ it('uses mobile class when isMobile is true', () => {+ mockIsMobile = true;+ const { container } = renderRotation();+ expect(container.firstChild).toHaveClass('wv-rotation-buttons-mobile');+ });++ it('uses desktop class when isMobile is false', () => {+ mockIsMobile = false;+ const { container } = renderRotation();+ expect(container.firstChild).toHaveClass('wv-rotation-buttons');+ });+ });++ describe('rotation display', () => {+ it('shows 0 degrees when rotation is 0 radians', () => {+ mockRotation = 0;+ const { getByRole } = renderRotation();+ const resetButton = getByRole('button', { name: /0/i });+ expect(resetButton).toBeInTheDocument();+ });++ it('shows correct degrees when rotation is Math.PI (180 degrees)', () => {+ mockRotation = Math.PI;+ const { container } = renderRotation();+ const resetButton = container.querySelector('.wv-map-reset-rotation');+ expect(resetButton.textContent).toBe('180');+ });+ });++ describe('button interaction', () => {+ it('renders left rotate button', () => {+ const { container } = renderRotation();+ expect(container.querySelector('.wv-map-rotate-left')).toBeInTheDocument();+ });++ it('renders right rotate button', () => {+ const { container } = renderRotation();+ expect(container.querySelector('.wv-map-rotate-right')).toBeInTheDocument();+ });++ it('renders reset rotation button', () => {+ const { container } = renderRotation();+ expect(container.querySelector('.wv-map-reset-rotation')).toBeInTheDocument();+ });++ it('calls map.getView().animate on reset button mousedown', () => {+ const { container } = renderRotation();+ const resetBtn = container.querySelector('.wv-map-reset-rotation');+ fireEvent.mouseDown(resetBtn);+ expect(mockMap.getView().animate).toHaveBeenCalledWith({ duration: 500, rotation: 0 });+ });++ it('calls map.getView().animate on left rotate mousedown', () => {+ const { container } = renderRotation();+ const leftBtn = container.querySelector('.wv-map-rotate-left');+ act(() => { fireEvent.mouseDown(leftBtn); });+ expect(mockMap.getView().animate).toHaveBeenCalled();+ });++ it('calls map.getView().animate on right rotate mousedown', () => {+ const { container } = renderRotation();+ const rightBtn = container.querySelector('.wv-map-rotate-right');+ act(() => { fireEvent.mouseDown(rightBtn); });+ expect(mockMap.getView().animate).toHaveBeenCalled();+ });++ it('calls clearInterval on mouseup of rotate left', () => {+ const clearIntervalSpy = jest.spyOn(window, 'clearInterval');+ const { container } = renderRotation();+ const leftBtn = container.querySelector('.wv-map-rotate-left');+ act(() => { fireEvent.mouseDown(leftBtn); });+ fireEvent.mouseUp(leftBtn);+ expect(clearIntervalSpy).toHaveBeenCalled();+ clearIntervalSpy.mockRestore();+ });++ it('calls clearInterval on mouseout of rotate right', () => {+ const clearIntervalSpy = jest.spyOn(window, 'clearInterval');+ const { container } = renderRotation();+ const rightBtn = container.querySelector('.wv-map-rotate-right');+ act(() => { fireEvent.mouseDown(rightBtn); });+ fireEvent.mouseOut(rightBtn);+ expect(clearIntervalSpy).toHaveBeenCalled();+ clearIntervalSpy.mockRestore();+ });++ it('stops propagation on mouse move', () => {+ const { container } = renderRotation();+ const leftBtn = container.querySelector('.wv-map-rotate-left');+ const event = new MouseEvent('mousemove', { bubbles: true });+ const stopPropagation = jest.spyOn(event, 'stopPropagation');+ leftBtn.dispatchEvent(event);+ expect(stopPropagation).toHaveBeenCalled();+ });+ });});diff --git a/web/js/components/map/zoom.test.js b/web/js/components/map/zoom.test.jsindex f4fb326a6..423b8a24e 100644--- a/web/js/components/map/zoom.test.js+++ b/web/js/components/map/zoom.test.js@@ -1,3 +1,182 @@-test('zoom component test', () => {+import { render, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+jest.mock('../../map/util', () => ({+ mapUtilZoomAction: jest.fn(),+}));+jest.mock('../util/hover-tooltip', () => () => null);+jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: () => null,+}));+jest.mock('react-redux', () => ({+ connect: (mapStateToProps) => {+ globalThis.zoomMapStateToProps = mapStateToProps;+ return (Component) => Component;+ },+}));++import Zoom from './zoom';+import { mapUtilZoomAction } from '../../map/util';++const makeMap = (zoom = 5) => ({+ getView: () => ({+ getZoom: () => zoom,+ animate: jest.fn(),+ }),+});++const renderZoom = ({+ map = makeMap(5),+ zoomLevel = 5,+ numZoomLevels = 10,+ isDistractionFreeModeActive = false,+ isMobile = false,+ isChartingActive = false,+} = {}) => render(+ <Zoom+ map={map}+ zoomLevel={zoomLevel}+ numZoomLevels={numZoomLevels}+ isDistractionFreeModeActive={isDistractionFreeModeActive}+ isMobile={isMobile}+ isChartingActive={isChartingActive}+ />,+);++describe('Zoom component', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe('rendering', () => {+ it('renders zoom in and zoom out buttons', () => {+ const { getByLabelText } = renderZoom();+ expect(getByLabelText('Zoom in view')).toBeInTheDocument();+ expect(getByLabelText('Zoom out view')).toBeInTheDocument();+ });++ it('returns null when map is not provided', () => {+ const { container } = renderZoom({ map: null });+ expect(container.firstChild).toBeNull();+ });++ it('returns null when distraction free mode is active', () => {+ const { container } = renderZoom({ isDistractionFreeModeActive: true });+ expect(container.firstChild).toBeNull();+ });++ it('returns null when charting mode is active', () => {+ const { container } = renderZoom({ isChartingActive: true });+ expect(container.firstChild).toBeNull();+ });++ it('uses mobile class when isMobile is true', () => {+ const { container } = renderZoom({ isMobile: true });+ expect(container.firstChild).toHaveClass('wv-zoom-buttons-mobile');+ });++ it('uses desktop class when isMobile is false', () => {+ const { container } = renderZoom({ isMobile: false });+ expect(container.firstChild).toHaveClass('wv-zoom-buttons');+ });+ });++ describe('disabled states', () => {+ it('disables zoom in button when at max zoom level', () => {+ const { getByLabelText } = renderZoom({ zoomLevel: 10, numZoomLevels: 10 });+ expect(getByLabelText('Zoom in view')).toBeDisabled();+ });++ it('disables zoom out button when at zoom level 0', () => {+ const { getByLabelText } = renderZoom({ zoomLevel: 0 });+ expect(getByLabelText('Zoom out view')).toBeDisabled();+ });++ it('does not disable zoom in button below max zoom', () => {+ const { getByLabelText } = renderZoom({ zoomLevel: 5, numZoomLevels: 10 });+ expect(getByLabelText('Zoom in view')).not.toBeDisabled();+ });++ it('does not disable zoom out button above zoom 0', () => {+ const { getByLabelText } = renderZoom({ zoomLevel: 1 });+ expect(getByLabelText('Zoom out view')).not.toBeDisabled();+ });+ });++ describe('click handlers', () => {+ it('calls mapUtilZoomAction with +1 when zoom in is clicked', () => {+ const map = makeMap(5);+ const { getByLabelText } = renderZoom({ map });+ fireEvent.click(getByLabelText('Zoom in view'));+ expect(mapUtilZoomAction).toHaveBeenCalledWith(map, 1);+ });++ it('calls mapUtilZoomAction with -1 when zoom out is clicked', () => {+ const map = makeMap(5);+ const { getByLabelText } = renderZoom({ map });+ fireEvent.click(getByLabelText('Zoom out view'));+ expect(mapUtilZoomAction).toHaveBeenCalledWith(map, -1);+ });++ it('does not call mapUtilZoomAction when zoom in is disabled', () => {+ const map = makeMap(10);+ const { getByLabelText } = renderZoom({ map, zoomLevel: 10, numZoomLevels: 10 });+ fireEvent.click(getByLabelText('Zoom in view'));+ expect(mapUtilZoomAction).not.toHaveBeenCalled();+ });++ it('does not call mapUtilZoomAction when zoom out is disabled', () => {+ const map = makeMap(0);+ const { getByLabelText } = renderZoom({ map, zoomLevel: 0 });+ fireEvent.click(getByLabelText('Zoom out view'));+ expect(mapUtilZoomAction).not.toHaveBeenCalled();+ });+ });++ describe('mouse move event', () => {+ it('stops propagation on mouse move over zoom in button', () => {+ const { getByLabelText } = renderZoom();+ const event = new MouseEvent('mousemove', { bubbles: true });+ const stopPropagation = jest.spyOn(event, 'stopPropagation');+ getByLabelText('Zoom in view').dispatchEvent(event);+ expect(stopPropagation).toHaveBeenCalled();+ });++ it('stops propagation on mouse move over zoom out button', () => {+ const { getByLabelText } = renderZoom();+ const event = new MouseEvent('mousemove', { bubbles: true });+ const stopPropagation = jest.spyOn(event, 'stopPropagation');+ getByLabelText('Zoom out view').dispatchEvent(event);+ expect(stopPropagation).toHaveBeenCalled();+ });+ });++ describe('mapStateToProps', () => {+ const makeState = (overrides = {}) => ({+ screenSize: { isMobileDevice: true },+ map: { ui: { selected: makeMap(7) } },+ proj: { selected: { numZoomLevels: 12 } },+ ui: { isDistractionFreeModeActive: true },+ charting: { active: false },+ ...overrides,+ });++ it('maps the selected map and derived zoom state', () => {+ const state = makeState();+ const props = globalThis.zoomMapStateToProps(state);+ expect(props.map).toBe(state.map.ui.selected);+ expect(props.zoomLevel).toBe(7);+ expect(props.numZoomLevels).toBe(12);+ expect(props.isDistractionFreeModeActive).toBe(true);+ expect(props.isMobile).toBe(true);+ expect(props.isChartingActive).toBe(false);+ });++ it('returns a null zoom level when no map is selected', () => {+ const state = makeState({ map: { ui: { selected: null } } });+ const props = globalThis.zoomMapStateToProps(state);+ expect(props.map).toBeNull();+ expect(props.zoomLevel).toBeNull();+ });+ });});diff --git a/web/js/components/measure-tool/measure-button.test.js b/web/js/components/measure-tool/measure-button.test.jsindex caed2c8de..ed9972210 100644--- a/web/js/components/measure-tool/measure-button.test.js+++ b/web/js/components/measure-tool/measure-button.test.js@@ -1,3 +1,162 @@-test('measure-button component test', () => {+/* eslint-disable react/prop-types */+import '@testing-library/jest-dom';+import { render, screen, fireEvent } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureStore from 'redux-mock-store';+import MeasureButton from './measure-button';+import googleTagManager from 'googleTagManager';+jest.mock('googleTagManager', () => ({ pushEvent: jest.fn() }));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon, size }) => <svg data-testid={`icon-${icon}`} data-size={size} />,+}));++jest.mock('reactstrap', () => ({+ Button: ({ children, disabled, onMouseDown, onTouchEnd, style, ...rest }) => (+ <button+ type="button"+ disabled={disabled}+ onMouseDown={onMouseDown}+ onTouchEnd={onTouchEnd}+ style={style}+ aria-label={rest['aria-label']}+ >+ {children}+ </button>+ ),+ UncontrolledTooltip: ({ children }) => <div>{children}</div>,+}));++jest.mock('../util/alert', () => function MockAlert({ id, message, onDismiss }) {+ return (+ <div data-testid={id}>+ <span data-testid="alert-message">{message}</span>+ <button type="button" data-testid="dismiss-btn" onClick={onDismiss}>dismiss</button>+ </div>+ );+});++jest.mock('../../modules/modal/actions', () => ({+ openCustomContent: jest.fn((id, props) => ({ type: 'OPEN_CUSTOM_CONTENT', id, props })),+}));++const mockStore = configureStore([]);++const defaultState = {+ measure: { isActive: false },+ ui: { isDistractionFreeModeActive: false },+ screenSize: { isMobileDevice: false },+};++function renderButton(stateOverrides = {}) {+ const store = mockStore({ ...defaultState, ...stateOverrides });+ const utils = render(+ <Provider store={store}>+ <MeasureButton />+ </Provider>,+ );+ return { ...utils, store };+}++describe('MeasureButton', () => {+ beforeEach(() => jest.clearAllMocks());++ describe('rendering', () => {+ it('renders the measure button', () => {+ renderButton();+ expect(screen.getByRole('button', { name: 'Measure distances & areas' })).toBeInTheDocument();+ });++ it('does not render alert when measure tool is not active', () => {+ renderButton();+ expect(screen.queryByTestId('measurement-alert')).toBeNull();+ });++ it('hides the button in distraction-free mode', () => {+ renderButton({ ui: { isDistractionFreeModeActive: true } });+ expect(screen.queryByRole('button', { name: 'Measure distances & areas' })).toBeNull();+ });++ it('disables the button when measure tool is already active', () => {+ renderButton({ measure: { isActive: true } });+ expect(screen.getByRole('button', { name: 'Measure distances & areas' })).toBeDisabled();+ });++ it('renders a 1x icon on desktop', () => {+ renderButton({ screenSize: { isMobileDevice: false } });+ expect(screen.getByTestId('icon-ruler')).toHaveAttribute('data-size', '1x');+ });++ it('renders a 2x icon on mobile', () => {+ renderButton({ screenSize: { isMobileDevice: true } });+ expect(screen.getByTestId('icon-ruler')).toHaveAttribute('data-size', '2x');+ });+ });++ describe('mouse interaction', () => {+ it('dispatches openCustomContent on mouse down', () => {+ const { store } = renderButton();+ fireEvent.mouseDown(screen.getByRole('button', { name: 'Measure distances & areas' }));+ const actions = store.getActions();+ expect(actions).toHaveLength(1);+ expect(actions[0]).toEqual(expect.objectContaining({ type: 'OPEN_CUSTOM_CONTENT', id: 'MEASURE_MENU' }));+ });++ it('fires GTM event on mouse down', () => {+ renderButton();+ fireEvent.mouseDown(screen.getByRole('button', { name: 'Measure distances & areas' }));+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'measure_tool_activated' });+ });++ it('shows desktop help message after mouse down when tool becomes active', () => {+ const store = mockStore({ ...defaultState, measure: { isActive: true } });+ render(<Provider store={store}><MeasureButton /></Provider>);+ fireEvent.mouseDown(screen.getByRole('button', { name: 'Measure distances & areas' }));+ expect(screen.getByTestId('alert-message')).toHaveTextContent(+ 'Click: Add a point. Right-click: Cancel. Double-click to complete.',+ );+ });++ it('dismisses the alert when dismiss is clicked', () => {+ const store = mockStore({ ...defaultState, measure: { isActive: true } });+ render(<Provider store={store}><MeasureButton /></Provider>);+ fireEvent.mouseDown(screen.getByRole('button', { name: 'Measure distances & areas' }));+ expect(screen.getByTestId('measurement-alert')).toBeInTheDocument();+ fireEvent.click(screen.getByTestId('dismiss-btn'));+ expect(screen.queryByTestId('measurement-alert')).toBeNull();+ });+ });++ describe('touch interaction', () => {+ it('dispatches openCustomContent on touch end', () => {+ const { store } = renderButton();+ fireEvent.touchEnd(screen.getByRole('button', { name: 'Measure distances & areas' }));+ const actions = store.getActions();+ expect(actions[0]).toEqual(expect.objectContaining({ type: 'OPEN_CUSTOM_CONTENT', id: 'MEASURE_MENU' }));+ });++ it('shows mobile help message after touch end when tool becomes active', () => {+ const store = mockStore({ ...defaultState, measure: { isActive: true } });+ render(<Provider store={store}><MeasureButton /></Provider>);+ fireEvent.touchEnd(screen.getByRole('button', { name: 'Measure distances & areas' }));+ expect(screen.getByTestId('alert-message')).toHaveTextContent(+ 'Tap to add a point. Double-tap to complete.',+ );+ });++ it('sets touchDevice prop to true in MEASURE_MENU_PROPS on touch end', () => {+ const { store } = renderButton();+ fireEvent.touchEnd(screen.getByRole('button', { name: 'Measure distances & areas' }));+ const actions = store.getActions();+ expect(actions[0].props.touchDevice).toBe(true);+ });++ it('sets touchDevice prop to false on mouse down', () => {+ const { store } = renderButton();+ fireEvent.mouseDown(screen.getByRole('button', { name: 'Measure distances & areas' }));+ const actions = store.getActions();+ expect(actions[0].props.touchDevice).toBe(false);+ });+ });});diff --git a/web/js/components/measure-tool/measure-menu.test.js b/web/js/components/measure-tool/measure-menu.test.jsindex fb6b10761..1fd2c9a46 100644--- a/web/js/components/measure-tool/measure-menu.test.js+++ b/web/js/components/measure-tool/measure-menu.test.js@@ -1,3 +1,199 @@-test('measure-menu component test', () => {+/* eslint-disable react/prop-types */+import '@testing-library/jest-dom';+import { render, screen, fireEvent } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureStore from 'redux-mock-store';+import MeasureMenu from './measure-menu';+jest.mock('../../modules/modal/actions', () => ({+ onToggle: jest.fn(() => ({ type: 'ON_TOGGLE' })),+}));++jest.mock('../../modules/measure/actions', () => ({+ changeUnits: jest.fn((units) => ({ type: 'CHANGE_UNITS', units })),+}));++jest.mock('../../util/util', () => ({+ events: { trigger: jest.fn() },+}));++jest.mock('../util/icon-list', () => function MockIconList({ list, onClick, size }) {+ return (+ <ul data-testid="icon-list" data-size={size}>+ {list.filter((item) => !item.hidden).map((item) => (+ <li key={item.key}>+ <button type="button" data-testid={item.id} onClick={() => onClick(item.key)}>+ {item.text}+ </button>+ </li>+ ))}+ </ul>+ );+});++const mockStore = configureStore([]);++const defaultState = {+ screenSize: { isMobileDevice: false },+ modal: { customProps: { touchDevice: false } },+ measure: {+ unitOfMeasure: 'km',+ allMeasurements: { 'EPSG:4326': {} },+ },+ proj: { selected: { crs: 'EPSG:4326' } },+};++function renderMenu(stateOverrides = {}) {+ const state = {+ ...defaultState,+ ...stateOverrides,+ measure: { ...defaultState.measure, ...(stateOverrides.measure || {}) },+ modal: { ...defaultState.modal, ...(stateOverrides.modal || {}) },+ };+ const store = mockStore(state);+ const utils = render(+ <Provider store={store}>+ <MeasureMenu />+ </Provider>,+ );+ return { ...utils, store };+}++describe('MeasureMenu', () => {+ beforeEach(() => jest.clearAllMocks());++ describe('rendering', () => {+ it('renders the unit toggle switch', () => {+ renderMenu();+ expect(screen.getByRole('checkbox', { name: /km/i })).toBeInTheDocument();+ });++ it('shows km label when unitOfMeasure is km', () => {+ renderMenu();+ expect(screen.getByText('km')).toBeInTheDocument();+ });++ it('shows mi label when unitOfMeasure is mi', () => {+ renderMenu({ measure: { unitOfMeasure: 'mi', allMeasurements: { 'EPSG:4326': {} } } });+ expect(screen.getByText('mi')).toBeInTheDocument();+ });++ it('unit toggle is unchecked when unit is km', () => {+ renderMenu();+ expect(screen.getByRole('checkbox')).not.toBeChecked();+ });++ it('unit toggle is checked when unit is mi', () => {+ renderMenu({ measure: { unitOfMeasure: 'mi', allMeasurements: { 'EPSG:4326': {} } } });+ expect(screen.getByRole('checkbox')).toBeChecked();+ });++ it('renders the distance and area measure buttons', () => {+ renderMenu();+ expect(screen.getByTestId('measure-distance-button')).toBeInTheDocument();+ expect(screen.getByTestId('measure-area-button')).toBeInTheDocument();+ });++ it('hides remove-measurements button when no measurements exist', () => {+ renderMenu();+ expect(screen.queryByTestId('clear-measurements-button')).toBeNull();+ });++ it('shows remove-measurements button when measurements exist', () => {+ renderMenu({+ measure: {+ unitOfMeasure: 'km',+ allMeasurements: { 'EPSG:4326': { m1: {} } },+ },+ });+ expect(screen.getByTestId('clear-measurements-button')).toBeInTheDocument();+ });++ it('hides download-geojson button when no measurements exist', () => {+ renderMenu();+ expect(screen.queryByTestId('download-geojson-button')).toBeNull();+ });++ it('shows download-geojson button when measurements exist and not mobile', () => {+ renderMenu({+ measure: {+ unitOfMeasure: 'km',+ allMeasurements: { 'EPSG:4326': { m1: {} } },+ },+ screenSize: { isMobileDevice: false },+ });+ expect(screen.getByTestId('download-geojson-button')).toBeInTheDocument();+ });++ it('hides download-geojson button on mobile even when measurements exist', () => {+ renderMenu({+ measure: {+ unitOfMeasure: 'km',+ allMeasurements: { 'EPSG:4326': { m1: {} } },+ },+ screenSize: { isMobileDevice: true },+ });+ expect(screen.queryByTestId('download-geojson-button')).toBeNull();+ });+ });++ describe('icon list size', () => {+ it('uses small icon list for non-touch devices', () => {+ renderMenu({ modal: { customProps: { touchDevice: false } } });+ expect(screen.getByTestId('icon-list')).toHaveAttribute('data-size', 'small');+ });++ it('uses large icon list for touch devices', () => {+ renderMenu({ modal: { customProps: { touchDevice: true } } });+ expect(screen.getByTestId('icon-list')).toHaveAttribute('data-size', 'large');+ });+ });++ describe('interactions', () => {+ it('dispatches changeUnits with mi when toggle is checked', () => {+ const { store } = renderMenu();+ fireEvent.click(screen.getByRole('checkbox'));+ const actions = store.getActions();+ expect(actions).toContainEqual(expect.objectContaining({ type: 'CHANGE_UNITS', units: 'mi' }));+ });++ it('dispatches changeUnits with km when toggle is unchecked', () => {+ const { store } = renderMenu({ measure: { unitOfMeasure: 'mi', allMeasurements: { 'EPSG:4326': {} } } });+ fireEvent.click(screen.getByRole('checkbox'));+ const actions = store.getActions();+ expect(actions).toContainEqual(expect.objectContaining({ type: 'CHANGE_UNITS', units: 'km' }));+ });++ it('triggers measure:distance event and closes modal on distance button click', () => {+ const util = require('../../util/util');+ const { store } = renderMenu();+ fireEvent.click(screen.getByTestId('measure-distance-button'));+ expect(util.events.trigger).toHaveBeenCalledWith('measure:distance');+ const actions = store.getActions();+ expect(actions).toContainEqual(expect.objectContaining({ type: 'ON_TOGGLE' }));+ });++ it('triggers measure:area event and closes modal on area button click', () => {+ const util = require('../../util/util');+ const { store } = renderMenu();+ fireEvent.click(screen.getByTestId('measure-area-button'));+ expect(util.events.trigger).toHaveBeenCalledWith('measure:area');+ const actions = store.getActions();+ expect(actions).toContainEqual(expect.objectContaining({ type: 'ON_TOGGLE' }));+ });++ it('triggers measure:clear event on remove-measurements click', () => {+ const util = require('../../util/util');+ const { store } = renderMenu({+ measure: {+ unitOfMeasure: 'km',+ allMeasurements: { 'EPSG:4326': { m1: {} } },+ },+ });+ fireEvent.click(screen.getByTestId('clear-measurements-button'));+ expect(util.events.trigger).toHaveBeenCalledWith('measure:clear');+ const actions = store.getActions();+ expect(actions).toContainEqual(expect.objectContaining({ type: 'ON_TOGGLE' }));+ });+ });});diff --git a/web/js/components/measure-tool/measure-tooltip.test.js b/web/js/components/measure-tool/measure-tooltip.test.jsindex 4759d5b2e..f5745e814 100644--- a/web/js/components/measure-tool/measure-tooltip.test.js+++ b/web/js/components/measure-tool/measure-tooltip.test.js@@ -1,3 +1,209 @@-test('measure-tooltip component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import '@testing-library/jest-dom';+import { render, fireEvent, cleanup } from '@testing-library/react';+import { LineString as OlLineString, Polygon as OlGeomPolygon } from 'ol/geom';+import MeasureTooltip from './measure-tooltip';+import { registerProjections } from '../../fixtures';+beforeEach(registerProjections);+afterEach(cleanup);++const GEO = 'EPSG:4326';+const makeLine = (coords) => new OlLineString(coords);+const makePoly = (coords) => new OlGeomPolygon([coords]);++const longLineCoords = [[-74, 40], [0, 51]]; // ~7,500 km+const smallPolyCoords = [[0, 0], [1, 0], [0, 1], [0, 0]];++const geographicProj = {+ selected: { crs: GEO, maxExtent: [-180, -90, 180, 90] },+};++function renderTooltip(overrides = {}) {+ const props = {+ active: true,+ crs: GEO,+ unitOfMeasure: 'km',+ geometry: makeLine(longLineCoords),+ onRemove: jest.fn(),+ proj: geographicProj,+ ...overrides,+ };+ const { container } = render(<MeasureTooltip {...props} />);+ return { container, props };+}++const q = (container, sel) => container.querySelector(sel);++describe('MeasureTooltip', () => {+ describe('rendering', () => {+ it('renders a measurement for a LineString', () => {+ const { container } = renderTooltip();+ expect(q(container, '.tooltip-measure')).toBeInTheDocument();+ });++ it('renders a measurement for a Polygon', () => {+ const { container } = renderTooltip({ geometry: makePoly(smallPolyCoords) });+ expect(q(container, '.tooltip-measure')).toBeInTheDocument();+ });++ it('applies tooltip-active class when active is true', () => {+ const { container } = renderTooltip({ active: true });+ expect(q(container, '.tooltip-active')).toBeInTheDocument();+ });++ it('applies tooltip-static class when active is false', () => {+ const { container } = renderTooltip({ active: false });+ expect(q(container, '.tooltip-static')).toBeInTheDocument();+ });++ it('hides close button when active is true', () => {+ const { container } = renderTooltip({ active: true });+ expect(q(container, '.close-tooltip')).toBeNull();+ });++ it('shows close button when active is false', () => {+ const { container } = renderTooltip({ active: false });+ expect(q(container, '.close-tooltip')).toBeInTheDocument();+ });++ it('calls onRemove when close button is clicked', () => {+ const onRemove = jest.fn();+ const { container } = renderTooltip({ active: false, onRemove });+ fireEvent.click(q(container, '.close-tooltip'));+ expect(onRemove).toHaveBeenCalledTimes(1);+ });++ it('calls onRemove on touch end of close button', () => {+ const onRemove = jest.fn();+ const { container } = renderTooltip({ active: false, onRemove });+ fireEvent.touchEnd(q(container, '.close-tooltip'));+ expect(onRemove).toHaveBeenCalledTimes(1);+ });++ it('returns null for invalid geographic coordinates (NaN)', () => {+ const { container } = renderTooltip({ geometry: makeLine([[NaN, NaN], [NaN, NaN]]) });+ expect(q(container, '.tooltip-measure')).toBeNull();+ });++ it('renders "0.0" tooltip when geometry is null', () => {+ // null geometry → getMeasurementValue returns '0.0' → no NaN → renders+ const { container } = renderTooltip({ geometry: null });+ expect(q(container, '.tooltip-measure')).toBeInTheDocument();+ });++ it('shows close button when active prop is omitted (undefined is falsy)', () => {+ // defaultProps declares active=true but React 18 function components may not apply it;+ // this test documents the actual runtime behaviour: omitting active shows the close button+ const { container } = render(+ <MeasureTooltip+ crs={GEO}+ unitOfMeasure="km"+ geometry={makeLine(longLineCoords)}+ onRemove={jest.fn()}+ proj={geographicProj}+ />,+ );+ expect(q(container, '.close-tooltip')).toBeInTheDocument();+ });+ });++ describe('distance formatting – km', () => {+ it('shows distance in km for a long line', () => {+ const { container } = renderTooltip({ unitOfMeasure: 'km', geometry: makeLine(longLineCoords) });+ expect(q(container, '.tooltip-measure span').innerHTML).toMatch(/km/);+ });++ it('shows distance in m for a line under 100 m', () => {+ const { container } = renderTooltip({+ unitOfMeasure: 'km',+ geometry: makeLine([[0, 0], [0.000009, 0]]),+ });+ const html = q(container, '.tooltip-measure span').innerHTML;+ expect(html).toMatch(/\d+ m$/);+ expect(html).not.toMatch(/km/);+ });+ });++ describe('distance formatting – mi', () => {+ it('shows distance in mi for a long line', () => {+ const { container } = renderTooltip({ unitOfMeasure: 'mi', geometry: makeLine(longLineCoords) });+ expect(q(container, '.tooltip-measure span').innerHTML).toMatch(/mi/);+ });++ it('shows distance in ft for a line under 0.25 miles', () => {+ const { container } = renderTooltip({+ unitOfMeasure: 'mi',+ geometry: makeLine([[0, 0], [0.001, 0]]),+ });+ expect(q(container, '.tooltip-measure span').innerHTML).toMatch(/ft/);+ });+ });++ describe('area formatting – km', () => {+ it('shows area in km² for a large polygon', () => {+ const { container } = renderTooltip({+ unitOfMeasure: 'km',+ geometry: makePoly([[0, 0], [10, 0], [0, 10], [0, 0]]),+ });+ expect(q(container, '.tooltip-measure span').innerHTML).toMatch(/km/);+ });++ it('shows area in m² for a tiny polygon', () => {+ const { container } = renderTooltip({+ unitOfMeasure: 'km',+ geometry: makePoly([[0, 0], [0.0001, 0], [0, 0.0001], [0, 0]]),+ });+ const html = q(container, '.tooltip-measure span').innerHTML;+ expect(html).toMatch(/m/);+ expect(html).not.toMatch(/km/);+ });+ });++ describe('area formatting – mi', () => {+ it('shows area in mi² for a large polygon', () => {+ const { container } = renderTooltip({+ unitOfMeasure: 'mi',+ geometry: makePoly([[0, 0], [10, 0], [0, 10], [0, 0]]),+ });+ expect(q(container, '.tooltip-measure span').innerHTML).toMatch(/mi/);+ });++ it('shows area in ft² for a tiny polygon', () => {+ const { container } = renderTooltip({+ unitOfMeasure: 'mi',+ geometry: makePoly([[0, 0], [0.001, 0], [0, 0.001], [0, 0]]),+ });+ expect(q(container, '.tooltip-measure span').innerHTML).toMatch(/ft/);+ });+ });++ describe('polar projection validity', () => {+ const arcticProj = {+ selected: {+ crs: 'EPSG:3413',+ maxExtent: [-9000000, -9000000, 9000000, 9000000],+ },+ };++ it('does not throw for polar coordinates within extent', () => {+ // Small in-bounds arctic coords — just asserts no crash+ expect(() => {+ renderTooltip({+ crs: 'EPSG:3413',+ geometry: makeLine([[0, 0], [100000, 100000]]),+ proj: arcticProj,+ });+ }).not.toThrow();+ });++ it('returns null when polar coordinates are outside extent', () => {+ const { container } = renderTooltip({+ crs: 'EPSG:3413',+ geometry: makeLine([[99000000, 99000000], [99000001, 99000000]]),+ proj: arcticProj,+ });+ expect(q(container, '.tooltip-measure')).toBeNull();+ });+ });});diff --git a/web/js/components/measure-tool/util.test.js b/web/js/components/measure-tool/util.test.jsindex 2fd34b337..1307bdaa6 100644--- a/web/js/components/measure-tool/util.test.js+++ b/web/js/components/measure-tool/util.test.js@@ -1,10 +1,16 @@-import { Polygon, LineString } from 'ol/geom';+import { Polygon, LineString, MultiLineString } from 'ol/geom';+import FileSaver from 'file-saver';import {getGeographicLibArea,getGeographicLibDistance,+ transformLineStringArc,+ transformPolygonArc,+ downloadGeoJSON,} from './util';import { registerProjections } from '../../fixtures';+jest.mock('file-saver', () => ({ saveAs: jest.fn() }));+beforeEach(registerProjections);/**@@ -119,3 +125,173 @@ test('always use the shortest distance between two points if within normal extenexpect(lineString1Distance).toBe(lineString2Distance);});++// ─── transformLineStringArc ────────────────────────────────────────────────++describe('transformLineStringArc', () => {+ const GEO = 'EPSG:4326';++ test('returns a MultiLineString', () => {+ const line = new LineString([[-74, 40], [0, 51]]);+ const result = transformLineStringArc(line, GEO);+ expect(result).toBeInstanceOf(MultiLineString);+ });++ test('transformed arc has more points than the original two-point line', () => {+ const line = new LineString([[-74, 40], [0, 51]]);+ const result = transformLineStringArc(line, GEO);+ // The flat coordinates array should have at least 3 pairs+ expect(result.getCoordinates()[0].length).toBeGreaterThan(2);+ });++ test('arc distance matches direct geodesic distance within 0.1%', () => {+ const coords = [[-74, 40], [0, 51]];+ const line = new LineString(coords);+ const directDistance = getGeographicLibDistance(line);+ const arcLine = transformLineStringArc(line, GEO);+ const arcPoints = arcLine.getCoordinates()[0];+ let arcDistance = 0;+ for (let i = 0; i < arcPoints.length - 1; i += 1) {+ const seg = new LineString([arcPoints[i], arcPoints[i + 1]]);+ arcDistance += getGeographicLibDistance(seg);+ }+ expect(Math.abs(arcDistance - directDistance) / directDistance).toBeLessThan(0.001);+ });++ test('handles line crossing anti-meridian (last two coords > 180 apart)', () => {+ // These two points are ~240 degrees apart in longitude → triggers checkForXFlip+ const line = new LineString([[-120, 0], [130, 0]]);+ const result = transformLineStringArc(line, GEO);+ expect(result).toBeInstanceOf(MultiLineString);+ });++ test('anti-meridian crossing line has same arc length as equivalent non-crossing line', () => {+ const crossingLine = new LineString([[-120, 0], [130, 0]]);+ const equivalentLine = new LineString([[-120, 0], [-230, 0]]); // shifted 360+ const crossingArc = transformLineStringArc(crossingLine, GEO);+ const equivalentArc = transformLineStringArc(equivalentLine, GEO);+ const sumSegments = (arc) => {+ const pts = arc.getCoordinates()[0];+ let dist = 0;+ for (let i = 0; i < pts.length - 1; i += 1) {+ dist += getGeographicLibDistance(new LineString([pts[i], pts[i + 1]]));+ }+ return dist;+ };+ expect(sumSegments(crossingArc).toFixed(0)).toBe(sumSegments(equivalentArc).toFixed(0));+ });+});++// ─── transformPolygonArc ───────────────────────────────────────────────────++describe('transformPolygonArc', () => {+ const GEO = 'EPSG:4326';++ test('returns a Polygon', () => {+ const poly = new Polygon([[[0, 0], [10, 0], [0, 10], [0, 0]]]);+ const result = transformPolygonArc(poly, GEO);+ expect(result).toBeInstanceOf(Polygon);+ });++ test('transformed polygon ring has more points than the original', () => {+ const poly = new Polygon([[[0, 0], [10, 0], [0, 10], [0, 0]]]);+ const original = poly.getCoordinates()[0].length;+ const result = transformPolygonArc(poly, GEO);+ expect(result.getCoordinates()[0].length).toBeGreaterThan(original);+ });++ test('arc polygon area is within 1% of the direct-calculation area', () => {+ const coords = [[[0, 0], [5, 0], [0, 5], [0, 0]]];+ const poly = new Polygon(coords);+ const directArea = getGeographicLibArea(poly);+ const arcPoly = transformPolygonArc(poly, GEO);+ const arcArea = getGeographicLibArea(arcPoly);+ expect(Math.abs(arcArea - directArea) / directArea).toBeLessThan(0.01);+ });+});++// ─── downloadGeoJSON ──────────────────────────────────────────────────────++function readBlob(blob) {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result);+ reader.onerror = reject;+ reader.readAsText(blob);+ });+}++describe('downloadGeoJSON', () => {+ const GEO = 'EPSG:4326';++ function makeFakeMeasurement(type, coords, label = '100 km') {+ const geom = type === 'Polygon'+ ? new Polygon([coords])+ : new LineString(coords);+ return {+ feature: { getGeometry: () => geom },+ overlay: { element: { innerText: label } },+ };+ }++ beforeEach(() => jest.clearAllMocks());++ test('calls FileSaver.saveAs with correct filename', () => {+ const measurements = {+ m1: makeFakeMeasurement('LineString', [[-74, 40], [0, 51]]),+ };+ downloadGeoJSON(measurements, GEO);+ expect(FileSaver.saveAs).toHaveBeenCalledTimes(1);+ const [, fileName] = FileSaver.saveAs.mock.calls[0];+ expect(fileName).toBe('worldviewMeasurements.json');+ });++ test('produces a valid GeoJSON FeatureCollection blob', async () => {+ const measurements = {+ m1: makeFakeMeasurement('LineString', [[-74, 40], [0, 51]]),+ };+ downloadGeoJSON(measurements, GEO);+ const [blob] = FileSaver.saveAs.mock.calls[0];+ expect(blob).toBeInstanceOf(Blob);+ const text = await readBlob(blob);+ const json = JSON.parse(text);+ expect(json.type).toBe('FeatureCollection');+ expect(json.features).toHaveLength(1);+ expect(json.features[0].properties.size).toBe(100);+ expect(json.features[0].properties.units).toBe('km');+ });++ test('handles Polygon measurements', async () => {+ const measurements = {+ m1: makeFakeMeasurement('Polygon', [[0, 0], [5, 0], [0, 5], [0, 0]]),+ };+ downloadGeoJSON(measurements, GEO);+ const [blob] = FileSaver.saveAs.mock.calls[0];+ const text = await readBlob(blob);+ const json = JSON.parse(text);+ expect(json.features[0].geometry.type).toBe('Polygon');+ });++ test('handles multiple measurements', async () => {+ const measurements = {+ m1: makeFakeMeasurement('LineString', [[-74, 40], [0, 51]]),+ m2: makeFakeMeasurement('Polygon', [[0, 0], [5, 0], [0, 5], [0, 0]]),+ };+ downloadGeoJSON(measurements, GEO);+ const [blob] = FileSaver.saveAs.mock.calls[0];+ const text = await readBlob(blob);+ const json = JSON.parse(text);+ expect(json.features).toHaveLength(2);+ });++ test('parses size with comma-formatted numbers from overlay text', async () => {+ const measurements = {+ m1: makeFakeMeasurement('LineString', [[-74, 40], [0, 51]], '1,234 km'),+ };+ downloadGeoJSON(measurements, GEO);+ const [blob] = FileSaver.saveAs.mock.calls[0];+ const text = await readBlob(blob);+ const json = JSON.parse(text);+ expect(json.features[0].properties.size).toBe(1234);+ });+});diff --git a/web/js/components/notifications/notification-block.test.js b/web/js/components/notifications/notification-block.test.jsindex 5d0118bfe..77b1495cd 100644--- a/web/js/components/notifications/notification-block.test.js+++ b/web/js/components/notifications/notification-block.test.js@@ -1,3 +1,140 @@-test('notification-block component test', () => {+/* eslint-disable react/prop-types */+import '@testing-library/jest-dom';+import { render, screen } from '@testing-library/react';+import NotificationBlock from './notification-block';+jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon }) => <svg data-testid={`icon-${Array.isArray(icon) ? icon[1] : icon}`} />,+}));++jest.mock('../../util/util', () => ({+ giveMonth: jest.fn((d) => {+ const months = ['January', 'February', 'March', 'April', 'May', 'June',+ 'July', 'August', 'September', 'October', 'November', 'December'];+ return months[d.getMonth()];+ }),+}));++const makeNotification = (message, createdAt = '2024-03-15T12:00:00Z') => ({+ message,+ created_at: createdAt,+});++describe('NotificationBlock', () => {+ describe('list rendering', () => {+ it('renders a <ul> with one <li> per notification', () => {+ const arr = [makeNotification('First'), makeNotification('Second')];+ const { container } = render(+ <NotificationBlock arr={arr} type="message" numberNotSeen={0} />,+ );+ expect(container.querySelectorAll('li')).toHaveLength(2);+ });++ it('renders nothing inside the list when arr is empty', () => {+ const { container } = render(+ <NotificationBlock arr={[]} type="message" numberNotSeen={0} />,+ );+ expect(container.querySelectorAll('li')).toHaveLength(0);+ });+ });++ describe('date formatting', () => {+ it('displays the formatted date from created_at', () => {+ const arr = [makeNotification('Hello', '2024-03-15T12:00:00Z')];+ render(<NotificationBlock arr={arr} type="message" numberNotSeen={0} />);+ // getDate() on 2024-03-15 UTC may resolve to 14 or 15 depending on local TZ in JSDOM;+ // just assert "March" and "2024" appear+ expect(screen.getByText(/March/)).toBeInTheDocument();+ expect(screen.getByText(/2024/)).toBeInTheDocument();+ });++ it('shows the day and year alongside the month', () => {+ const arr = [makeNotification('Test', '2023-07-04T00:00:00Z')];+ render(<NotificationBlock arr={arr} type="message" numberNotSeen={0} />);+ expect(screen.getByText(/July/)).toBeInTheDocument();+ expect(screen.getByText(/2023/)).toBeInTheDocument();+ });+ });++ describe('active class (numberNotSeen)', () => {+ it('applies the type-specific class to items within numberNotSeen count', () => {+ const arr = [makeNotification('A'), makeNotification('B'), makeNotification('C')];+ const { container } = render(+ <NotificationBlock arr={arr} type="alert" numberNotSeen={2} />,+ );+ const items = container.querySelectorAll('li');+ expect(items[0]).toHaveClass('alert-notification-item');+ expect(items[1]).toHaveClass('alert-notification-item');+ expect(items[2]).not.toHaveClass('alert-notification-item');+ });++ it('applies no active class when numberNotSeen is 0', () => {+ const arr = [makeNotification('A'), makeNotification('B')];+ const { container } = render(+ <NotificationBlock arr={arr} type="message" numberNotSeen={0} />,+ );+ container.querySelectorAll('li').forEach((li) => {+ expect(li).not.toHaveClass('message-notification-item');+ });+ });++ it('applies active class to all items when numberNotSeen exceeds arr length', () => {+ const arr = [makeNotification('A'), makeNotification('B')];+ const { container } = render(+ <NotificationBlock arr={arr} type="outage" numberNotSeen={10} />,+ );+ container.querySelectorAll('li').forEach((li) => {+ expect(li).toHaveClass('outage-notification-item');+ });+ });++ it('uses the correct type prefix in the class name', () => {+ const arr = [makeNotification('X')];+ const { container } = render(+ <NotificationBlock arr={arr} type="outage" numberNotSeen={1} />,+ );+ expect(container.querySelector('li')).toHaveClass('outage-notification-item');+ });+ });++ describe('icons', () => {+ it('renders the bolt icon for type "alert"', () => {+ const arr = [makeNotification('A')];+ render(<NotificationBlock arr={arr} type="alert" numberNotSeen={0} />);+ expect(screen.getByTestId('icon-bolt')).toBeInTheDocument();+ });++ it('renders the gift icon for type "message"', () => {+ const arr = [makeNotification('A')];+ render(<NotificationBlock arr={arr} type="message" numberNotSeen={0} />);+ expect(screen.getByTestId('icon-gift')).toBeInTheDocument();+ });++ it('renders the exclamation-circle icon for type "outage"', () => {+ const arr = [makeNotification('A')];+ render(<NotificationBlock arr={arr} type="outage" numberNotSeen={0} />);+ expect(screen.getByTestId('icon-exclamation-circle')).toBeInTheDocument();+ });+ });++ describe('message content', () => {+ it('renders the notification message as HTML via dangerouslySetInnerHTML', () => {+ const arr = [makeNotification('<strong>Important</strong> update')];+ const { container } = render(+ <NotificationBlock arr={arr} type="message" numberNotSeen={0} />,+ );+ const p = container.querySelector('p');+ expect(p.innerHTML).toBe('<strong>Important</strong> update');+ });++ it('renders multiple messages independently', () => {+ const arr = [makeNotification('First message'), makeNotification('Second message')];+ const { container } = render(+ <NotificationBlock arr={arr} type="message" numberNotSeen={0} />,+ );+ const paragraphs = container.querySelectorAll('p');+ expect(paragraphs[0].innerHTML).toBe('First message');+ expect(paragraphs[1].innerHTML).toBe('Second message');+ });+ });});diff --git a/web/js/components/projection/util.test.js b/web/js/components/projection/util.test.jsindex 88fe850d4..1cedb477c 100644--- a/web/js/components/projection/util.test.js+++ b/web/js/components/projection/util.test.js@@ -1,3 +1,107 @@-test('util component test', () => {+import parse from './util';+const config = {+ projections: {+ geographic: { id: 'geographic' },+ arctic: { id: 'arctic' },+ },+};++describe('parse (projection util)', () => {+ describe('permalink v1.0–1.1 switch migration', () => {+ it('copies switch value to p and removes switch', () => {+ const state = { switch: 'geographic' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBe('geographic');+ expect(result.switch).toBeUndefined();+ });++ it('does not modify state when switch is absent', () => {+ const state = { p: 'arctic' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBe('arctic');+ expect(result.switch).toBeUndefined();+ });++ it('migrates switch even when p is also present', () => {+ const state = { switch: 'arctic', p: 'geographic' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBe('arctic');+ expect(result.switch).toBeUndefined();+ });+ });++ describe('projection validation', () => {+ it('keeps p when projId is valid', () => {+ const state = { p: 'geographic' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBe('geographic');+ expect(errors).toHaveLength(0);+ });++ it('removes p and pushes an error when projId is not in config', () => {+ const state = { p: 'unknown' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBeUndefined();+ expect(errors).toHaveLength(1);+ expect(errors[0].message).toBe('Unsupported projection: unknown');+ });++ it('does not push an error when p is absent', () => {+ const state = {};+ const errors = [];+ const result = parse(state, errors, config);+ expect(errors).toHaveLength(0);+ expect(result.p).toBeUndefined();+ });+ });++ describe('state immutability', () => {+ it('does not mutate the original state object', () => {+ const state = { p: 'unknown', other: 'value' };+ const original = { ...state };+ const errors = [];+ parse(state, errors, config);+ expect(state).toEqual(original);+ });++ it('preserves unrelated state keys', () => {+ const state = { p: 'geographic', t: '2024-01-01', z: 4 };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.t).toBe('2024-01-01');+ expect(result.z).toBe(4);+ });++ it('preserves unrelated keys even when projection is invalid', () => {+ const state = { p: 'bad', t: '2024-01-01' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.t).toBe('2024-01-01');+ });+ });++ describe('combined migration + validation', () => {+ it('migrates switch then validates the resulting p', () => {+ const state = { switch: 'unknown' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBeUndefined();+ expect(result.switch).toBeUndefined();+ expect(errors[0].message).toBe('Unsupported projection: unknown');+ });++ it('migrates switch and keeps valid p', () => {+ const state = { switch: 'arctic' };+ const errors = [];+ const result = parse(state, errors, config);+ expect(result.p).toBe('arctic');+ expect(errors).toHaveLength(0);+ });+ });});diff --git a/web/js/components/range-selection/dragger-range.test.js b/web/js/components/range-selection/dragger-range.test.jsindex 4304ebe14..52b5e01b3 100644--- a/web/js/components/range-selection/dragger-range.test.js+++ b/web/js/components/range-selection/dragger-range.test.js@@ -1,3 +1,250 @@-test('dragger-range component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import '@testing-library/jest-dom';+import { render, act } from '@testing-library/react';+import TimelineDraggerRange from './dragger-range';+jest.mock('react-draggable', () => function MockDraggable({+ children, onDrag, onStop,+}) {+ return (+ <g+ data-testid="draggable"+ onMouseMove={(e) => onDrag && onDrag(e, { deltaX: 10, x: 100 })}+ onMouseUp={() => onStop && onStop()}+ >+ {children}+ </g>+ );+});++const BASE_DATE = new Date('2023-06-01T00:00:00Z');+const LIMIT_DATE = '2023-12-31T00:00:00Z';++const defaultProps = {+ startLocation: 100,+ endLocation: 300,+ startLocationDate: new Date('2023-01-01T00:00:00Z'),+ endLocationDate: BASE_DATE,+ timelineStartDateLimit: '2020-01-01T00:00:00Z',+ timelineEndDateLimit: LIMIT_DATE,+ timeScale: 'day',+ deltaStart: 0,+ max: { width: 800, start: false, end: false, startOffset: 0 },+ height: 64,+ width: 5,+ color: '#45bdff',+ opacity: 0.3,+ draggerID: 'range-dragger',+ onDrag: jest.fn(),+ onStop: jest.fn(),+};++function renderRange(overrides = {}) {+ const props = { ...defaultProps, ...overrides };+ return render(+ <svg>+ <TimelineDraggerRange {...props} />+ </svg>,+ );+}++describe('TimelineDraggerRange', () => {+ beforeEach(() => jest.clearAllMocks());++ describe('initial render', () => {+ it('renders a rect element', () => {+ const { container } = renderRange();+ expect(container.querySelector('rect')).toBeInTheDocument();+ });++ it('applies the draggerID to the rect', () => {+ const { container } = renderRange({ draggerID: 'my-range' });+ expect(container.querySelector('#my-range')).toBeInTheDocument();+ });++ it('applies color and opacity as fill style', () => {+ const { container } = renderRange({ color: '#ff0000', opacity: 0.5 });+ const rect = container.querySelector('rect');+ expect(rect.getAttribute('fill')).toBe('#ff0000');+ expect(rect.style.fillOpacity).toBe('0.5');+ });++ it('applies height to the rect', () => {+ const { container } = renderRange({ height: 48 });+ expect(container.querySelector('rect').getAttribute('height')).toBe('48');+ });+ });++ describe('checkWidth (width calculation)', () => {+ it('sets rect width to endLocation minus startLocation', () => {+ const { container } = renderRange({ startLocation: 100, endLocation: 400 });+ expect(container.querySelector('rect').getAttribute('width')).toBe('300');+ });++ it('clamps startLocation to 0 when it is negative', () => {+ // start=-50, end=200 → clamped start=0, width=200+ const { container } = renderRange({ startLocation: -50, endLocation: 200 });+ expect(container.querySelector('rect').getAttribute('width')).toBe('200');+ });++ it('clamps endLocation to maxWidth when it exceeds max', () => {+ // start=600, end=900 → clamped end=800, width=200+ const { container } = renderRange({ startLocation: 600, endLocation: 900 });+ expect(container.querySelector('rect').getAttribute('width')).toBe('200');+ });++ it('sets width to 0 when end is less than start', () => {+ const { container } = renderRange({ startLocation: 500, endLocation: 200 });+ expect(container.querySelector('rect').getAttribute('width')).toBe('0');+ });+ });++ describe('handleStartPositionRestriction', () => {+ it('returns startLocation - deltaStart when startLocation > 0', () => {+ // startLocation=100, deltaStart=20 → x = 100-20 = 80+ const { container } = renderRange({ startLocation: 100, deltaStart: 20 });+ const rect = container.querySelector('rect');+ expect(Number(rect.getAttribute('x'))).toBe(80);+ });++ it('returns -deltaStart when startLocation <= 0', () => {+ // startLocation=0, deltaStart=30 → x = -30+ const { container } = renderRange({ startLocation: 0, deltaStart: 30 });+ const rect = container.querySelector('rect');+ expect(Number(rect.getAttribute('x'))).toBe(-30);+ });+ });++ describe('componentDidUpdate', () => {+ it('recalculates width when startLocation prop changes', () => {+ const { container, rerender } = renderRange({ startLocation: 100, endLocation: 400 });+ expect(container.querySelector('rect').getAttribute('width')).toBe('300');+ act(() => {+ rerender(+ <svg>+ <TimelineDraggerRange {...defaultProps} startLocation={200} endLocation={400} />+ </svg>,+ );+ });+ expect(container.querySelector('rect').getAttribute('width')).toBe('200');+ });++ it('recalculates width when endLocation prop changes', () => {+ const { container, rerender } = renderRange({ startLocation: 100, endLocation: 300 });+ act(() => {+ rerender(+ <svg>+ <TimelineDraggerRange {...defaultProps} startLocation={100} endLocation={500} />+ </svg>,+ );+ });+ expect(container.querySelector('rect').getAttribute('width')).toBe('400');+ });+ });++ describe('handleDrag – day scale (scaleMs set)', () => {+ it('calls onDrag when dragged forward within bounds', () => {+ const onDrag = jest.fn();+ const { container } = renderRange({ onDrag });+ act(() => {+ container.querySelector('[data-testid="draggable"]').dispatchEvent(+ new MouseEvent('mousemove', { bubbles: true }),+ );+ });+ expect(onDrag).toHaveBeenCalled();+ });++ it('passes deltaX=0 when endLocationDate has reached the timeline end limit', () => {+ const onDrag = jest.fn();+ // endLocationDate === timelineEndDateLimit → dragging right stops+ renderRange({+ onDrag,+ endLocationDate: new Date(LIMIT_DATE),+ timelineEndDateLimit: LIMIT_DATE,+ });+ // The drag mock sends deltaX=10 (rightward); the component should zero it+ const { container } = renderRange({+ onDrag,+ endLocationDate: new Date(LIMIT_DATE),+ timelineEndDateLimit: LIMIT_DATE,+ });+ act(() => {+ container.querySelector('[data-testid="draggable"]').dispatchEvent(+ new MouseEvent('mousemove', { bubbles: true }),+ );+ });+ // deltaX was throttled to 0 because we are at the end limit+ const [calledDeltaX] = onDrag.mock.calls[0];+ expect(calledDeltaX).toBe(0);+ });+ });++ describe('handleDrag – month/year scale (scaleMs null)', () => {+ it('handles month timeScale without error', () => {+ const onDrag = jest.fn();+ const { container } = renderRange({ onDrag, timeScale: 'month' });+ expect(() => {+ act(() => {+ container.querySelector('[data-testid="draggable"]').dispatchEvent(+ new MouseEvent('mousemove', { bubbles: true }),+ );+ });+ }).not.toThrow();+ });++ it('handles year timeScale without error', () => {+ const onDrag = jest.fn();+ const { container } = renderRange({ onDrag, timeScale: 'year' });+ expect(() => {+ act(() => {+ container.querySelector('[data-testid="draggable"]').dispatchEvent(+ new MouseEvent('mousemove', { bubbles: true }),+ );+ });+ }).not.toThrow();+ });+ });++ describe('handleDraggerClick', () => {+ it('updates previousStartLocation when startLocation has changed', () => {+ const { container, rerender } = renderRange({ startLocation: 100 });+ // Move the start location so startLocation in state != previousStartLocation+ act(() => {+ rerender(+ <svg>+ <TimelineDraggerRange {...defaultProps} startLocation={200} endLocation={400} />+ </svg>,+ );+ });+ // Click the rect — should not throw+ expect(() => {+ act(() => {+ container.querySelector('rect').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ }).not.toThrow();+ });++ it('does not throw when startLocation has not changed (click without drag)', () => {+ const { container } = renderRange({ startLocation: 100 });+ expect(() => {+ act(() => {+ container.querySelector('rect').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ }).not.toThrow();+ });+ });++ describe('onStop', () => {+ it('calls onStop when drag ends', () => {+ const onStop = jest.fn();+ const { container } = renderRange({ onStop });+ act(() => {+ container.querySelector('[data-testid="draggable"]').dispatchEvent(+ new MouseEvent('mouseup', { bubbles: true }),+ );+ });+ expect(onStop).toHaveBeenCalled();+ });+ });});diff --git a/web/js/components/range-selection/dragger.test.js b/web/js/components/range-selection/dragger.test.jsindex 35544394c..fd82bf67b 100644--- a/web/js/components/range-selection/dragger.test.js+++ b/web/js/components/range-selection/dragger.test.js@@ -1,3 +1,169 @@-test('dragger component test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import '@testing-library/jest-dom';+import { render, act } from '@testing-library/react';+import TimelineDragger from './dragger';+// Draggable wraps children; simulate it as a passthrough so we can inspect the SVG group+jest.mock('react-draggable', () => function MockDraggable({ children, onDrag, onStop }) {+ return (+ <g+ data-testid="draggable"+ onMouseMove={(e) => onDrag && onDrag(e, { deltaX: 5, x: 10 })}+ onMouseUp={() => onStop && onStop()}+ >+ {children}+ </g>+ );+});++const defaultProps = {+ id: 'start',+ position: 50,+ max: 800,+ onDrag: jest.fn(),+ onStop: jest.fn(),+ draggerID: 'dragger-1',+ backgroundColor: '#fff',+};++function renderDragger(overrides = {}) {+ const props = { ...defaultProps, ...overrides };+ return render(+ <svg>+ <TimelineDragger {...props} />+ </svg>,+ );+}++describe('TimelineDragger', () => {+ beforeEach(() => jest.clearAllMocks());++ describe('rendering – default dragger (no path)', () => {+ it('renders a rect and polygon when path is not provided', () => {+ const { container } = renderDragger();+ expect(container.querySelector('rect')).toBeInTheDocument();+ expect(container.querySelector('polygon')).toBeInTheDocument();+ });++ it('applies the draggerID to the polygon', () => {+ const { container } = renderDragger({ draggerID: 'my-dragger' });+ expect(container.querySelector('#my-dragger')).toBeInTheDocument();+ });++ it('does not render a <path> element when path prop is null', () => {+ const { container } = renderDragger({ path: null });+ expect(container.querySelector('path')).toBeNull();+ });+ });++ describe('rendering – custom dragger (with path)', () => {+ it('renders a <path> element when path prop is provided', () => {+ const { container } = renderDragger({ path: 'M0,0 L10,10' });+ expect(container.querySelector('path')).toBeInTheDocument();+ });++ it('does not render a polygon when path prop is provided', () => {+ const { container } = renderDragger({ path: 'M0,0 L10,10' });+ expect(container.querySelector('polygon')).toBeNull();+ });+ });++ describe('visibility', () => {+ it('is visible when position is within 0 and max', () => {+ const { container } = renderDragger({ position: 100, max: 800 });+ const polygon = container.querySelector('polygon');+ expect(polygon.style.visibility).toBe('visible');+ });++ it('is hidden when position is less than 0', () => {+ const { container } = renderDragger({ position: -10, max: 800 });+ const polygon = container.querySelector('polygon');+ expect(polygon.style.visibility).toBe('hidden');+ });++ it('is hidden when position exceeds max', () => {+ const { container } = renderDragger({ position: 900, max: 800 });+ const polygon = container.querySelector('polygon');+ expect(polygon.style.visibility).toBe('hidden');+ });++ it('is visible when position equals 0', () => {+ const { container } = renderDragger({ position: 0, max: 800 });+ const polygon = container.querySelector('polygon');+ expect(polygon.style.visibility).toBe('visible');+ });+ });++ describe('text rendering', () => {+ it('renders a <text> element when text prop is provided', () => {+ const { container } = renderDragger({ text: 'A' });+ expect(container.querySelector('text')).toBeInTheDocument();+ });++ it('does not render a <text> element when text prop is absent', () => {+ const { container } = renderDragger();+ expect(container.querySelector('text')).toBeNull();+ });++ it('renders text content correctly', () => {+ const { container } = renderDragger({ text: 'B' });+ expect(container.querySelector('text').textContent).toBe('B');+ });+ });++ describe('componentDidUpdate', () => {+ it('updates internal position state when position prop changes', () => {+ const { container, rerender } = renderDragger({ position: 100 });+ rerender(+ <svg>+ <TimelineDragger {...defaultProps} position={200} />+ </svg>,+ );+ // The Draggable mock receives the updated position — no error thrown means state updated+ expect(container.querySelector('[data-testid="draggable"]')).toBeInTheDocument();+ });++ it('updates internal max state when max prop changes', () => {+ const { container, rerender } = renderDragger({ max: 800 });+ rerender(+ <svg>+ <TimelineDragger {...defaultProps} max={600} />+ </svg>,+ );+ expect(container.querySelector('[data-testid="draggable"]')).toBeInTheDocument();+ });+ });++ describe('handleDrag', () => {+ it('calls onDrag with deltaX, id, and x on drag event', () => {+ const onDrag = jest.fn();+ const { container } = renderDragger({ onDrag, id: 'start' });+ const draggable = container.querySelector('[data-testid="draggable"]');+ act(() => {+ draggable.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, movementX: 3 }));+ });+ expect(onDrag).toHaveBeenCalledWith(5, 'start', 10);+ });+ });++ describe('default props', () => {+ it('applies default color, height, width, and position without explicit props', () => {+ const { container } = render(+ <svg>+ <TimelineDragger+ id="test"+ max={800}+ onDrag={jest.fn()}+ onStop={jest.fn()}+ draggerID="d1"+ backgroundColor="#ccc"+ />+ </svg>,+ );+ // rect should have default width=5+ const rect = container.querySelector('rect');+ expect(rect.getAttribute('width')).toBe('5');+ });+ });});diff --git a/web/js/components/range-selection/range-selection.test.js b/web/js/components/range-selection/range-selection.test.jsindex 664839b16..090e4c73e 100644--- a/web/js/components/range-selection/range-selection.test.js+++ b/web/js/components/range-selection/range-selection.test.js@@ -1,3 +1,349 @@-test('range-selection component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import '@testing-library/jest-dom';+import { render, act } from '@testing-library/react';+import TimelineRangeSelector from './range-selection';+jest.mock('react-draggable', () => function MockDraggable({ children }) {+ return <g data-testid="draggable">{children}</g>;+});++// Capture the onDrag/onStop callbacks passed to child mocks so tests can invoke them directly+let capturedDraggerOnDrag = null;+let capturedRangeOnDrag = null;+let capturedOnStop = null;++jest.mock('./dragger', () => function MockDragger({ onDrag, onStop, id }) {+ capturedDraggerOnDrag = onDrag;+ capturedOnStop = onStop;+ return <g data-testid={`dragger-${id}`} />;+});++jest.mock('./dragger-range', () => function MockDraggerRange({ onDrag }) {+ capturedRangeOnDrag = onDrag;+ return <g data-testid="dragger-range" />;+});++const defaultProps = {+ axisWidth: 1000,+ startLocation: 100,+ endLocation: 400,+ startLocationDate: new Date('2023-01-01T00:00:00Z'),+ endLocationDate: new Date('2023-06-01T00:00:00Z'),+ timelineStartDateLimit: '2020-01-01T00:00:00Z',+ timelineEndDateLimit: '2025-01-01T00:00:00Z',+ timeScale: 'day',+ frontDate: '2023-01-01',+ position: 0,+ transformX: 0,+ pinWidth: 5,+ max: { width: 800, start: false, end: false, startOffset: 0 },+ updateAnimationDateAndLocation: jest.fn(),+};++function renderSelector(overrides = {}) {+ const props = { ...defaultProps, ...overrides };+ return render(+ <svg>+ <TimelineRangeSelector {...props} />+ </svg>,+ );+}++describe('TimelineRangeSelector', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ capturedDraggerOnDrag = null;+ capturedRangeOnDrag = null;+ capturedOnStop = null;+ });++ describe('rendering', () => {+ it('renders the range selector svg element', () => {+ const { container } = renderSelector();+ // The component renders its own svg inside our wrapper svg+ expect(+ container.querySelector('#wv-timeline-range-selector'),+ ).toBeInTheDocument();+ });++ it('sets svg width from axisWidth prop', () => {+ const { container } = renderSelector({ axisWidth: 1200 });+ const inner = container.querySelector('#wv-timeline-range-selector');+ expect(inner.getAttribute('width')).toBe('1200');+ });++ it('renders two Dragger and one DraggerRange child components', () => {+ const { getByTestId } = renderSelector();+ expect(getByTestId('dragger-start')).toBeInTheDocument();+ expect(getByTestId('dragger-end')).toBeInTheDocument();+ expect(getByTestId('dragger-range')).toBeInTheDocument();+ });+ });++ describe('componentDidMount / updateLocation', () => {+ it('syncs startLocation and endLocation into state on mount without error', () => {+ // animationDraggerPositionUpdate is only called when delta != 0;+ // on mount state == props so delta == 0, no callback triggered+ const update = jest.fn();+ expect(() => renderSelector({ updateAnimationDateAndLocation: update }))+ .not.toThrow();+ });+ });++ describe('componentDidUpdate – updateLocation', () => {+ it('syncs new startLocation into state when prop changes', () => {+ // After prop change, drag to confirm state was updated via the new location+ const update = jest.fn();+ const { rerender } = renderSelector({ updateAnimationDateAndLocation: update });+ act(() => {+ rerender(+ <svg>+ <TimelineRangeSelector+ {...defaultProps}+ startLocation={200}+ updateAnimationDateAndLocation={update}+ />+ </svg>,+ );+ });+ update.mockClear();+ // Now drag the start dragger — it should read the updated startLocation (200)+ act(() => { capturedDraggerOnDrag(10, 'start'); }); // 200+10=210 < 400+ expect(update).toHaveBeenCalled();+ });++ it('syncs new endLocation into state when prop changes', () => {+ const update = jest.fn();+ const { rerender } = renderSelector({ updateAnimationDateAndLocation: update });+ act(() => {+ rerender(+ <svg>+ <TimelineRangeSelector+ {...defaultProps}+ endLocation={600}+ updateAnimationDateAndLocation={update}+ />+ </svg>,+ );+ });+ update.mockClear();+ // Drag end dragger — should read updated endLocation (600)+ act(() => { capturedDraggerOnDrag(10, 'end'); }); // 600+10=610 < 800+ expect(update).toHaveBeenCalled();+ });+ });++ describe('onItemDrag – start dragger', () => {+ it('updates state when start dragger moves within bounds', () => {+ const update = jest.fn();+ renderSelector({ updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(10, 'start'); }); // 100→110 < endLocation 400+ expect(update).toHaveBeenCalled();+ });++ it('ignores start drag that would go below 0', () => {+ const update = jest.fn();+ renderSelector({ startLocation: 5, updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(-20, 'start'); }); // 5-20 = -15 < 0+ expect(update).not.toHaveBeenCalled();+ });++ it('ignores start drag that would exceed endLocation', () => {+ const update = jest.fn();+ renderSelector({+ startLocation: 390,+ endLocation: 400,+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(50, 'start'); }); // 390+50=440 > 400+ expect(update).not.toHaveBeenCalled();+ });++ it('pushes end dragger forward when start + pinWidth >= end', () => {+ const update = jest.fn();+ renderSelector({+ startLocation: 395,+ endLocation: 400,+ pinWidth: 5,+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ // 396+5=401 >= 400, and 401 < 800 → end is pushed to 401, allowed+ act(() => { capturedDraggerOnDrag(1, 'start'); });+ expect(update).toHaveBeenCalled();+ });++ it('ignores start drag when start + pinWidth would exceed max width', () => {+ const update = jest.fn();+ renderSelector({+ startLocation: 795,+ endLocation: 800,+ pinWidth: 5,+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(1, 'start'); }); // 796+5=801 >= 800+ expect(update).not.toHaveBeenCalled();+ });+ });++ describe('onItemDrag – end dragger', () => {+ it('updates state when end dragger moves within bounds', () => {+ const update = jest.fn();+ renderSelector({ updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(20, 'end'); }); // 400+20=420 < 800+ expect(update).toHaveBeenCalled();+ });++ it('ignores end drag that would exceed max width', () => {+ const update = jest.fn();+ renderSelector({ endLocation: 790, updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(20, 'end'); }); // 790+20=810 > 800+ expect(update).not.toHaveBeenCalled();+ });++ it('ignores end drag when startX > endX', () => {+ const update = jest.fn();+ renderSelector({+ startLocation: 400,+ endLocation: 410,+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(-50, 'end'); }); // end=360, start(400) > 360+ expect(update).not.toHaveBeenCalled();+ });++ it('pulls start dragger back when start + 2*pinWidth >= end', () => {+ const update = jest.fn();+ renderSelector({+ startLocation: 395,+ endLocation: 406,+ pinWidth: 5,+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(-1, 'end'); }); // end=405, 395+10=405 → start=400+ expect(update).toHaveBeenCalled();+ });+ });++ describe('onRangeDrag', () => {+ it('calls updateAnimationDateAndLocation when range is dragged', () => {+ const update = jest.fn();+ renderSelector({ updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedRangeOnDrag(10, 50); }); // shifts both start and end by 10+ expect(update).toHaveBeenCalledWith(+ expect.any(Date),+ expect.any(Date),+ expect.any(Number),+ expect.any(Number),+ true, // isDragging+ );+ });++ it('shifts both start and end locations by the delta', () => {+ const update = jest.fn();+ renderSelector({+ startLocation: 100,+ endLocation: 400,+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedRangeOnDrag(50, 0); });+ const [, , newStart, newEnd] = update.mock.calls[0];+ expect(newStart).toBe(150);+ expect(newEnd).toBe(450);+ });+ });++ describe('onDragStop', () => {+ it('calls updateAnimationDateAndLocation with isDragging=false on stop', () => {+ const update = jest.fn();+ renderSelector({ updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedOnStop(); });+ const args = update.mock.calls[0];+ expect(args[4]).toBe(false); // isDragging+ });+ });++ describe('animationDraggerPositionUpdate – date limit clamping', () => {+ it('clamps end date to timelineStartDateLimit when end is before the start limit', () => {+ const update = jest.fn();+ renderSelector({+ endLocationDate: new Date('2019-01-01T00:00:00Z'),+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedOnStop(); });+ const [, endDate] = update.mock.calls[0];+ expect(new Date(endDate).toISOString()).toBe('2020-01-01T00:00:00.000Z');+ });++ it('clamps start date to timelineStartDateLimit when start is before start limit', () => {+ const update = jest.fn();+ renderSelector({+ startLocationDate: new Date('2019-01-01T00:00:00Z'),+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedOnStop(); });+ const [startDate] = update.mock.calls[0];+ expect(new Date(startDate).toISOString()).toBe('2020-01-01T00:00:00.000Z');+ });++ it('clamps end date to timelineEndDateLimit when end is after end limit', () => {+ const update = jest.fn();+ renderSelector({+ endLocationDate: new Date('2030-01-01T00:00:00Z'),+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedOnStop(); });+ const [, endDate] = update.mock.calls[0];+ expect(new Date(endDate).toISOString()).toBe('2025-01-01T00:00:00.000Z');+ });++ it('clamps start date to timelineEndDateLimit when start is after end limit', () => {+ const update = jest.fn();+ renderSelector({+ startLocationDate: new Date('2030-01-01T00:00:00Z'),+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedOnStop(); });+ const [startDate] = update.mock.calls[0];+ expect(new Date(startDate).toISOString()).toBe('2025-01-01T00:00:00.000Z');+ });+ });++ describe('getAnimationLocateDateUpdate – month/year timeScale', () => {+ it('computes a new date for month timeScale (scaleMs is null)', () => {+ const update = jest.fn();+ renderSelector({ timeScale: 'month', updateAnimationDateAndLocation: update });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(12, 'start'); });+ expect(update).toHaveBeenCalled();+ });++ it('computes a new date for year timeScale (scaleMs is null)', () => {+ const update = jest.fn();+ renderSelector({+ timeScale: 'year',+ frontDate: '2023-01-01',+ updateAnimationDateAndLocation: update,+ });+ update.mockClear();+ act(() => { capturedDraggerOnDrag(18, 'start'); });+ expect(update).toHaveBeenCalled();+ });+ });});diff --git a/web/js/components/sidebar/nav/nav-case.test.js b/web/js/components/sidebar/nav/nav-case.test.jsindex fec260167..2f863265c 100644--- a/web/js/components/sidebar/nav/nav-case.test.js+++ b/web/js/components/sidebar/nav/nav-case.test.js@@ -1,3 +1,196 @@-test('nav-case component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import '@testing-library/jest-dom';+import { render, screen, fireEvent } from '@testing-library/react';+import NavCase from './nav-case';+jest.mock('./nav-item', () => function MockNavItem({+ id, className, label, disabled, isDisabled, shouldHideInMobile, isMobile, onTabClick, text,+}) {+ return (+ <button+ type="button"+ data-testid={`nav-item-${id}`}+ data-classname={className}+ data-label={label}+ data-disabled={String(disabled)}+ data-is-disabled={String(isDisabled)}+ data-should-hide={String(shouldHideInMobile)}+ data-mobile={String(isMobile)}+ onClick={() => onTabClick(id)}+ >+ {text}+ </button>+ );+});++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ icon, style }) => (+ <span data-testid="fa-icon" data-icon={icon} style={style} />+ ),+}));++jest.mock('reactstrap', () => ({+ Nav: ({ children }) => <div data-testid="nav">{children}</div>,+ UncontrolledTooltip: ({ children }) => <div data-testid="tooltip">{children}</div>,+}));++const defaultProps = {+ tabTypes: { download: true, events: true },+ isMobile: false,+ isCompareMode: false,+ isChartMode: false,+ isEventsTabDisabledEmbed: false,+ onTabClick: jest.fn(),+ activeTab: 'layers',+ isDataDisabled: false,+ toggleSidebar: jest.fn(),+};++function renderCase(overrides = {}) {+ return render(<NavCase {...defaultProps} {...overrides} />);+}++describe('NavCase', () => {+ beforeEach(() => jest.clearAllMocks());++ describe('which tabs render', () => {+ it('always renders the Layers tab', () => {+ renderCase();+ expect(screen.getByTestId('nav-item-layers')).toBeInTheDocument();+ });++ it('renders the events tab when tabTypes.events is true', () => {+ renderCase();+ expect(screen.getByTestId('nav-item-events')).toBeInTheDocument();+ });++ it('does not render the events tab when tabTypes.events is false', () => {+ renderCase({ tabTypes: { download: true, events: false } });+ expect(screen.queryByTestId('nav-item-events')).toBeNull();+ });++ it('does not render the events tab when isEventsTabDisabledEmbed is true', () => {+ renderCase({ isEventsTabDisabledEmbed: true });+ expect(screen.queryByTestId('nav-item-events')).toBeNull();+ });++ it('renders the download tab when tabTypes.download is true', () => {+ renderCase();+ expect(screen.getByTestId('nav-item-download')).toBeInTheDocument();+ });++ it('does not render the download tab when tabTypes.download is false', () => {+ renderCase({ tabTypes: { download: false, events: true } });+ expect(screen.queryByTestId('nav-item-download')).toBeNull();+ });+ });++ describe('layers tab className', () => {+ it('is active when activeTab is layers', () => {+ renderCase({ activeTab: 'layers' });+ expect(screen.getByTestId('nav-item-layers')).toHaveAttribute('data-classname', 'sidebar-tab first-tab active');+ });++ it('is not active when another tab is active', () => {+ renderCase({ activeTab: 'events' });+ expect(screen.getByTestId('nav-item-layers')).toHaveAttribute('data-classname', 'sidebar-tab first-tab');+ });+ });++ describe('events tab', () => {+ it('is active when activeTab is events', () => {+ renderCase({ activeTab: 'events' });+ expect(screen.getByTestId('nav-item-events')).toHaveAttribute('data-classname', 'sidebar-tab second-tab active');+ });++ it('uses the default events label by default', () => {+ renderCase();+ expect(screen.getByTestId('nav-item-events')).toHaveAttribute('data-label', 'Natural Events');+ });++ it('uses the chart-mode label and disabled class when in chart mode', () => {+ renderCase({ isChartMode: true });+ const events = screen.getByTestId('nav-item-events');+ expect(events).toHaveAttribute('data-label', 'You must exit charting mode to use the natural events feature');+ expect(events).toHaveAttribute('data-classname', 'sidebar-tab second-tab disabled');+ expect(events).toHaveAttribute('data-disabled', 'true');+ });++ it('uses the compare-mode label and disabled class when in compare mode', () => {+ renderCase({ isCompareMode: true });+ const events = screen.getByTestId('nav-item-events');+ expect(events).toHaveAttribute('data-label', 'You must exit comparison mode to use the natural events feature');+ expect(events).toHaveAttribute('data-classname', 'sidebar-tab second-tab disabled');+ expect(events).toHaveAttribute('data-is-disabled', 'true');+ });+ });++ describe('download tab', () => {+ it('is active when activeTab is download', () => {+ renderCase({ activeTab: 'download' });+ expect(screen.getByTestId('nav-item-download')).toHaveAttribute('data-classname', 'sidebar-tab third-tab active');+ });++ it('uses the default data download label and class by default', () => {+ renderCase();+ const download = screen.getByTestId('nav-item-download');+ expect(download).toHaveAttribute('data-label', 'Data Download');+ expect(download).toHaveAttribute('data-classname', 'sidebar-tab third-tab');+ expect(download).toHaveAttribute('data-disabled', 'false');+ });++ it('uses the chart-mode label and disabled class when in chart mode', () => {+ renderCase({ activeTab: 'layers', isChartMode: true });+ const download = screen.getByTestId('nav-item-download');+ expect(download).toHaveAttribute('data-label', 'You must exit charting mode to download data');+ expect(download).toHaveAttribute('data-classname', 'sidebar-tab third-tab disabled');+ expect(download).toHaveAttribute('data-disabled', 'true');+ });++ it('uses the compare-mode label when in compare mode', () => {+ renderCase({ isCompareMode: true });+ const download = screen.getByTestId('nav-item-download');+ expect(download).toHaveAttribute('data-label', 'You must exit comparison mode to download data');+ expect(download).toHaveAttribute('data-disabled', 'true');+ });++ it('is disabled when data is disabled', () => {+ renderCase({ isDataDisabled: true });+ expect(screen.getByTestId('nav-item-download')).toHaveAttribute('data-is-disabled', 'true');+ });+ });++ describe('collapse button', () => {+ it('calls toggleSidebar when clicked', () => {+ const toggleSidebar = jest.fn();+ renderCase({ toggleSidebar });+ fireEvent.click(document.getElementById('toggleIconHolder'));+ expect(toggleSidebar).toHaveBeenCalled();+ });++ it('uses the caret-up icon on desktop', () => {+ renderCase({ isMobile: false });+ expect(screen.getByTestId('fa-icon')).toHaveAttribute('data-icon', 'caret-up');+ });++ it('uses the times icon on mobile', () => {+ renderCase({ isMobile: true });+ expect(screen.getByTestId('fa-icon')).toHaveAttribute('data-icon', 'times');+ });++ it('applies mobile sizing styles to the collapse button on mobile', () => {+ renderCase({ isMobile: true });+ expect(document.getElementById('toggleIconHolder')).toHaveStyle({ height: '48px', width: '45px' });+ });+ });++ describe('onTabClick wiring', () => {+ it('passes onTabClick through so a tab can fire it', () => {+ const onTabClick = jest.fn();+ renderCase({ onTabClick });+ fireEvent.click(screen.getByTestId('nav-item-layers'));+ expect(onTabClick).toHaveBeenCalledWith('layers');+ });+ });});diff --git a/web/js/components/sidebar/nav/nav-item.test.js b/web/js/components/sidebar/nav/nav-item.test.jsindex b667598c1..2afd610c7 100644--- a/web/js/components/sidebar/nav/nav-item.test.js+++ b/web/js/components/sidebar/nav/nav-item.test.js@@ -1,3 +1,119 @@-test('nav-item component test', () => {+/* eslint-disable react/prop-types */+/* eslint-disable react/jsx-props-no-spreading */+import '@testing-library/jest-dom';+import { render, screen, fireEvent } from '@testing-library/react';+import CustomNavItem from './nav-item';+jest.mock('reactstrap', () => ({+ NavItem: ({ children, style }) => (+ <div data-testid="nav-item" style={style}>{children}</div>+ ),+ NavLink: ({+ children, disabled, className, id, onClick, ...rest+ }) => (+ <button+ type="button"+ data-testid="nav-link"+ disabled={disabled}+ className={className}+ id={id}+ onClick={onClick}+ aria-label={rest['aria-label']}+ >+ {children}+ </button>+ ),+}));++jest.mock('../../util/hover-tooltip', () => function MockHoverTooltip({+ isMobile, labelText, target, placement,+}) {+ return (+ <div+ data-testid="hover-tooltip"+ data-mobile={String(isMobile)}+ data-label={labelText}+ data-target={target}+ data-placement={placement}+ />+ );+});++const defaultProps = {+ isMobile: false,+ shouldHideInMobile: false,+ isDisabled: false,+ label: 'Map Layers',+ className: 'sidebar-tab first-tab',+ onTabClick: jest.fn(),+ id: 'layers',+ iconClassName: 'icon-layers',+ text: 'Layers',+};++function renderItem(overrides = {}) {+ return render(<CustomNavItem {...defaultProps} {...overrides} />);+}++describe('CustomNavItem', () => {+ beforeEach(() => jest.clearAllMocks());++ it('renders the text and icon', () => {+ const { container } = renderItem();+ expect(screen.getByText('Layers')).toBeInTheDocument();+ expect(container.querySelector('i')).toHaveClass('productsIcon', 'selected', 'icon-layers');+ });++ it('applies the provided className and aria-label to the NavLink', () => {+ renderItem();+ const link = screen.getByTestId('nav-link');+ expect(link).toHaveClass('sidebar-tab', 'first-tab');+ expect(link).toHaveAttribute('aria-label', 'Map Layers');+ });++ it('builds the tab id from the id prop', () => {+ renderItem();+ expect(screen.getByTestId('nav-link')).toHaveAttribute('id', 'layers-sidebar-tab');+ });++ it('passes disabled through to the NavLink', () => {+ renderItem({ isDisabled: true });+ expect(screen.getByTestId('nav-link')).toBeDisabled();+ });++ it('is enabled when isDisabled is false', () => {+ renderItem({ isDisabled: false });+ expect(screen.getByTestId('nav-link')).not.toBeDisabled();+ });++ it('calls onTabClick with the id when clicked', () => {+ const onTabClick = jest.fn();+ renderItem({ onTabClick });+ fireEvent.click(screen.getByTestId('nav-link'));+ expect(onTabClick).toHaveBeenCalledWith('layers');+ });++ it('hides the item when shouldHideInMobile and isMobile are both true', () => {+ renderItem({ shouldHideInMobile: true, isMobile: true });+ expect(screen.getByTestId('nav-item')).toHaveStyle({ display: 'none' });+ });++ it('shows the item when shouldHideInMobile is true but isMobile is false', () => {+ renderItem({ shouldHideInMobile: true, isMobile: false });+ expect(screen.getByTestId('nav-item')).toHaveStyle({ display: 'block' });+ });++ it('shows the item when isMobile is true but shouldHideInMobile is false', () => {+ renderItem({ shouldHideInMobile: false, isMobile: true });+ expect(screen.getByTestId('nav-item')).toHaveStyle({ display: 'block' });+ });++ it('passes the expected props to the HoverTooltip', () => {+ renderItem({ isMobile: true });+ const tooltip = screen.getByTestId('hover-tooltip');+ expect(tooltip).toHaveAttribute('data-mobile', 'true');+ expect(tooltip).toHaveAttribute('data-label', 'Map Layers');+ expect(tooltip).toHaveAttribute('data-target', 'layers-sidebar-tab');+ expect(tooltip).toHaveAttribute('data-placement', 'top');+ });});