Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Checking in next batch of unit tests for containers/ directory.

Jason Hurleyd2d19e3a3d5f
diff --git a/web/js/containers/alertDropdown.test.js b/web/js/containers/alertDropdown.test.js
index 6e342db98..a929c9da5 100644
--- a/web/js/containers/alertDropdown.test.js
+++ b/web/js/containers/alertDropdown.test.js
@@ -1,3 +1,79 @@
-test('alertDropdown container test', () => {
+/* eslint-disable react/prop-types */
+import { render, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+
+let mockState;
+jest.mock('react-redux', () => ({
+ useSelector: (selector) => selector(mockState),
+}));
+
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: (props) => <i data-testid="fa-icon" data-icon={String(props.icon)} />,
+}));
+
+jest.mock('../components/feature-alert/alert', () => () => <div data-testid="feature-alert" />);
+jest.mock('./alerts', () => () => <div data-testid="alerts" />);
+
+const AlertDropdown = require('./alertDropdown').default;
+
+const makeState = (overrides = {}) => ({
+ ui: { isDistractionFreeModeActive: false },
+ screenSize: { isMobileDevice: false },
+ ...overrides,
+});
+
+beforeEach(() => {
+ mockState = makeState();
+});
+
+describe('AlertDropdown', () => {
+ it('renders the dropdown wrapper visible by default', () => {
+ const { container } = render(<AlertDropdown isTourActive={false} />);
+ const wrapper = container.querySelector('.wv-alert-dropdown');
+ expect(wrapper).toBeInTheDocument();
+ expect(wrapper).not.toHaveAttribute('hidden');
+ });
+
+ it('hides the wrapper when distraction free mode is active', () => {
+ mockState = makeState({ ui: { isDistractionFreeModeActive: true } });
+ const { container } = render(<AlertDropdown isTourActive={false} />);
+ expect(container.querySelector('.wv-alert-dropdown')).toHaveAttribute('hidden');
+ });
+
+ it('hides the wrapper when the tour is active', () => {
+ const { container } = render(<AlertDropdown isTourActive />);
+ expect(container.querySelector('.wv-alert-dropdown')).toHaveAttribute('hidden');
+ });
+
+ it('hides the wrapper on mobile devices', () => {
+ mockState = makeState({ screenSize: { isMobileDevice: true } });
+ const { container } = render(<AlertDropdown isTourActive={false} />);
+ expect(container.querySelector('.wv-alert-dropdown')).toHaveAttribute('hidden');
+ });
+
+ it('renders FeatureAlert and Alerts inside the alert container', () => {
+ const { getByTestId } = render(<AlertDropdown isTourActive={false} />);
+ expect(getByTestId('feature-alert')).toBeInTheDocument();
+ expect(getByTestId('alerts')).toBeInTheDocument();
+ });
+
+ it('toggles the dropdown open and closed via the button', () => {
+ const { container } = render(<AlertDropdown isTourActive={false} />);
+ const button = container.querySelector('button');
+ expect(container.querySelector('.wv-alert-footer')).toHaveAttribute('hidden');
+ fireEvent.click(button);
+ // with two children in the container, footer shows when open
+ expect(container.querySelector('.wv-alert-footer')).not.toHaveAttribute('hidden');
+ fireEvent.click(button);
+ expect(container.querySelector('.wv-alert-footer')).toHaveAttribute('hidden');
+ });
+
+ it('shows the alert container when the dropdown is open', () => {
+ const { container } = render(<AlertDropdown isTourActive={false} />);
+ const button = container.querySelector('button');
+ expect(container.querySelector('#wv-alert-container')).toHaveAttribute('hidden');
+ fireEvent.click(button);
+ expect(container.querySelector('#wv-alert-container')).not.toHaveAttribute('hidden');
+ });
});
diff --git a/web/js/containers/alerts.test.js b/web/js/containers/alerts.test.js
index ee5325fc8..a81c59bbd 100644
--- a/web/js/containers/alerts.test.js
+++ b/web/js/containers/alerts.test.js
@@ -1,3 +1,298 @@
-test('alert container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, act } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+let mockCapturedAlerts = [];
+jest.mock('../components/util/alert', () => (props) => {
+ mockCapturedAlerts.push(props);
+ return <div data-testid="alert" data-message={props.message} />;
+});
+
+jest.mock('../modules/modal/actions', () => ({
+ openCustomContent: jest.fn((id, params) => ({ type: 'OPEN_CUSTOM_CONTENT', id, params })),
+}));
+
+jest.mock('../modules/layers/util', () => ({
+ hasVectorLayers: jest.fn(() => false),
+}));
+
+jest.mock('../modules/alerts/constants', () => ({
+ DISABLE_VECTOR_ZOOM_ALERT: 'DISABLE_VECTOR_ZOOM_ALERT',
+ DISABLE_VECTOR_EXCEEDED_ALERT: 'DISABLE_VECTOR_EXCEEDED_ALERT',
+ MODAL_PROPERTIES: {
+ eventModalProps: { id: 'event_modal', props: { event: true } },
+ compareModalProps: { id: 'compare_modal', props: { compare: true } },
+ vectorModalProps: { id: 'vector_modal', props: { vector: true } },
+ granuleModalProps: { id: 'granule_modal', props: { granule: true } },
+ zoomModalProps: { id: 'zoom_modal', props: { zoom: true } },
+ },
+}));
+
+jest.mock('../util/local-storage', () => ({
+ __esModule: true,
+ default: {
+ enabled: true,
+ keys: {
+ DISMISSED_COMPARE_ALERT: 'DISMISSED_COMPARE_ALERT',
+ DISMISSED_DISTRACTION_FREE_ALERT: 'DISMISSED_DISTRACTION_FREE_ALERT',
+ DISMISSED_EVENT_VIS_ALERT: 'DISMISSED_EVENT_VIS_ALERT',
+ DISSMISSED_DDV_ZOOM_ALERT: 'DISSMISSED_DDV_ZOOM_ALERT',
+ DISSMISSED_DDV_LOCATION_ALERT: 'DISSMISSED_DDV_LOCATION_ALERT',
+ },
+ getItem: jest.fn(() => null),
+ setItem: jest.fn(),
+ },
+}));
+
+jest.mock('../modules/layers/selectors', () => ({
+ getActiveLayers: jest.fn(() => []),
+ subdailyLayersActive: jest.fn(() => false),
+}));
+
+const DismissableAlerts = require('./alerts').default;
+const safeLocalStorage = require('../util/local-storage').default;
+const { openCustomContent } = require('../modules/modal/actions');
+const { hasVectorLayers } = require('../modules/layers/util');
+const { getActiveLayers, subdailyLayersActive } = require('../modules/layers/selectors');
+
+const defaultProps = {
+ ddvZoomAlerts: [],
+ ddvLocationAlerts: [],
+ dismissVectorZoomAlert: jest.fn(),
+ dismissVectorExceededAlert: jest.fn(),
+ hasSubdailyLayers: false,
+ isAnimationActive: false,
+ isCompareActive: false,
+ isDistractionFreeModeActive: false,
+ isEmbedModeActive: false,
+ isEventsActive: false,
+ isSmall: false,
+ isMobile: false,
+ isVectorZoomAlertPresent: false,
+ isVectorExceededAlertPresent: false,
+ isDDVZoomAlertPresent: false,
+ isDDVLocationAlertPresent: false,
+ openAlertModal: jest.fn(),
+ openGranuleAlertModal: jest.fn(),
+ openZoomAlertModal: jest.fn(),
+};
+
+const renderComponent = (props = {}) => render(
+ <DismissableAlerts {...defaultProps} {...props} />,
+);
+
+const findAlert = (message) => mockCapturedAlerts.find((a) => a.message.includes(message));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockCapturedAlerts = [];
+ safeLocalStorage.getItem.mockReturnValue(null);
+});
+
+describe('DismissableAlerts render', () => {
+ it('renders nothing when no alerts are present', () => {
+ const { container } = renderComponent();
+ expect(container.querySelectorAll('[data-testid="alert"]')).toHaveLength(0);
+ });
+
+ it('returns null in embed mode', () => {
+ const { container } = renderComponent({ isEmbedModeActive: true, isEventsActive: true });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('returns null when distraction free mode is active on initial load', () => {
+ const { container } = renderComponent({ isDistractionFreeModeActive: true });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('shows the distraction free alert after leaving and re-entering', () => {
+ const { rerender } = renderComponent({ isDistractionFreeModeActive: true });
+ // leaving distraction free mode clears the init load flag
+ act(() => {
+ rerender(<DismissableAlerts {...defaultProps} isDistractionFreeModeActive={false} />);
+ });
+ mockCapturedAlerts = [];
+ act(() => {
+ rerender(<DismissableAlerts {...defaultProps} isDistractionFreeModeActive />);
+ });
+ const alert = findAlert('distraction free mode');
+ expect(alert).toBeDefined();
+ act(() => { alert.onDismiss(); });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('DISMISSED_DISTRACTION_FREE_ALERT', true);
+ });
+
+ it('shows the events alert and supports click and dismiss', () => {
+ const openAlertModal = jest.fn();
+ renderComponent({ isEventsActive: true, openAlertModal });
+ const alert = findAlert('Events may not be visible');
+ expect(alert).toBeDefined();
+ alert.onClick();
+ expect(openAlertModal).toHaveBeenCalledWith({ id: 'event_modal', props: { event: true } });
+ act(() => { alert.onDismiss(); });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('DISMISSED_EVENT_VIS_ALERT', true);
+ expect(mockCapturedAlerts.filter((a) => a.message.includes('Events may not'))).toHaveLength(1);
+ });
+
+ it('does not show the events alert when previously dismissed', () => {
+ safeLocalStorage.getItem.mockReturnValue('true');
+ renderComponent({ isEventsActive: true });
+ expect(findAlert('Events may not be visible')).toBeUndefined();
+ });
+
+ it('does not show events or compare alerts on small screens', () => {
+ renderComponent({ isEventsActive: true, isCompareActive: true, isSmall: true });
+ expect(mockCapturedAlerts).toHaveLength(0);
+ });
+
+ it('shows the compare alert with click and dismiss', () => {
+ const openAlertModal = jest.fn();
+ renderComponent({ isCompareActive: true, openAlertModal });
+ const alert = findAlert('comparison mode');
+ expect(alert).toBeDefined();
+ alert.onClick();
+ expect(openAlertModal).toHaveBeenCalledWith({ id: 'compare_modal', props: { compare: true } });
+ act(() => { alert.onDismiss(); });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('DISMISSED_COMPARE_ALERT', true);
+ });
+
+ it('shows the vector zoom alert with dismiss callback from props', () => {
+ const dismissVectorZoomAlert = jest.fn();
+ const openAlertModal = jest.fn();
+ renderComponent({ isVectorZoomAlertPresent: true, dismissVectorZoomAlert, openAlertModal });
+ const alert = findAlert('Vector features may not be clickable');
+ alert.onClick();
+ expect(openAlertModal).toHaveBeenCalledWith({ id: 'vector_modal', props: { vector: true } });
+ alert.onDismiss();
+ expect(dismissVectorZoomAlert).toHaveBeenCalled();
+ });
+
+ it('shows the vector exceeded alert', () => {
+ const dismissVectorExceededAlert = jest.fn();
+ renderComponent({ isVectorExceededAlertPresent: true, dismissVectorExceededAlert });
+ const alert = findAlert('Too many results');
+ alert.onDismiss();
+ expect(dismissVectorExceededAlert).toHaveBeenCalled();
+ });
+
+ it('shows the animation data alert on mobile with subdaily layers', () => {
+ renderComponent({ isMobile: true, isAnimationActive: true, hasSubdailyLayers: true });
+ const alert = findAlert('large amount of data');
+ expect(alert).toBeDefined();
+ alert.onDismiss();
+ });
+
+ it('shows DDV zoom alerts per layer', () => {
+ const openZoomAlertModal = jest.fn();
+ renderComponent({
+ isDDVZoomAlertPresent: true,
+ ddvZoomAlerts: ['Layer One', 'Layer Two'],
+ openZoomAlertModal,
+ });
+ const zoomAlerts = mockCapturedAlerts.filter((a) => a.message.includes('zoom level'));
+ expect(zoomAlerts).toHaveLength(2);
+ expect(zoomAlerts[0].onClick).toBe(openZoomAlertModal);
+ act(() => { zoomAlerts[0].onDismiss(); });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('DISSMISSED_DDV_ZOOM_ALERT', true);
+ });
+
+ it('shows DDV location alerts per layer', () => {
+ const openGranuleAlertModal = jest.fn();
+ renderComponent({
+ isDDVLocationAlertPresent: true,
+ ddvLocationAlerts: ['Layer Three'],
+ openGranuleAlertModal,
+ });
+ const locationAlerts = mockCapturedAlerts.filter((a) => a.message.includes('location or date'));
+ expect(locationAlerts).toHaveLength(1);
+ expect(locationAlerts[0].onClick).toBe(openGranuleAlertModal);
+ act(() => { locationAlerts[0].onDismiss(); });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('DISSMISSED_DDV_LOCATION_ALERT', true);
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (overrides = {}) => ({
+ embed: { isEmbedModeActive: false },
+ events: { selected: { id: 'event1' } },
+ sidebar: { activeTab: 'events' },
+ compare: { active: true },
+ alerts: {
+ isVectorZoomAlertPresent: true,
+ isVectorExceededAlertPresent: true,
+ isDDVZoomAlertPresent: false,
+ isDDVLocationAlertPresent: false,
+ ddvZoomAlerts: [],
+ ddvLocationAlerts: [],
+ },
+ ui: { isDistractionFreeModeActive: false },
+ animation: { isActive: false },
+ screenSize: { screenWidth: 1200, breakpoints: { small: 740 }, isMobileDevice: false },
+ ...overrides,
+ });
+
+ it('maps alert state with vector layers present', () => {
+ hasVectorLayers.mockReturnValue(true);
+ const result = capturedMapState(makeState());
+ expect(result.isEventsActive).toBe(true);
+ expect(result.isCompareActive).toBe(true);
+ expect(result.isVectorZoomAlertPresent).toBe(true);
+ expect(result.isVectorExceededAlertPresent).toBe(true);
+ expect(result.isSmall).toBe(false);
+ expect(getActiveLayers).toHaveBeenCalled();
+ expect(subdailyLayersActive).toHaveBeenCalled();
+ });
+
+ it('vector alerts are false without active vector layers', () => {
+ hasVectorLayers.mockReturnValue(false);
+ const result = capturedMapState(makeState());
+ expect(result.isVectorZoomAlertPresent).toBe(false);
+ expect(result.isVectorExceededAlertPresent).toBe(false);
+ });
+
+ it('isEventsActive is false when no event selected', () => {
+ const result = capturedMapState(makeState({ events: { selected: {} } }));
+ expect(result.isEventsActive).toBe(false);
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('openAlertModal dispatches openCustomContent with given props', () => {
+ props.openAlertModal({ id: 'my_modal', props: { a: 1 } });
+ expect(openCustomContent).toHaveBeenCalledWith('my_modal', { a: 1 });
+ });
+
+ it('openGranuleAlertModal uses granule modal props', () => {
+ props.openGranuleAlertModal();
+ expect(openCustomContent).toHaveBeenCalledWith('granule_modal', { granule: true });
+ });
+
+ it('openZoomAlertModal uses zoom modal props', () => {
+ props.openZoomAlertModal();
+ expect(openCustomContent).toHaveBeenCalledWith('zoom_modal', { zoom: true });
+ });
+
+ it('dismiss actions dispatch the disable types', () => {
+ props.dismissVectorZoomAlert();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'DISABLE_VECTOR_ZOOM_ALERT' });
+ props.dismissVectorExceededAlert();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'DISABLE_VECTOR_EXCEEDED_ALERT' });
+ });
});
diff --git a/web/js/containers/embed.test.js b/web/js/containers/embed.test.js
index 21a5e856c..55510dbf3 100644
--- a/web/js/containers/embed.test.js
+++ b/web/js/containers/embed.test.js
@@ -1,3 +1,114 @@
-test('embed container test', () => {
+/* eslint-disable react/prop-types */
+import { render, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+
+let capturedMapState;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ return (Component) => Component;
+ },
+}));
+
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: (props) => <i data-icon={String(props.icon)} />,
+}));
+
+jest.mock('googleTagManager', () => ({
+ __esModule: true,
+ default: { pushEvent: jest.fn() },
+}));
+
+jest.mock('../modules/link/util', () => ({
+ getPermalink: jest.fn(() => 'https://example.com/permalink'),
+}));
+
+jest.mock('../modules/date/selectors', () => ({
+ getSelectedDate: jest.fn(() => new Date('2021-01-01T00:00:00Z')),
+}));
+
+jest.mock('../components/util/hover-tooltip', () => () => <span data-testid="tooltip" />);
+
+jest.mock('../main', () => ({
+ __esModule: true,
+ default: { location: { search: '?p=geographic' } },
+}));
+
+const Embed = require('./embed').default;
+const googleTagManager = require('googleTagManager').default;
+const { getPermalink } = require('../modules/link/util');
+const { getSelectedDate } = require('../modules/date/selectors');
+
+const selectedDate = new Date('2021-01-01T00:00:00Z');
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ getPermalink.mockReturnValue('https://example.com/permalink');
+});
+
+describe('Embed component', () => {
+ it('renders nothing when embed mode is not active', () => {
+ const { container } = render(
+ <Embed isEmbedModeActive={false} selectedDate={selectedDate} isMobile={false} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders the embed wrapper and link button when active', () => {
+ const { container } = render(
+ <Embed isEmbedModeActive selectedDate={selectedDate} isMobile={false} />,
+ );
+ expect(container.querySelector('#embed-mode-wrapper')).toBeInTheDocument();
+ expect(container.querySelector('#wv-embed-link-button')).toBeInTheDocument();
+ });
+
+ it('opens the permalink in a new tab on button click', () => {
+ const openSpy = jest.spyOn(window, 'open').mockImplementation(() => {});
+ const { container } = render(
+ <Embed isEmbedModeActive selectedDate={selectedDate} isMobile={false} />,
+ );
+ fireEvent.click(container.querySelector('#wv-embed-link-button'));
+ expect(getPermalink).toHaveBeenCalledWith('?p=geographic', selectedDate);
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'embed_open_new_tab' });
+ expect(openSpy).toHaveBeenCalledWith('https://example.com/permalink', '_blank');
+ openSpy.mockRestore();
+ });
+
+ it('shows the click-to-interact overlay on mouse enter and hides it on leave', () => {
+ const { container } = render(
+ <Embed isEmbedModeActive selectedDate={selectedDate} isMobile={false} />,
+ );
+ const wrapper = container.querySelector('#embed-mode-wrapper');
+ fireEvent.mouseEnter(wrapper);
+ expect(container.querySelector('.embed-overlay-bg')).toBeInTheDocument();
+ fireEvent.mouseLeave(wrapper);
+ expect(container.querySelector('.embed-overlay-bg')).toBeNull();
+ });
+
+ it('removes the overlay permanently after clicking it', () => {
+ const { container } = render(
+ <Embed isEmbedModeActive selectedDate={selectedDate} isMobile={false} />,
+ );
+ const wrapper = container.querySelector('#embed-mode-wrapper');
+ fireEvent.mouseEnter(wrapper);
+ fireEvent.click(container.querySelector('.embed-overlay-bg'));
+ expect(container.querySelector('.embed-overlay-bg')).toBeNull();
+ // wrapper id removed after click
+ expect(container.querySelector('#embed-mode-wrapper')).toBeNull();
+ });
+});
+
+describe('mapStateToProps', () => {
+ it('maps embed and screenSize state', () => {
+ const state = {
+ screenSize: { isMobileDevice: true },
+ embed: { isEmbedModeActive: true },
+ };
+ const result = capturedMapState(state);
+ expect(result.isEmbedModeActive).toBe(true);
+ expect(result.isMobile).toBe(true);
+ expect(getSelectedDate).toHaveBeenCalledWith(state);
+ expect(result.selectedDate).toEqual(selectedDate);
+ });
});
diff --git a/web/js/containers/error-boundary.test.js b/web/js/containers/error-boundary.test.js
index 55a998585..716b9337c 100644
--- a/web/js/containers/error-boundary.test.js
+++ b/web/js/containers/error-boundary.test.js
@@ -1,3 +1,76 @@
-test('error-boundary container test', () => {
+/* eslint-disable react/prop-types */
+import { render } from '@testing-library/react';
+import '@testing-library/jest-dom';
+
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: (props) => <i data-icon={String(props.icon)} />,
+}));
+
+jest.mock('../modules/modal/actions', () => ({
+ openCustomContent: jest.fn((id, params) => ({ type: 'OPEN_CUSTOM_CONTENT', id, params })),
+}));
+
+const ErrorBoundary = require('./error-boundary').default;
+const { openCustomContent } = require('../modules/modal/actions');
+
+function Bomb() {
+ throw new Error('boom');
+}
+
+describe('ErrorBoundary', () => {
+ it('renders children when no error occurs', () => {
+ const { getByText } = render(
+ <ErrorBoundary errorAlert={jest.fn()}>
+ <div>safe child</div>
+ </ErrorBoundary>,
+ );
+ expect(getByText('safe child')).toBeInTheDocument();
+ });
+
+ it('renders nothing and calls errorAlert when a child throws', () => {
+ const errorAlert = jest.fn();
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
+ const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ const { container } = render(
+ <ErrorBoundary errorAlert={errorAlert}>
+ <Bomb />
+ </ErrorBoundary>,
+ );
+ expect(errorAlert).toHaveBeenCalled();
+ expect(consoleWarn).toHaveBeenCalled();
+ expect(container).toBeEmptyDOMElement();
+ consoleError.mockRestore();
+ consoleWarn.mockRestore();
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ it('errorAlert dispatches the error modal with header and body', () => {
+ const dispatch = jest.fn();
+ const props = capturedMapDispatch(dispatch);
+ props.errorAlert();
+ expect(openCustomContent).toHaveBeenCalledWith('ERROR_MODAL', expect.objectContaining({
+ headerText: 'Error!',
+ bodyComponent: expect.any(Function),
+ }));
+ expect(dispatch).toHaveBeenCalled();
+ });
+
+ it('the body component renders the error message content', () => {
+ const dispatch = jest.fn();
+ capturedMapDispatch(dispatch).errorAlert();
+ const { bodyComponent: Body } = openCustomContent.mock.calls.at(-1)[1];
+ const { container } = render(<Body />);
+ expect(container.querySelector('.error-header')).toBeInTheDocument();
+ expect(container.querySelector('.error-body')).toBeInTheDocument();
+ });
});
diff --git a/web/js/containers/gif.test.js b/web/js/containers/gif.test.js
index 8adbe1eb9..79ea83461 100644
--- a/web/js/containers/gif.test.js
+++ b/web/js/containers/gif.test.js
@@ -1,3 +1,410 @@
-test('gif container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, act } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+const mockCreateGIF = jest.fn();
+const mockCancel = jest.fn();
+jest.mock('../modules/animation/gifstream', () => ({
+ __esModule: true,
+ default: class MockGifStream {
+ createGIF(...args) { mockCreateGIF(...args); }
+
+ cancel(...args) { mockCancel(...args); }
+ },
+}));
+
+let mockGifPanelProps = null;
+jest.mock('../components/animation-widget/gif-panel', () => (props) => {
+ mockGifPanelProps = props;
+ return <div data-testid="gif-panel" />;
+});
+
+let mockGifResultsProps = null;
+jest.mock('../components/animation-widget/gif-post-creation', () => (props) => {
+ mockGifResultsProps = props;
+ return <div data-testid="gif-results" />;
+});
+
+let mockCropProps = null;
+jest.mock('../components/util/image-crop', () => (props) => {
+ mockCropProps = props;
+ return <div data-testid="crop" />;
+});
+
+let mockModalProps = null;
+jest.mock('reactstrap', () => ({
+ Modal: (props) => {
+ mockModalProps = props;
+ return <div data-testid="modal">{props.children}</div>;
+ },
+ ModalBody: ({ children }) => <div data-testid="modal-body">{children}</div>,
+ ModalHeader: (props) => (
+ <div data-testid="modal-header">
+ {props.children}
+ {props.close}
+ </div>
+ ),
+ Progress: (props) => <div data-testid="progress" data-value={props.value} />,
+ Spinner: () => <div data-testid="spinner" />,
+}));
+
+jest.mock('ol/proj', () => ({
+ transform: jest.fn((coord) => coord),
+}));
+
+jest.mock('lodash', () => ({
+ ...jest.requireActual('lodash'),
+ debounce: (fn) => fn,
+}));
+
+jest.mock('../util/util', () => ({
+ __esModule: true,
+ default: {
+ formatCoordinate: jest.fn((coord) => `fmt(${coord.join(',')})`),
+ warn: jest.fn(),
+ },
+}));
+
+jest.mock('../modules/image-download/util', () => ({
+ imageUtilCalculateResolution: jest.fn(() => '1km'),
+ imageUtilGetCoordsFromPixelValues: jest.fn(() => [[0, 0], [10, 10]]),
+}));
+
+jest.mock('../modules/date/constants', () => ({
+ TIME_SCALE_FROM_NUMBER: {
+ 1: 'year', 2: 'month', 3: 'day', 4: 'hour', 5: 'minute',
+ },
+}));
+
+jest.mock('../modules/animation/selectors', () => ({
+ __esModule: true,
+ default: jest.fn(() => ['image1', 'image2']),
+}));
+
+jest.mock('../modules/animation/util', () => ({
+ getStampProps: jest.fn(() => ({
+ stampHeight: 30,
+ dateStamp: {
+ fontSize: 20, x: 5, y: 6, align: 'left',
+ },
+ })),
+ svgToPng: jest.fn(() => ({ width: 100, height: 30 })),
+ getNumberOfSteps: jest.fn(() => 12),
+}));
+
+jest.mock('../modules/animation/actions', () => ({
+ changeCropBounds: jest.fn((bounds) => ({ type: 'CHANGE_CROP_BOUNDS', bounds })),
+}));
+
+jest.mock('../modules/layers/selectors', () => ({
+ subdailyLayersActive: jest.fn(() => false),
+}));
+
+jest.mock('../modules/date/util', () => ({
+ formatDisplayDate: jest.fn((date) => `display-${date}`),
+}));
+
+const Gif = require('./gif').default;
+const util = require('../util/util').default;
+const getImageArray = require('../modules/animation/selectors').default;
+const { getStampProps, svgToPng, getNumberOfSteps } = require('../modules/animation/util');
+const { changeCropBounds } = require('../modules/animation/actions');
+
+const defaultProps = {
+ boundaries: null,
+ startDate: new Date('2020-01-01T00:00:00Z'),
+ endDate: new Date('2020-01-10T00:00:00Z'),
+ startDateStr: '2020 JAN 01',
+ endDateStr: '2020 JAN 10',
+ getImageArrayFunc: jest.fn(() => ['img']),
+ increment: '1 day Between Frames',
+ map: {
+ ui: {
+ selected: {
+ getView: jest.fn(() => ({ getZoom: jest.fn(() => 3) })),
+ },
+ },
+ },
+ numberOfFrames: 12,
+ onBoundaryChange: jest.fn(),
+ onClose: jest.fn(),
+ proj: { id: 'geographic', crs: 'EPSG:4326', resolutions: [1, 2] },
+ screenHeight: 800,
+ screenWidth: 1200,
+ speed: 3,
+ url: 'http://snapshot.test',
+};
+
+const renderComponent = (props = {}) => render(<Gif {...defaultProps} {...props} />);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockGifPanelProps = null;
+ mockGifResultsProps = null;
+ mockCropProps = null;
+ mockModalProps = null;
+});
+
+describe('GIF selectable box', () => {
+ it('renders the gif panel and crop with default boundaries', () => {
+ const { getByTestId } = renderComponent();
+ expect(getByTestId('gif-panel')).toBeInTheDocument();
+ expect(getByTestId('crop')).toBeInTheDocument();
+ // default boundaries x=500,y=300,x2=700,y2=500
+ expect(mockCropProps.x).toBe(500);
+ expect(mockCropProps.width).toBe(200);
+ expect(mockGifPanelProps.startDate).toBe('2020 JAN 01');
+ expect(mockGifPanelProps.numberOfFrames).toBe(12);
+ });
+
+ it('toggles the showDates checkbox', () => {
+ renderComponent();
+ expect(mockGifPanelProps.showDates).toBe(true);
+ act(() => {
+ mockGifPanelProps.onCheck();
+ });
+ expect(mockGifPanelProps.showDates).toBe(false);
+ });
+
+ it('renders the close button which calls onClose', () => {
+ const onClose = jest.fn();
+ const { container } = renderComponent({ onClose });
+ const btn = container.querySelector('.modal-close-btn');
+ btn.click();
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('updates boundaries and modal offsets on crop change', () => {
+ const onBoundaryChange = jest.fn();
+ renderComponent({ onBoundaryChange });
+ act(() => {
+ mockCropProps.onChange({
+ x: 100, y: 100, width: 80, height: 60,
+ });
+ });
+ expect(onBoundaryChange).toHaveBeenCalledWith({
+ x: 100, y: 100, x2: 180, y2: 160,
+ });
+ expect(mockCropProps.x).toBe(100);
+ expect(mockCropProps.width).toBe(80);
+ });
+});
+
+describe('getModalOffsets placement', () => {
+ it('places the modal to the left when it would overflow on the right', () => {
+ renderComponent({
+ boundaries: {
+ x: 700, y: 100, x2: 1100, y2: 300,
+ },
+ });
+ // left = 1120 > 1200-342 → x - padding - width = 700-20-342 = 338
+ expect(mockModalProps.style.left).toBe(338);
+ });
+
+ it('places the modal below when no room on either side and y < height', () => {
+ renderComponent({
+ boundaries: {
+ x: 50, y: 100, x2: 1190, y2: 300,
+ },
+ });
+ // left = 1210 → 1210-342-20 = 848; y(100) < 280 → top = y2 = 300
+ expect(mockModalProps.style.left).toBe(848);
+ expect(mockModalProps.style.top).toBe(300);
+ });
+
+ it('places the modal above when no room on either side and y >= height', () => {
+ renderComponent({
+ boundaries: {
+ x: 50, y: 400, x2: 1190, y2: 600,
+ },
+ });
+ // top = y - padding - height = 400-20-280 = 100
+ expect(mockModalProps.style.top).toBe(100);
+ });
+
+ it('clamps the modal to the bottom of the screen', () => {
+ renderComponent({
+ boundaries: {
+ x: 500, y: 700, x2: 700, y2: 780,
+ },
+ });
+ // top = 680; 680+280 > 800 → 800-20-280 = 500
+ expect(mockModalProps.style.top).toBe(500);
+ });
+});
+
+describe('GIF creation flow', () => {
+ it('creates a GIF and shows results on success', () => {
+ const getImageArrayFunc = jest.fn(() => ['img1', 'img2']);
+ const { getByTestId, queryByTestId } = renderComponent({ getImageArrayFunc });
+ act(() => {
+ mockGifPanelProps.onClick(300, 200);
+ });
+ expect(getStampProps).toHaveBeenCalled();
+ expect(svgToPng).toHaveBeenCalled();
+ expect(getImageArrayFunc).toHaveBeenCalledWith(
+ expect.objectContaining({ url: 'http://snapshot.test', showDates: true }),
+ { width: 300, height: 200 },
+ );
+ expect(mockCreateGIF).toHaveBeenCalled();
+ // while downloading, the requesting imagery modal shows a spinner
+ expect(getByTestId('spinner')).toBeInTheDocument();
+
+ const [options, onComplete] = mockCreateGIF.mock.calls[0];
+ act(() => {
+ options.progressCallback(42);
+ });
+ expect(getByTestId('progress')).toHaveAttribute('data-value', '42');
+ expect(queryByTestId('spinner')).toBeNull();
+
+ act(() => {
+ onComplete({ blob: { size: 1024000 } });
+ });
+ expect(getByTestId('gif-results')).toBeInTheDocument();
+ expect(mockGifResultsProps.gifObject.width).toBe(300);
+ // size = round((1024000 / 1024) * 0.001, 2) MB
+ expect(mockGifResultsProps.gifObject.size).toBe(1);
+ });
+
+ it('resets state when GIF creation errors', () => {
+ const { getByTestId, queryByTestId } = renderComponent();
+ act(() => {
+ mockGifPanelProps.onClick(300, 200);
+ });
+ const [, onComplete] = mockCreateGIF.mock.calls[0];
+ act(() => {
+ onComplete({ error: 'failed' });
+ });
+ expect(queryByTestId('gif-results')).toBeNull();
+ expect(getByTestId('gif-panel')).toBeInTheDocument();
+ });
+
+ it('resets state when GIF creation is cancelled while mounted', () => {
+ const { getByTestId } = renderComponent();
+ act(() => {
+ mockGifPanelProps.onClick(300, 200);
+ });
+ const [, onComplete] = mockCreateGIF.mock.calls[0];
+ act(() => {
+ onComplete({ cancelled: true });
+ });
+ expect(getByTestId('gif-panel')).toBeInTheDocument();
+ });
+
+ it('does not build a GIF when image array is unavailable (too many frames)', () => {
+ const getImageArrayFunc = jest.fn(() => false);
+ renderComponent({ getImageArrayFunc });
+ act(() => {
+ mockGifPanelProps.onClick(300, 200);
+ });
+ expect(mockCreateGIF).not.toHaveBeenCalled();
+ });
+
+ it('cancels the gif stream when unmounted while downloading', () => {
+ const { unmount } = renderComponent();
+ act(() => {
+ mockGifPanelProps.onClick(300, 200);
+ });
+ unmount();
+ expect(mockCancel).toHaveBeenCalled();
+ });
+
+ it('does not cancel when unmounted while idle', () => {
+ const { unmount } = renderComponent();
+ unmount();
+ expect(mockCancel).not.toHaveBeenCalled();
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (overrides = {}) => ({
+ screenSize: { screenWidth: 1440, screenHeight: 900 },
+ proj: { selected: { id: 'geographic', crs: 'EPSG:4326' } },
+ animation: {
+ speed: 5,
+ startDate: new Date('2020-01-01T00:00:00Z'),
+ endDate: new Date('2020-01-05T00:00:00Z'),
+ boundaries: { x: 1, y: 2, x2: 3, y2: 4 },
+ gifActive: true,
+ },
+ map: { ui: {} },
+ date: {
+ customSelected: false,
+ autoSelected: false,
+ interval: 3,
+ customInterval: 4,
+ customDelta: 2,
+ },
+ config: { features: {}, parameters: {} },
+ layers: { active: { layers: [] } },
+ ...overrides,
+ });
+
+ it('maps animation state with standard increment', () => {
+ const result = capturedMapState(makeState());
+ expect(result.increment).toBe('1 day Between Frames');
+ expect(result.speed).toBe(5);
+ expect(result.isActive).toBe(true);
+ expect(result.url).toBe('http://localhost:3002/api/v1/snapshot');
+ expect(result.numberOfFrames).toBe(12);
+ expect(getNumberOfSteps).toHaveBeenCalled();
+ });
+
+ it('uses the custom interval when customSelected', () => {
+ const state = makeState();
+ state.date.customSelected = true;
+ const result = capturedMapState(state);
+ expect(result.increment).toBe('2 hour Between Frames');
+ });
+
+ it('uses Auto Interval when autoSelected', () => {
+ const state = makeState();
+ state.date.autoSelected = true;
+ const result = capturedMapState(state);
+ expect(result.increment).toBe('Auto Interval Between Frames');
+ });
+
+ it('uses configured imageDownload url', () => {
+ const state = makeState({
+ config: { features: { imageDownload: { url: 'https://snapshots.example' } }, parameters: {} },
+ });
+ expect(capturedMapState(state).url).toBe('https://snapshots.example');
+ });
+
+ it('redirects to parameters.imageDownload with a warning', () => {
+ const state = makeState({
+ config: { features: {}, parameters: { imageDownload: 'https://override.example' } },
+ });
+ expect(capturedMapState(state).url).toBe('https://override.example');
+ expect(util.warn).toHaveBeenCalledWith('Redirecting GIF download to: https://override.example');
+ });
+
+ it('getImageArrayFunc proxies to getImageArray with state', () => {
+ const state = makeState();
+ const result = capturedMapState(state);
+ const arr = result.getImageArrayFunc({ opt: 1 }, { width: 5, height: 5 });
+ expect(getImageArray).toHaveBeenCalledWith({ opt: 1 }, { width: 5, height: 5 }, state);
+ expect(arr).toEqual(['image1', 'image2']);
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ it('onBoundaryChange dispatches changeCropBounds', () => {
+ const dispatch = jest.fn();
+ const props = capturedMapDispatch(dispatch);
+ props.onBoundaryChange({ x: 9 });
+ expect(changeCropBounds).toHaveBeenCalledWith({ x: 9 });
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_CROP_BOUNDS', bounds: { x: 9 } });
+ });
});
diff --git a/web/js/containers/image-download.test.js b/web/js/containers/image-download.test.js
index 76c5b92a3..850391ccb 100644
--- a/web/js/containers/image-download.test.js
+++ b/web/js/containers/image-download.test.js
@@ -1,3 +1,253 @@
-test('image-download container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, act } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+let mockPanelProps = null;
+let mockCropProps = null;
+jest.mock('../components/image-download/image-download-panel', () => (props) => {
+ mockPanelProps = props;
+ return <div data-testid="image-download-panel" />;
+});
+jest.mock('../components/util/image-crop', () => (props) => {
+ mockCropProps = props;
+ return <div data-testid="crop" />;
+});
+
+jest.mock('./error-boundary', () => ({ children }) => <div>{children}</div>);
+
+jest.mock('ol/proj', () => ({
+ transform: jest.fn((coord) => coord),
+}));
+
+jest.mock('../modules/image-download/util', () => ({
+ getAlertMessageIfCrossesDateline: jest.fn(() => 'dateline-message'),
+ imageUtilCalculateResolution: jest.fn(() => '500m'),
+ imageUtilGetPixelValuesFromCoords: jest.fn(() => ({
+ x: 10, y: 20, x2: 110, y2: 120,
+ })),
+}));
+
+jest.mock('../util/util', () => ({
+ __esModule: true,
+ default: {
+ formatCoordinate: jest.fn((coord) => `fmt(${coord.join(',')})`),
+ },
+}));
+
+jest.mock('../modules/layers/selectors', () => ({
+ getLayers: jest.fn(() => ['layer1']),
+ subdailyLayersActive: jest.fn(() => false),
+}));
+
+jest.mock('../modules/date/selectors', () => ({
+ getSelectedDate: jest.fn(() => new Date('2021-01-01T00:00:00Z')),
+}));
+
+jest.mock('../modules/modal/actions', () => ({
+ onToggle: jest.fn(() => ({ type: 'MODAL_TOGGLE' })),
+}));
+
+jest.mock('../modules/image-download/actions', () => ({
+ onPanelChange: jest.fn((type, value) => ({ type: 'PANEL_CHANGE', panelType: type, value })),
+ updateBoundaries: jest.fn((obj) => ({ type: 'UPDATE_BOUNDARIES', obj })),
+}));
+
+jest.mock('../components/location-search/util', () => ({
+ getNormalizedCoordinate: jest.fn((coord) => coord),
+}));
+
+const ImageDownloadContainer = require('./image-download').default;
+const { getLayers: getLayersSelector } = require('../modules/layers/selectors');
+const { onToggle } = require('../modules/modal/actions');
+const {
+ onPanelChange: onPanelChangeAction,
+ updateBoundaries,
+} = require('../modules/image-download/actions');
+
+const makeMapUi = () => ({
+ selected: {
+ getCoordinateFromPixel: jest.fn(([x, y]) => [x / 10, y / 10]),
+ getView: jest.fn(() => ({
+ getZoom: jest.fn(() => 4),
+ calculateExtent: jest.fn(() => [0, 0, 100, 100]),
+ })),
+ getSize: jest.fn(() => [1024, 768]),
+ },
+});
+
+const defaultProps = {
+ closeModal: jest.fn(),
+ fileType: 'image/jpeg',
+ map: { ui: makeMapUi() },
+ onBoundaryChange: jest.fn(),
+ onPanelChange: jest.fn(),
+ proj: {
+ id: 'geographic',
+ selected: { crs: 'EPSG:4326', resolutions: [1, 2, 3] },
+ },
+ url: 'http://snapshot.test',
+ date: new Date('2021-01-01T00:00:00Z'),
+ getLayers: jest.fn(() => []),
+ hasSubdailyLayers: false,
+ isWorldfile: false,
+ markerCoordinates: [],
+ resolution: '250m',
+ screenHeight: 800,
+ screenWidth: 1200,
+ boundaries: null,
+};
+
+const renderComponent = (props = {}) => render(
+ <ImageDownloadContainer {...defaultProps} {...props} />,
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockPanelProps = null;
+ mockCropProps = null;
+});
+
+describe('ImageDownloadContainer render', () => {
+ it('renders panel and crop with default boundaries centered on screen', () => {
+ renderComponent();
+ expect(mockPanelProps).not.toBeNull();
+ expect(mockCropProps).not.toBeNull();
+ // default boundaries: x=500, y=300, x2=700, y2=500
+ expect(mockCropProps.x).toBe(500);
+ expect(mockCropProps.y).toBe(300);
+ expect(mockCropProps.width).toBe(200);
+ expect(mockCropProps.height).toBe(200);
+ expect(mockPanelProps.resolution).toBe('250m');
+ expect(mockPanelProps.datelineMessage).toBe('dateline-message');
+ });
+
+ it('uses provided boundaries when present', () => {
+ renderComponent({
+ boundaries: {
+ x: 1, y: 2, x2: 11, y2: 22,
+ },
+ });
+ expect(mockCropProps.x).toBe(1);
+ expect(mockCropProps.width).toBe(10);
+ });
+
+ it('calculates resolution when none is set', () => {
+ renderComponent({ resolution: null });
+ expect(mockPanelProps.resolution).toBe('500m');
+ });
+
+ it('uses polar file types and resolutions for non-geographic projections', () => {
+ renderComponent({
+ proj: { id: 'arctic', selected: { crs: 'EPSG:3413', resolutions: [1] } },
+ });
+ expect(mockPanelProps.fileTypes).toBeDefined();
+ expect(mockPanelProps.resolutions).toBeDefined();
+ });
+
+ it('onLatLongChange updates boundaries and calls debounced update', () => {
+ jest.useFakeTimers();
+ renderComponent();
+ act(() => {
+ mockPanelProps.onLatLongChange([0, 0, 10, 10]);
+ });
+ expect(mockCropProps.x).toBe(10);
+ expect(mockCropProps.y).toBe(20);
+ act(() => { jest.advanceTimersByTime(250); });
+ expect(defaultProps.onBoundaryChange).toHaveBeenCalledWith({
+ x: 10, y: 20, x2: 110, y2: 120,
+ });
+ jest.useRealTimers();
+ });
+
+ it('onBoundaryChange (crop) converts width/height and updates lat/long state', () => {
+ jest.useFakeTimers();
+ renderComponent();
+ act(() => {
+ mockCropProps.onChange({
+ x: 100, y: 200, width: 50, height: 60,
+ });
+ });
+ expect(mockCropProps.x).toBe(100);
+ expect(mockCropProps.width).toBe(50);
+ act(() => { jest.advanceTimersByTime(250); });
+ expect(defaultProps.onBoundaryChange).toHaveBeenCalledWith({
+ x: 100, y: 200, x2: 150, y2: 260,
+ });
+ jest.useRealTimers();
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (configFeatures = {}) => ({
+ config: { features: configFeatures },
+ proj: { id: 'geographic', selected: { crs: 'EPSG:4326' } },
+ screenSize: { screenWidth: 1440, screenHeight: 900 },
+ locationSearch: { coordinates: [5, 6] },
+ map: { ui: makeMapUi() },
+ imageDownload: {
+ isWorldfile: true,
+ fileType: 'image/png',
+ resolution: '1km',
+ boundaries: { x: 0, y: 0, x2: 5, y2: 5 },
+ },
+ });
+
+ it('maps image download state with the default snapshot URL', () => {
+ const result = capturedMapState(makeState());
+ expect(result.url).toBe('http://localhost:3002/api/v1/snapshot');
+ expect(result.isWorldfile).toBe(true);
+ expect(result.fileType).toBe('image/png');
+ expect(result.resolution).toBe('1km');
+ expect(result.screenWidth).toBe(1440);
+ expect(result.markerCoordinates).toEqual([5, 6]);
+ });
+
+ it('uses configured imageDownload URL when present', () => {
+ const result = capturedMapState(makeState({ imageDownload: { url: 'https://wvs.earthdata.nasa.gov/api/v1/snapshot' } }));
+ expect(result.url).toBe('https://wvs.earthdata.nasa.gov/api/v1/snapshot');
+ });
+
+ it('getLayers invokes the layers selector with reverse and renderable', () => {
+ const state = makeState();
+ const result = capturedMapState(state);
+ result.getLayers();
+ expect(getLayersSelector).toHaveBeenCalledWith(state, { reverse: true, renderable: true });
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('onClose dispatches modal toggle', () => {
+ props.onClose();
+ expect(onToggle).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'MODAL_TOGGLE' });
+ });
+
+ it('onPanelChange dispatches the panel change action', () => {
+ props.onPanelChange('fileType', 'image/png');
+ expect(onPanelChangeAction).toHaveBeenCalledWith('fileType', 'image/png');
+ });
+
+ it('onBoundaryChange dispatches updateBoundaries', () => {
+ const bounds = { x: 1 };
+ props.onBoundaryChange(bounds);
+ expect(updateBoundaries).toHaveBeenCalledWith(bounds);
+ });
});
diff --git a/web/js/containers/info.test.js b/web/js/containers/info.test.js
index 91915ff7d..61ceb1614 100644
--- a/web/js/containers/info.test.js
+++ b/web/js/containers/info.test.js
@@ -1,3 +1,305 @@
-test('info container test', () => {
+/* eslint-disable react/jsx-props-no-spreading */
+import { render } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+let capturedIconListProps;
+jest.mock('../components/util/icon-list', () => (props) => {
+ capturedIconListProps = props;
+ return <div data-testid="icon-list" />;
+});
+
+jest.mock('googleTagManager', () => ({
+ __esModule: true,
+ default: { pushEvent: jest.fn() },
+}));
+
+jest.mock('../modules/modal/actions', () => ({
+ openCustomContent: jest.fn((id, params) => ({ type: 'OPEN_CUSTOM_CONTENT', id, params })),
+ toggleAboutModal: jest.fn((isOpen) => ({ type: 'TOGGLE_ABOUT_MODAL', isOpen })),
+}));
+
+jest.mock('../modules/ui/actions', () => ({
+ __esModule: true,
+ default: jest.fn(() => ({ type: 'TOGGLE_DISTRACTION_FREE' })),
+}));
+
+jest.mock('../components/about/about', () => () => <div />);
+jest.mock('../components/global-settings/global-settings', () => () => <div />);
+jest.mock('./notifications', () => () => <div />);
+
+jest.mock('../modules/feedback/util', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+jest.mock('../modules/feedback/actions', () => ({
+ __esModule: true,
+ default: jest.fn(() => ({ type: 'INIT_FEEDBACK' })),
+}));
+
+jest.mock('../modules/tour/actions', () => ({
+ startTour: jest.fn(() => ({ type: 'START_TOUR' })),
+ endTour: jest.fn(() => ({ type: 'END_TOUR' })),
+}));
+
+jest.mock('../modules/notifications/actions', () => ({
+ notificationsSeen: jest.fn(() => ({ type: 'NOTIFICATIONS_SEEN' })),
+}));
+
+jest.mock('../modules/notifications/util', () => ({
+ addToLocalStorage: jest.fn(),
+}));
+
+const InfoList = require('./info').default;
+const googleTagManager = require('googleTagManager').default;
+const { openCustomContent, toggleAboutModal } = require('../modules/modal/actions');
+const onClickFeedback = require('../modules/feedback/util').default;
+const initFeedback = require('../modules/feedback/actions').default;
+const { startTour: startTourAction, endTour: endTourAction } = require('../modules/tour/actions');
+const { notificationsSeen } = require('../modules/notifications/actions');
+const { addToLocalStorage } = require('../modules/notifications/util');
+
+const defaultProps = {
+ sendFeedback: jest.fn(),
+ feedbackEnabled: false,
+ feedbackIsInitiated: false,
+ globalSettingsClick: jest.fn(),
+ aboutClick: jest.fn(),
+ config: { features: {}, stories: null, storyOrder: null },
+ startTour: jest.fn(),
+ isDistractionFreeModeActive: false,
+ isTourActive: false,
+ isMobile: false,
+ openAboutModal: jest.fn(),
+ toggleDistractionFreeMode: jest.fn(),
+ notifications: {
+ isActive: false, total: 0, numberUnseen: 0, type: '', object: {},
+ },
+ notificationClick: jest.fn(),
+};
+
+const renderComponent = (props = {}) => render(<InfoList {...defaultProps} {...props} />);
+
+const findItem = (id) => capturedIconListProps.list.find((item) => item.id === id);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ capturedIconListProps = null;
+});
+
+describe('InfoList list contents', () => {
+ it('renders base items: settings, about, source code, api, distraction free', () => {
+ renderComponent();
+ const ids = capturedIconListProps.list.map((item) => item.id);
+ expect(ids).toEqual([
+ 'settings_info_item',
+ 'about_info_item',
+ 'source_code_info_item',
+ 'api_access_info_item',
+ 'distraction_free_info_item',
+ ]);
+ expect(capturedIconListProps.size).toBe('small');
+ });
+
+ it('only shows the distraction free item in distraction free mode', () => {
+ renderComponent({ isDistractionFreeModeActive: true });
+ expect(capturedIconListProps.list).toHaveLength(1);
+ expect(capturedIconListProps.list[0].text).toBe('Exit Distraction Free');
+ });
+
+ it('adds a feedback entry with onClick when feedback is enabled on desktop', () => {
+ const sendFeedback = jest.fn();
+ renderComponent({ feedbackEnabled: true, sendFeedback });
+ const feedback = findItem('send_feedback_info_item');
+ expect(feedback.onClick).toBeDefined();
+ feedback.onClick();
+ expect(sendFeedback).toHaveBeenCalledWith(false, false);
+ });
+
+ it('uses a mailto href for feedback on mobile and large icon size', () => {
+ renderComponent({ feedbackEnabled: true, isMobile: true });
+ const feedback = findItem('send_feedback_info_item');
+ expect(feedback.href).toContain('mailto:');
+ expect(capturedIconListProps.size).toBe('large');
+ });
+
+ it('adds the explore tour item when tour features are configured', () => {
+ const startTour = jest.fn();
+ renderComponent({
+ startTour,
+ config: { features: { tour: true }, stories: {}, storyOrder: [] },
+ });
+ const tourItem = findItem('start_tour_info_item');
+ expect(tourItem).toBeDefined();
+ tourItem.onClick();
+ expect(startTour).toHaveBeenCalledWith(false);
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'tour_start_button' });
+ });
+
+ it('adds the notifications item when notifications are active', () => {
+ const notificationClick = jest.fn();
+ const notifications = {
+ isActive: true, total: 3, numberUnseen: 2, type: 'message', object: { foo: 1 },
+ };
+ renderComponent({ notifications, notificationClick });
+ const item = findItem('notifications_info_item');
+ expect(item.badge).toBe(2);
+ expect(item.iconName).toBe('gift');
+ expect(item.className).toBe('message-notification');
+ item.onClick();
+ expect(notificationClick).toHaveBeenCalledWith({ foo: 1 }, 2);
+ });
+
+ it('uses outage icon for outage notifications', () => {
+ renderComponent({
+ notifications: {
+ isActive: true, total: 1, numberUnseen: 1, type: 'outage', object: {},
+ },
+ });
+ expect(findItem('notifications_info_item').iconName).toBe('exclamation-circle');
+ });
+
+ it('uses bolt icon for alert notifications and zero badge with no type', () => {
+ renderComponent({
+ notifications: {
+ isActive: true, total: 1, numberUnseen: 1, type: 'alert', object: {},
+ },
+ });
+ expect(findItem('notifications_info_item').iconName).toEqual(['fas', 'bolt']);
+ });
+
+ it('settings item triggers globalSettingsClick', () => {
+ const globalSettingsClick = jest.fn();
+ renderComponent({ globalSettingsClick });
+ findItem('settings_info_item').onClick();
+ expect(globalSettingsClick).toHaveBeenCalled();
+ });
+
+ it('about item triggers aboutClick and openAboutModal', () => {
+ const aboutClick = jest.fn();
+ const openAboutModal = jest.fn();
+ renderComponent({ aboutClick, openAboutModal });
+ findItem('about_info_item').onClick();
+ expect(aboutClick).toHaveBeenCalled();
+ expect(openAboutModal).toHaveBeenCalled();
+ });
+
+ it('distraction free item toggles distraction free mode', () => {
+ const toggleDistractionFreeMode = jest.fn();
+ renderComponent({ toggleDistractionFreeMode });
+ findItem('distraction_free_info_item').onClick();
+ expect(toggleDistractionFreeMode).toHaveBeenCalled();
+ });
+});
+
+describe('mapStateToProps', () => {
+ it('maps state correctly', () => {
+ const state = {
+ ui: { isDistractionFreeModeActive: true },
+ feedback: { isInitiated: true },
+ tour: { active: true },
+ notifications: { isActive: true },
+ config: { features: { feedback: true } },
+ models: {},
+ screenSize: { isMobileDevice: true },
+ };
+ const result = capturedMapState(state);
+ expect(result.feedbackEnabled).toBe(true);
+ expect(result.feedbackIsInitiated).toBe(true);
+ expect(result.isDistractionFreeModeActive).toBe(true);
+ expect(result.isTourActive).toBe(true);
+ expect(result.isMobile).toBe(true);
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('toggleDistractionFreeMode dispatches the toggle action', () => {
+ props.toggleDistractionFreeMode();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_DISTRACTION_FREE' });
+ });
+
+ it('sendFeedback initiates feedback when not yet initiated', () => {
+ props.sendFeedback(false, true);
+ expect(onClickFeedback).toHaveBeenCalledWith(false, true);
+ expect(initFeedback).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'INIT_FEEDBACK' });
+ });
+
+ it('sendFeedback skips init when already initiated', () => {
+ props.sendFeedback(true, false);
+ expect(onClickFeedback).toHaveBeenCalledWith(true, false);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('notificationClick opens the notification modal and marks seen on close', () => {
+ props.notificationClick({ some: 'obj' }, 2);
+ expect(openCustomContent).toHaveBeenCalledWith('NOTIFICATION_LIST_MODAL', expect.objectContaining({
+ headerText: 'Notifications',
+ }));
+ const { onClose } = openCustomContent.mock.calls.at(-1)[1];
+ onClose();
+ expect(notificationsSeen).toHaveBeenCalled();
+ expect(addToLocalStorage).toHaveBeenCalledWith({ some: 'obj' });
+ });
+
+ it('notificationClick onClose does nothing when nothing unseen', () => {
+ props.notificationClick({ some: 'obj' }, 0);
+ const { onClose } = openCustomContent.mock.calls.at(-1)[1];
+ onClose();
+ expect(notificationsSeen).not.toHaveBeenCalled();
+ });
+
+ it('startTour dispatches startTour directly when tour is not active', () => {
+ props.startTour(false);
+ expect(startTourAction).toHaveBeenCalled();
+ expect(endTourAction).not.toHaveBeenCalled();
+ });
+
+ it('startTour restarts the tour when already active', () => {
+ jest.useFakeTimers();
+ props.startTour(true);
+ expect(endTourAction).toHaveBeenCalled();
+ jest.runAllTimers();
+ expect(startTourAction).toHaveBeenCalled();
+ jest.useRealTimers();
+ });
+
+ it('globalSettingsClick opens the global settings modal', () => {
+ props.globalSettingsClick();
+ expect(openCustomContent).toHaveBeenCalledWith('GLOBAL_SETTINGS_MODAL', expect.objectContaining({
+ headerText: 'Global Settings',
+ }));
+ });
+
+ it('aboutClick dispatches toggleAboutModal(true)', () => {
+ props.aboutClick();
+ expect(toggleAboutModal).toHaveBeenCalledWith(true);
+ });
+
+ it('openAboutModal opens the about modal and toggles off on close', () => {
+ props.openAboutModal();
+ expect(openCustomContent).toHaveBeenCalledWith('ABOUT_MODAL', expect.objectContaining({
+ headerText: 'About',
+ }));
+ const { onClose } = openCustomContent.mock.calls.at(-1)[1];
+ onClose();
+ expect(toggleAboutModal).toHaveBeenCalledWith(false);
+ });
});
diff --git a/web/js/containers/modal.test.js b/web/js/containers/modal.test.js
index 3226a0acc..a6c94094e 100644
--- a/web/js/containers/modal.test.js
+++ b/web/js/containers/modal.test.js
@@ -1,3 +1,431 @@
-test('modal container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, act, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+let mockModalProps = null;
+jest.mock('reactstrap', () => ({
+ Modal: (props) => {
+ mockModalProps = props;
+ return (
+ <div data-testid="modal" id={props.id} className={props.className}>
+ {props.children}
+ </div>
+ );
+ },
+ ModalBody: ({ children }) => <div data-testid="modal-body">{children}</div>,
+ ModalHeader: (props) => (
+ <div data-testid="modal-header">
+ {props.children}
+ {props.close}
+ </div>
+ ),
+ ModalFooter: () => <div data-testid="modal-footer" />,
+}));
+
+let mockResizableProps = null;
+jest.mock('react-resizable', () => ({
+ Resizable: (props) => {
+ mockResizableProps = props;
+ return <div data-testid="resizable">{props.children}</div>;
+ },
+}));
+
+jest.mock('../components/util/detect-outer-click', () => (props) => (
+ <div data-testid="detect-outer-click">{props.children}</div>
+));
+
+jest.mock('./error-boundary', () => ({ children }) => <div>{children}</div>);
+
+jest.mock('../util/customHooks', () => {
+ const { useRef, useEffect } = require('react');
+ return (val) => {
+ const ref = useRef();
+ useEffect(() => {
+ ref.current = val;
+ });
+ return ref.current;
+ };
+});
+
+jest.mock('../modules/modal/actions', () => ({
+ onToggle: jest.fn(() => ({ type: 'MODAL_TOGGLE' })),
+}));
+
+const ModalContainer = require('./modal').default;
+const { onToggle: onToggleAction } = require('../modules/modal/actions');
+
+const defaultProps = {
+ isCustom: false,
+ id: 'TEST_MODAL',
+ isOpen: true,
+ customProps: {},
+ isMobile: false,
+ screenHeight: 800,
+ screenWidth: 1200,
+ isEmbedModeActive: false,
+ isTemplateModal: false,
+ bodyText: 'modal body text',
+ headerText: 'Test Header',
+ onToggle: jest.fn(),
+};
+
+const renderComponent = (props = {}) => render(
+ <ModalContainer {...defaultProps} {...props} />,
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockModalProps = null;
+ mockResizableProps = null;
+});
+
+describe('ModalContainer basic rendering', () => {
+ it('renders header and body text', () => {
+ const { getByText, getByTestId } = renderComponent();
+ expect(getByTestId('modal-header')).toHaveTextContent('Test Header');
+ expect(getByText('modal body text')).toBeInTheDocument();
+ expect(mockModalProps.id).toBe('test_modal');
+ expect(mockModalProps.className).toBe('default-modal');
+ });
+
+ it('toggle includes onClose when modal is open', () => {
+ const onToggle = jest.fn();
+ const onClose = jest.fn();
+ const { container } = renderComponent({ onToggle, onClose });
+ fireEvent.click(container.querySelector('.modal-close-btn'));
+ expect(onToggle).toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('uses plain onToggle when modal is closed', () => {
+ const onToggle = jest.fn();
+ const onClose = jest.fn();
+ renderComponent({ onToggle, onClose, isOpen: false });
+ expect(mockModalProps.toggle).toBe(onToggle);
+ });
+
+ it('merges customProps when isCustom and id are set', () => {
+ const { getByText } = renderComponent({
+ isCustom: true,
+ customProps: { bodyText: 'custom body', headerText: 'Custom Header' },
+ });
+ expect(getByText('custom body')).toBeInTheDocument();
+ });
+
+ it('renders a body component with closeModal and parentId', () => {
+ let receivedProps = null;
+ function Body(props) {
+ receivedProps = props;
+ return <div>body component</div>;
+ }
+ const { getByText } = renderComponent({
+ isCustom: true,
+ customProps: { bodyComponent: Body, bodyComponentProps: { extra: 7 } },
+ });
+ expect(getByText('body component')).toBeInTheDocument();
+ expect(receivedProps.parentId).toBe('TEST_MODAL');
+ expect(receivedProps.extra).toBe(7);
+ expect(receivedProps.screenHeight).toBe(800);
+ });
+
+ it('renders bodyHeader when provided', () => {
+ const { getByText } = renderComponent({
+ isCustom: true,
+ customProps: { bodyHeader: 'A Header' },
+ });
+ expect(getByText('A Header')).toBeInTheDocument();
+ });
+
+ it('renders footer when provided', () => {
+ const { getByTestId } = renderComponent({
+ isCustom: true,
+ customProps: { footer: true },
+ });
+ expect(getByTestId('modal-footer')).toBeInTheDocument();
+ });
+
+ it('renders a CompletelyCustomModal with toggleWithClose', () => {
+ let receivedProps = null;
+ function CustomModal(props) {
+ receivedProps = props;
+ return <div>completely custom</div>;
+ }
+ const { getByText } = renderComponent({
+ isCustom: true,
+ customProps: { CompletelyCustomModal: CustomModal, dialogKey: 3 },
+ });
+ expect(getByText('completely custom')).toBeInTheDocument();
+ expect(receivedProps.toggleWithClose).toBeDefined();
+ });
+});
+
+describe('restricted display', () => {
+ it('returns null for desktopOnly modals on mobile', () => {
+ const { container } = renderComponent({ isMobile: true, desktopOnly: true });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('returns null for mobileOnly modals on desktop', () => {
+ const { container } = renderComponent({
+ isCustom: true,
+ customProps: { mobileOnly: true },
+ });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('returns null for large modals in embed mode', () => {
+ const { container } = renderComponent({
+ isEmbedModeActive: true,
+ isCustom: true,
+ customProps: { size: 'lg' },
+ });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders LAYER_INFO_MODAL even in embed mode', () => {
+ const { queryByTestId } = renderComponent({
+ id: 'LAYER_INFO_MODAL',
+ isEmbedModeActive: true,
+ isCustom: true,
+ customProps: { size: 'lg' },
+ });
+ expect(queryByTestId('modal')).toBeInTheDocument();
+ });
+
+ it('calls toggle for desktopOnly modal opened on mobile', () => {
+ const onToggle = jest.fn();
+ renderComponent({ isMobile: true, desktopOnly: true, onToggle });
+ expect(onToggle).toHaveBeenCalled();
+ });
+});
+
+describe('template modals', () => {
+ it('renders loading text while the template loads', () => {
+ const { getByText } = renderComponent({
+ isTemplateModal: true,
+ bodyTemplate: { isLoading: true },
+ });
+ expect(getByText('Loading')).toBeInTheDocument();
+ expect(mockModalProps.className).toBe('template-modal');
+ });
+
+ it('renders template html content when loaded', () => {
+ const { container } = renderComponent({
+ isTemplateModal: true,
+ bodyTemplate: { isLoading: false, response: '<b>tpl-content</b>' },
+ });
+ expect(container.querySelector('#template-content').innerHTML).toBe('<b>tpl-content</b>');
+ });
+});
+
+describe('resizing and styles', () => {
+ it('wraps children in Resizable when isResizable', () => {
+ const { getByTestId } = renderComponent({
+ isCustom: true,
+ customProps: { isResizable: true, width: 400, height: 500 },
+ });
+ expect(getByTestId('resizable')).toBeInTheDocument();
+ expect(mockResizableProps.width).toBe(400);
+ });
+
+ it('onResize updates modal width and height style', () => {
+ renderComponent({
+ isCustom: true,
+ customProps: { isResizable: true, width: 400, height: 500 },
+ });
+ act(() => {
+ mockResizableProps.onResize(
+ { stopPropagation: jest.fn() },
+ { size: { width: 321, height: 432 } },
+ );
+ });
+ expect(mockModalProps.style.width).toBe(321);
+ expect(mockModalProps.style.height).toBe(432);
+ });
+
+ it('applies mobile fullscreen top offset', () => {
+ renderComponent({
+ isMobile: true,
+ isCustom: true,
+ customProps: { mobileFullScreen: true },
+ });
+ expect(mockModalProps.style.top).toBe(106);
+ expect(mockModalProps.style.margin).toBe(0);
+ // landscape resize applied via effect (screenHeight < screenWidth)
+ expect(mockModalProps.style.width).toBe(445);
+ expect(mockModalProps.style.height).toBe(300);
+ });
+
+ it('applies portrait fullscreen sizing when height exceeds width', () => {
+ renderComponent({
+ isMobile: true,
+ isCustom: true,
+ screenHeight: 900,
+ screenWidth: 400,
+ customProps: { mobileFullScreen: true },
+ });
+ expect(mockModalProps.style.width).toBe(400);
+ expect(mockModalProps.style.height).toBe(794);
+ });
+
+ it('uses offset props for style on desktop', () => {
+ renderComponent({
+ isCustom: true,
+ customProps: { offsetLeft: 11, offsetTop: 22, offsetRight: 33 },
+ });
+ expect(mockModalProps.style.left).toBe(11);
+ expect(mockModalProps.style.top).toBe(22);
+ expect(mockModalProps.style.right).toBe(33);
+ expect(mockModalProps.style.margin).toBe('0.5rem auto');
+ });
+});
+
+describe('dragging', () => {
+ const dragProps = {
+ isCustom: true,
+ customProps: {
+ isDraggable: true,
+ dragHandle: '.drag-handle',
+ offsetLeft: 100,
+ offsetTop: 100,
+ width: 300,
+ height: 200,
+ bodyComponent: () => (
+ <div className="drag-handle">
+ <span data-testid="drag-target">drag me</span>
+ </div>
+ ),
+ },
+ };
+
+ it('moves the modal on drag', () => {
+ const { getByTestId } = renderComponent(dragProps);
+ const target = getByTestId('drag-target');
+ act(() => {
+ fireEvent.mouseDown(target, { button: 0, clientX: 10, clientY: 10 });
+ });
+ act(() => {
+ fireEvent.mouseMove(window, { clientX: 60, clientY: 40 });
+ });
+ expect(mockModalProps.style.left).toBe(150);
+ expect(mockModalProps.style.top).toBe(130);
+ act(() => {
+ fireEvent.mouseUp(window);
+ });
+ // after mouseup further movement is ignored
+ act(() => {
+ fireEvent.mouseMove(window, { clientX: 600, clientY: 400 });
+ });
+ expect(mockModalProps.style.left).toBe(150);
+ });
+
+ it('clamps movement onscreen when stayOnscreen is set', () => {
+ const { getByTestId } = renderComponent({
+ ...dragProps,
+ customProps: { ...dragProps.customProps, stayOnscreen: true },
+ });
+ const target = getByTestId('drag-target');
+ act(() => {
+ fireEvent.mouseDown(target, { button: 0, clientX: 0, clientY: 0 });
+ });
+ act(() => {
+ fireEvent.mouseMove(window, { clientX: 5000, clientY: 5000 });
+ });
+ // maxLeft = 1200-300, maxTop = 800-200
+ expect(mockModalProps.style.left).toBe(900);
+ expect(mockModalProps.style.top).toBe(600);
+ });
+
+ it('ignores non-left-button mousedown', () => {
+ const { getByTestId } = renderComponent(dragProps);
+ act(() => {
+ fireEvent.mouseDown(getByTestId('drag-target'), { button: 2, clientX: 10, clientY: 10 });
+ });
+ act(() => {
+ fireEvent.mouseMove(window, { clientX: 60, clientY: 40 });
+ });
+ expect(mockModalProps.style.left).toBe(100);
+ });
+
+ it('ignores mousedown outside the drag handle', () => {
+ const { getByTestId } = renderComponent({
+ ...dragProps,
+ customProps: {
+ ...dragProps.customProps,
+ bodyComponent: () => <span data-testid="outside-target">outside</span>,
+ },
+ });
+ act(() => {
+ fireEvent.mouseDown(getByTestId('outside-target'), { button: 0, clientX: 10, clientY: 10 });
+ });
+ act(() => {
+ fireEvent.mouseMove(window, { clientX: 60, clientY: 40 });
+ });
+ expect(mockModalProps.style.left).toBe(100);
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (modalOverrides = {}) => ({
+ embed: { isEmbedModeActive: true },
+ modal: {
+ bodyText: 'text',
+ headerText: 'header',
+ isCustom: true,
+ id: 'SOME_MODAL',
+ isOpen: true,
+ template: null,
+ customProps: { a: 1 },
+ ...modalOverrides,
+ },
+ screenSize: {
+ screenHeight: 700,
+ screenWidth: 1000,
+ orientation: 'landscape',
+ isMobileDevice: true,
+ },
+ });
+
+ it('maps modal state', () => {
+ const result = capturedMapState(makeState());
+ expect(result.bodyText).toBe('text');
+ expect(result.headerText).toBe('header');
+ expect(result.isCustom).toBe(true);
+ expect(result.id).toBe('SOME_MODAL');
+ expect(result.isOpen).toBe(true);
+ expect(result.isTemplateModal).toBe(false);
+ expect(result.bodyTemplate).toBeUndefined();
+ expect(result.isMobile).toBe(true);
+ expect(result.isEmbedModeActive).toBe(true);
+ expect(result.screenHeight).toBe(700);
+ });
+
+ it('resolves template state when modal has a template', () => {
+ const state = makeState({ template: 'someTemplate' });
+ state.someTemplate = { isLoading: false, response: 'tpl' };
+ const result = capturedMapState(state);
+ expect(result.isTemplateModal).toBe(true);
+ expect(result.bodyTemplate).toEqual({ isLoading: false, response: 'tpl' });
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ it('onToggle dispatches the modal toggle action', () => {
+ const dispatch = jest.fn();
+ const props = capturedMapDispatch(dispatch);
+ props.onToggle();
+ expect(onToggleAction).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'MODAL_TOGGLE' });
+ });
});
diff --git a/web/js/containers/notifications.test.js b/web/js/containers/notifications.test.js
index f4aa103f0..911a7b02d 100644
--- a/web/js/containers/notifications.test.js
+++ b/web/js/containers/notifications.test.js
@@ -1,3 +1,96 @@
-test('notifications container test', () => {
+/* eslint-disable react/prop-types */
+import { render } from '@testing-library/react';
+import '@testing-library/jest-dom';
+
+let capturedMapState;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ return (Component) => Component;
+ },
+}));
+
+const capturedBlocks = [];
+jest.mock('../components/notifications/notification-block', () => (props) => {
+ capturedBlocks.push(props);
+ return <div data-testid={`block-${props.type}`} />;
+});
+
+jest.mock('../modules/notifications/util', () => ({
+ getNumberOfTypeNotSeen: jest.fn(() => 2),
+}));
+
+const Notifications = require('./notifications').default;
+const { getNumberOfTypeNotSeen } = require('../modules/notifications/util');
+
+const object = {
+ messages: [{ id: 1 }],
+ outages: [{ id: 2 }],
+ alerts: [{ id: 3 }],
+};
+
+beforeEach(() => {
+ capturedBlocks.length = 0;
+ jest.clearAllMocks();
+ getNumberOfTypeNotSeen.mockReturnValue(2);
+});
+
+describe('Notifications render', () => {
+ it('renders only the outage block when there are unseen outages outside kiosk mode', () => {
+ const { getByTestId, queryByTestId } = render(
+ <Notifications kioskModeEnabled={false} numberOutagesUnseen={3} object={object} />,
+ );
+ expect(getByTestId('block-outage')).toBeInTheDocument();
+ expect(queryByTestId('block-alert')).toBeNull();
+ expect(queryByTestId('block-message')).toBeNull();
+ expect(capturedBlocks[0].arr).toBe(object.outages);
+ expect(capturedBlocks[0].numberNotSeen).toBe(2);
+ });
+
+ it('renders all three blocks when no unseen outages', () => {
+ const { getByTestId } = render(
+ <Notifications kioskModeEnabled={false} numberOutagesUnseen={0} object={object} />,
+ );
+ expect(getByTestId('block-outage')).toBeInTheDocument();
+ expect(getByTestId('block-alert')).toBeInTheDocument();
+ expect(getByTestId('block-message')).toBeInTheDocument();
+ expect(getNumberOfTypeNotSeen).toHaveBeenCalledWith('outage', object.outages);
+ expect(getNumberOfTypeNotSeen).toHaveBeenCalledWith('alert', object.alerts);
+ expect(getNumberOfTypeNotSeen).toHaveBeenCalledWith('message', object.messages);
+ });
+
+ it('renders all three blocks in kiosk mode even with unseen outages', () => {
+ const { getByTestId } = render(
+ <Notifications kioskModeEnabled numberOutagesUnseen={3} object={object} />,
+ );
+ expect(getByTestId('block-alert')).toBeInTheDocument();
+ expect(getByTestId('block-message')).toBeInTheDocument();
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (uiOverrides = {}) => ({
+ notifications: { object, numberOutagesUnseen: 5 },
+ ui: { eic: null, isKioskModeActive: false, ...uiOverrides },
+ });
+
+ it('maps notifications state', () => {
+ const result = capturedMapState(makeState());
+ expect(result.object).toBe(object);
+ expect(result.numberOutagesUnseen).toBe(5);
+ expect(result.kioskModeEnabled).toBe(false);
+ });
+
+ it('enables kiosk mode when eic is set', () => {
+ expect(capturedMapState(makeState({ eic: 'da' })).kioskModeEnabled).toBe(true);
+ });
+
+ it('keeps kiosk mode off when eic is an empty string', () => {
+ expect(capturedMapState(makeState({ eic: '' })).kioskModeEnabled).toBe(false);
+ });
+
+ it('enables kiosk mode when isKioskModeActive is true', () => {
+ expect(capturedMapState(makeState({ isKioskModeActive: true })).kioskModeEnabled).toBe(true);
+ });
});
diff --git a/web/js/containers/projection.test.js b/web/js/containers/projection.test.js
index 3b88c81c8..b5fb65753 100644
--- a/web/js/containers/projection.test.js
+++ b/web/js/containers/projection.test.js
@@ -1,3 +1,188 @@
-test('projection container test', () => {
+/* eslint-disable react/jsx-props-no-spreading */
+import { render } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+let capturedIconListProps;
+jest.mock('../components/util/icon-list', () => (props) => {
+ capturedIconListProps = props;
+ return <div data-testid="icon-list" />;
+});
+
+jest.mock('googleTagManager', () => ({
+ __esModule: true,
+ default: { pushEvent: jest.fn() },
+}));
+
+jest.mock('../modules/projection/actions', () => ({
+ __esModule: true,
+ default: jest.fn((id) => ({ type: 'CHANGE_PROJECTION', id })),
+}));
+
+jest.mock('../modules/modal/actions', () => ({
+ onToggle: jest.fn(() => ({ type: 'MODAL_TOGGLE' })),
+}));
+
+jest.mock('../modules/date/actions', () => ({
+ changeTimeScale: jest.fn((val) => ({ type: 'CHANGE_TIME_SCALE', val })),
+ selectInterval: jest.fn(() => ({ type: 'SELECT_INTERVAL' })),
+ changeAutoInterval: jest.fn((val) => ({ type: 'CHANGE_AUTO_INTERVAL', val })),
+}));
+
+const ProjectionList = require('./projection').default;
+const googleTagManager = require('googleTagManager').default;
+const changeProjection = require('../modules/projection/actions').default;
+const { onToggle } = require('../modules/modal/actions');
+const {
+ changeTimeScale: changeTimeScaleAction,
+ changeAutoInterval: changeAutoIntervalAction,
+} = require('../modules/date/actions');
+
+const defaultProps = {
+ projection: 'geographic',
+ projectionArray: [],
+ isMobile: false,
+ layers: [],
+ updateProjection: jest.fn(),
+ onCloseModal: jest.fn(),
+ changeTimeScale: jest.fn(),
+ changeAutoInterval: jest.fn(),
+};
+
+const renderComponent = (props = {}) => render(
+ <ProjectionList {...defaultProps} {...props} />,
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ capturedIconListProps = null;
+});
+
+describe('ProjectionList component', () => {
+ it('renders IconList with small size on desktop', () => {
+ renderComponent();
+ expect(capturedIconListProps.size).toBe('small');
+ expect(capturedIconListProps.active).toBe('geographic');
+ });
+
+ it('renders IconList with large size on mobile', () => {
+ renderComponent({ isMobile: true });
+ expect(capturedIconListProps.size).toBe('large');
+ });
+
+ it('only closes the modal when the same projection is clicked', () => {
+ const updateProjection = jest.fn();
+ const onCloseModal = jest.fn();
+ renderComponent({ updateProjection, onCloseModal });
+ capturedIconListProps.onClick('geographic');
+ expect(updateProjection).not.toHaveBeenCalled();
+ expect(onCloseModal).toHaveBeenCalled();
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'change_projection',
+ projection: 'geographic',
+ });
+ });
+
+ it('updates projection with daily defaults when no TEMPO layers exist', () => {
+ const updateProjection = jest.fn();
+ const changeTimeScale = jest.fn();
+ const changeAutoInterval = jest.fn();
+ renderComponent({ updateProjection, changeTimeScale, changeAutoInterval });
+ capturedIconListProps.onClick('arctic');
+ expect(updateProjection).toHaveBeenCalledWith('arctic');
+ expect(changeAutoInterval).toHaveBeenCalledWith(false);
+ expect(changeTimeScale).toHaveBeenCalledWith(3);
+ });
+
+ it('enables auto interval when visible TEMPO layers support the projection', () => {
+ const changeTimeScale = jest.fn();
+ const changeAutoInterval = jest.fn();
+ const layers = [{
+ id: 'TEMPO_NO2',
+ visible: true,
+ projections: { geographic: {} },
+ }];
+ renderComponent({
+ projection: 'arctic', layers, changeTimeScale, changeAutoInterval,
+ });
+ capturedIconListProps.onClick('geographic');
+ expect(changeAutoInterval).toHaveBeenCalledWith(true);
+ expect(changeTimeScale).toHaveBeenCalledWith(4);
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (config = {}) => ({
+ config,
+ models: { foo: 'bar' },
+ proj: { id: 'arctic' },
+ screenSize: { isMobileDevice: true },
+ layers: { active: { layers: [{ id: 'x' }] } },
+ });
+
+ it('uses the default projection array when config has none', () => {
+ const result = capturedMapState(makeState());
+ expect(result.projectionArray).toHaveLength(3);
+ expect(result.projectionArray[0].key).toBe('arctic');
+ expect(result.projection).toBe('arctic');
+ expect(result.isMobile).toBe(true);
+ expect(result.layers).toEqual([{ id: 'x' }]);
+ });
+
+ it('builds the projection array from config.ui.projections', () => {
+ const config = {
+ ui: {
+ projections: [
+ { name: 'Custom', style: 'star', id: 'custom' },
+ ],
+ },
+ };
+ const result = capturedMapState(makeState(config));
+ expect(result.projectionArray).toEqual([{
+ text: 'Custom',
+ iconClass: ' ui-icon icon-large',
+ iconName: 'star',
+ id: 'change-custom-button',
+ key: 'custom',
+ }]);
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('updateProjection dispatches changeProjection', () => {
+ props.updateProjection('antarctic');
+ expect(changeProjection).toHaveBeenCalledWith('antarctic');
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_PROJECTION', id: 'antarctic' });
+ });
+
+ it('onCloseModal dispatches onToggle', () => {
+ props.onCloseModal();
+ expect(onToggle).toHaveBeenCalled();
+ });
+
+ it('changeTimeScale dispatches the time scale action', () => {
+ props.changeTimeScale(3);
+ expect(changeTimeScaleAction).toHaveBeenCalledWith(3);
+ });
+
+ it('changeAutoInterval dispatches the auto interval action', () => {
+ props.changeAutoInterval(true);
+ expect(changeAutoIntervalAction).toHaveBeenCalledWith(true);
+ });
});
diff --git a/web/js/containers/share.test.js b/web/js/containers/share.test.js
index bbfaeb028..b356ccd94 100644
--- a/web/js/containers/share.test.js
+++ b/web/js/containers/share.test.js
@@ -1,3 +1,354 @@
-test('share container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import {
+ render, fireEvent, act, waitFor,
+} from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+jest.mock('copy-to-clipboard', () => ({
+ __esModule: true,
+ default: jest.fn(() => Promise.resolve()),
+}));
+
+jest.mock('googleTagManager', () => ({
+ __esModule: true,
+ default: { pushEvent: jest.fn() },
+}));
+
+jest.mock('../components/toolbar/share/tooltips', () => () => <div data-testid="share-tooltips" />);
+jest.mock('../components/util/hover-tooltip', () => () => <span data-testid="hover-tooltip" />);
+
+let mockCheckboxProps = null;
+jest.mock('../components/util/checkbox', () => (props) => {
+ mockCheckboxProps = props;
+ return <div data-testid="shorten-checkbox" data-checked={props.checked} />;
+});
+
+jest.mock('../modules/link/util', () => ({
+ getPermalink: jest.fn((qs, date, isEmbed) => `permalink:${qs}:${isEmbed ? 'embed' : 'std'}`),
+ wrapWithIframe: jest.fn((url) => `<iframe src="${url}"></iframe>`),
+}));
+
+jest.mock('../modules/feedback/util', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+jest.mock('../modules/feedback/actions', () => ({
+ __esModule: true,
+ default: jest.fn(() => ({ type: 'INIT_FEEDBACK' })),
+}));
+
+jest.mock('../modules/date/selectors', () => ({
+ getSelectedDate: jest.fn(() => new Date('2021-01-01T00:00:00Z')),
+}));
+
+jest.mock('../modules/link/actions', () => ({
+ requestShortLink: jest.fn((location, type, signal, options) => ({
+ type: 'REQUEST_SHORT_LINK', location, contentType: type, options,
+ })),
+}));
+
+const mockUnlisten = jest.fn();
+const mockHistory = {
+ location: { search: '?p=geographic' },
+ listen: jest.fn(() => mockUnlisten),
+};
+jest.mock('../main', () => ({
+ __esModule: true,
+ default: mockHistory,
+}));
+
+const ShareLinkContainer = require('./share').default;
+const copy = require('copy-to-clipboard').default;
+const googleTagManager = require('googleTagManager').default;
+const { getPermalink, wrapWithIframe } = require('../modules/link/util');
+const onClickFeedback = require('../modules/feedback/util').default;
+const initFeedback = require('../modules/feedback/actions').default;
+const { requestShortLink } = require('../modules/link/actions');
+
+const defaultProps = {
+ embedDisableNavLink: false,
+ feedbackIsInitiated: false,
+ feedbackEnabled: true,
+ isMobile: false,
+ mock: '',
+ requestShortLinkAction: jest.fn(() => Promise.resolve()),
+ selectedDate: new Date('2021-01-01T00:00:00Z'),
+ sendFeedback: jest.fn(),
+ shortLink: { isLoading: false, response: false, error: false },
+ urlShortening: true,
+};
+
+const renderComponent = (props = {}) => render(
+ <ShareLinkContainer {...defaultProps} {...props} />,
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockCheckboxProps = null;
+ mockHistory.location = { search: '?p=geographic' };
+});
+
+describe('ShareLinkContainer tabs', () => {
+ it('renders three tabs on desktop', () => {
+ const { container } = renderComponent();
+ const navLinks = container.querySelectorAll('.nav-link');
+ expect(navLinks).toHaveLength(3);
+ expect(navLinks[0].textContent).toBe('Link');
+ expect(navLinks[1].textContent).toBe('Embed');
+ expect(navLinks[2].textContent).toBe('Cite Us');
+ });
+
+ it('renders only link and cite-us tabs on mobile', () => {
+ const { container } = renderComponent({ isMobile: true });
+ const navLinks = container.querySelectorAll('.nav-link');
+ expect(navLinks).toHaveLength(2);
+ });
+
+ it('disables the embed tab with a tooltip when embedDisableNavLink is set', () => {
+ const { container, getAllByTestId } = renderComponent({ embedDisableNavLink: true });
+ const embedLink = container.querySelector('.embed-share-nav .nav-link');
+ expect(embedLink.classList.contains('disabled')).toBe(true);
+ expect(getAllByTestId('hover-tooltip').length).toBeGreaterThan(0);
+ });
+
+ it('switches to the embed tab and renders iframe code', () => {
+ const { container } = renderComponent();
+ fireEvent.click(container.querySelectorAll('.nav-link')[1]);
+ expect(wrapWithIframe).toHaveBeenCalledWith('permalink:?p=geographic:embed');
+ const input = container.querySelector('#permalink-content-embed');
+ expect(input.value).toContain('<iframe');
+ expect(container.querySelector('.share-body').classList.contains('tall')).toBe(true);
+ });
+
+ it('switches to cite-us tab and renders the citation textarea', () => {
+ const { container } = renderComponent();
+ fireEvent.click(container.querySelectorAll('.nav-link')[2]);
+ const textarea = container.querySelector('textarea#permalink-content-cite-us');
+ expect(textarea.value).toContain('NASA Worldview application');
+ });
+});
+
+describe('link tab behavior', () => {
+ it('shows the permalink in the input', () => {
+ const { container } = renderComponent();
+ expect(container.querySelector('#permalink-content-link').value)
+ .toBe('permalink:?p=geographic:std');
+ });
+
+ it('copies the link to the clipboard and records the event', async () => {
+ const { container } = renderComponent();
+ fireEvent.click(container.querySelector('#copy-to-clipboard-button-link'));
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'share_link_copy',
+ link_type: 'link',
+ });
+ expect(copy).toHaveBeenCalledWith('permalink:?p=geographic:std', { format: 'text/plain' });
+ await act(async () => {});
+ });
+
+ it('shortens the link via the checkbox and shows the short link', async () => {
+ const requestShortLinkAction = jest.fn(() => Promise.resolve());
+ const { container } = renderComponent({
+ requestShortLinkAction,
+ shortLink: { isLoading: false, response: { link: 'https://go.nasa.gov/x' }, error: false },
+ });
+ await act(async () => {
+ mockCheckboxProps.onCheck();
+ });
+ expect(requestShortLinkAction).toHaveBeenCalledWith('mock/short_link.json');
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'share_link_shorten' });
+ expect(container.querySelector('#permalink-content-link').value).toBe('https://go.nasa.gov/x');
+ // unchecking flips back without re-requesting
+ await act(async () => {
+ mockCheckboxProps.onCheck();
+ });
+ expect(requestShortLinkAction).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('#permalink-content-link').value)
+ .toBe('permalink:?p=geographic:std');
+ });
+
+ it('shows "Please wait..." while the short link is loading', async () => {
+ const { container } = renderComponent({
+ shortLink: { isLoading: true, response: false, error: false },
+ });
+ await act(async () => {
+ mockCheckboxProps.onCheck();
+ });
+ expect(container.querySelector('#permalink-content-link').value).toBe('Please wait...');
+ });
+
+ it('resets isShort when the short link request errors', async () => {
+ const { container, rerender } = renderComponent({
+ shortLink: { isLoading: false, response: { link: 'short' }, error: false },
+ });
+ await act(async () => {
+ mockCheckboxProps.onCheck();
+ });
+ expect(container.querySelector('#permalink-content-link').value).toBe('short');
+ act(() => {
+ rerender(
+ <ShareLinkContainer
+ {...defaultProps}
+ shortLink={{ isLoading: false, response: false, error: true }}
+ />,
+ );
+ });
+ expect(container.querySelector('#permalink-content-link').value)
+ .toBe('permalink:?p=geographic:std');
+ });
+});
+
+describe('history listener', () => {
+ it('updates the query string when history location changes', async () => {
+ const { container } = renderComponent();
+ expect(mockHistory.listen).toHaveBeenCalled();
+ const listener = mockHistory.listen.mock.calls[0][0];
+ mockHistory.location = { search: '?p=arctic' };
+ act(() => {
+ listener({ search: '?p=arctic' }, 'PUSH');
+ });
+ await waitFor(() => {
+ expect(container.querySelector('#permalink-content-link').value)
+ .toBe('permalink:?p=arctic:std');
+ });
+ });
+
+ it('ignores listener updates with undefined search', () => {
+ const { container } = renderComponent();
+ const listener = mockHistory.listen.mock.calls[0][0];
+ act(() => {
+ listener({ search: undefined }, 'PUSH');
+ });
+ expect(container.querySelector('#permalink-content-link').value)
+ .toBe('permalink:?p=geographic:std');
+ });
+
+ it('unsubscribes from history on unmount', () => {
+ const { unmount } = renderComponent();
+ unmount();
+ expect(mockUnlisten).toHaveBeenCalled();
+ });
+});
+
+describe('embed tab feedback link', () => {
+ it('opens feedback on click when feedback is enabled', () => {
+ const sendFeedback = jest.fn();
+ const { container } = renderComponent({ sendFeedback });
+ fireEvent.click(container.querySelectorAll('.nav-link')[1]);
+ fireEvent.click(container.querySelector('#feedback-url'));
+ expect(sendFeedback).toHaveBeenCalledWith(false, false);
+ });
+
+ it('does not open feedback when feedback is disabled', () => {
+ const sendFeedback = jest.fn();
+ const { container } = renderComponent({ sendFeedback, feedbackEnabled: false });
+ fireEvent.click(container.querySelectorAll('.nav-link')[1]);
+ fireEvent.click(container.querySelector('#feedback-url'));
+ expect(sendFeedback).not.toHaveBeenCalled();
+ });
+
+ it('opens feedback via Enter key', () => {
+ const sendFeedback = jest.fn();
+ const { container } = renderComponent({ sendFeedback });
+ fireEvent.click(container.querySelectorAll('.nav-link')[1]);
+ fireEvent.keyDown(container.querySelector('#feedback-url'), { key: 'Enter' });
+ expect(sendFeedback).toHaveBeenCalled();
+ });
+
+ it('ignores other keys', () => {
+ const sendFeedback = jest.fn();
+ const { container } = renderComponent({ sendFeedback });
+ fireEvent.click(container.querySelectorAll('.nav-link')[1]);
+ fireEvent.keyDown(container.querySelector('#feedback-url'), { key: 'a' });
+ expect(sendFeedback).not.toHaveBeenCalled();
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (overrides = {}) => ({
+ screenSize: { isMobileDevice: false },
+ config: {
+ features: { urlShortening: true, feedback: true },
+ parameters: {},
+ },
+ shortLink: { isLoading: false },
+ sidebar: { activeTab: 'layers' },
+ tour: { active: false },
+ feedback: { isInitiated: true },
+ ...overrides,
+ });
+
+ it('maps share state', () => {
+ const result = capturedMapState(makeState());
+ expect(result.urlShortening).toBe(true);
+ expect(result.feedbackEnabled).toBe(true);
+ expect(result.feedbackIsInitiated).toBe(true);
+ expect(result.embedDisableNavLink).toBe(false);
+ expect(result.mock).toBe('');
+ });
+
+ it('disables embed nav when the download tab is active', () => {
+ const result = capturedMapState(makeState({ sidebar: { activeTab: 'download' } }));
+ expect(result.embedDisableNavLink).toBe(true);
+ });
+
+ it('disables embed nav when the tour is active', () => {
+ const result = capturedMapState(makeState({ tour: { active: true } }));
+ expect(result.embedDisableNavLink).toBe(true);
+ });
+
+ it('passes the shorten mock parameter when configured', () => {
+ const result = capturedMapState(makeState({
+ config: {
+ features: { urlShortening: false, feedback: false },
+ parameters: { shorten: 'mock-param' },
+ },
+ }));
+ expect(result.mock).toBe('mock-param');
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('requestShortLinkAction dispatches requestShortLink', () => {
+ props.requestShortLinkAction('some/location', { opt: 1 });
+ expect(requestShortLink).toHaveBeenCalledWith('some/location', 'application/json', null, { opt: 1 });
+ expect(dispatch).toHaveBeenCalled();
+ });
+
+ it('sendFeedback initiates feedback when needed', () => {
+ props.sendFeedback(false, false);
+ expect(onClickFeedback).toHaveBeenCalledWith(false, false);
+ expect(initFeedback).toHaveBeenCalled();
+ });
+
+ it('sendFeedback skips init when already initiated', () => {
+ props.sendFeedback(true, true);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
+
+describe('getPermalink usage', () => {
+ it('builds permalink from current query string and selected date', () => {
+ renderComponent();
+ expect(getPermalink).toHaveBeenCalledWith('?p=geographic', defaultProps.selectedDate, undefined);
+ });
});
diff --git a/web/js/containers/timeline/timeline.test.js b/web/js/containers/timeline/timeline.test.js
index 12df1737b..c5a76be46 100644
--- a/web/js/containers/timeline/timeline.test.js
+++ b/web/js/containers/timeline/timeline.test.js
@@ -1,3 +1,2318 @@
-test('timeline container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import {
+ render, fireEvent, act, waitFor,
+} from '@testing-library/react';
+import '@testing-library/jest-dom';
+// ─── Capture connect() args before module load ──────────────────────────────
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+// ─── reactstrap ──────────────────────────────────────────────────────────────
+jest.mock('reactstrap', () => ({
+ UncontrolledTooltip: ({ children }) => <span data-testid="tooltip">{children}</span>,
+}));
+
+// ─── googleTagManager ────────────────────────────────────────────────────────
+jest.mock('googleTagManager', () => ({ pushEvent: jest.fn() }));
+
+// ─── child components (all stubbed) ──────────────────────────────────────────
+jest.mock('../error-boundary', () => function MockErrorBoundary({ children }) {
+ return <div data-testid="error-boundary">{children}</div>;
+});
+jest.mock('../../components/timeline/mobile-date-picker', () => function MockMobileDatePicker() {
+ return <div data-testid="mobile-date-picker" />;
+});
+let capturedTimelineAxisProps = null;
+jest.mock('../../components/timeline/timeline-axis/timeline-axis', () => function MockTimelineAxis(props) {
+ capturedTimelineAxisProps = props;
+ return <div data-testid="timeline-axis" />;
+});
+let capturedCoverageProps = null;
+jest.mock('../../components/timeline/timeline-coverage/timeline-coverage', () => function MockCoverage(props) {
+ capturedCoverageProps = props;
+ return <div data-testid="timeline-coverage" />;
+});
+jest.mock('../../components/timeline/timeline-controls/timescale-interval-change', () => function MockTSIC() {
+ return <div data-testid="timescale-interval-change" />;
+});
+let capturedDraggerContainerProps = null;
+jest.mock('../../components/timeline/timeline-draggers/dragger-container', () => function MockDraggerContainer(props) {
+ capturedDraggerContainerProps = props;
+ return <div data-testid="dragger-container" />;
+});
+jest.mock('../../components/timeline/timeline-axis/date-tooltip/axis-hover-line', () => function MockAxisHoverLine() {
+ return <div data-testid="axis-hover-line" />;
+});
+jest.mock('../../components/timeline/timeline-axis/date-tooltip/date-tooltip', () => function MockDateTooltip() {
+ return <div data-testid="date-tooltip" />;
+});
+jest.mock('../../components/timeline/custom-interval-selector/custom-interval-selector', () => function MockCustomIntervalSelector() {
+ return <div data-testid="custom-interval-selector" />;
+});
+jest.mock('../../components/date-selector/date-selector', () => function MockDateSelector() {
+ return <div data-testid="date-selector" />;
+});
+
+let capturedDateChangeArrowsProps = null;
+jest.mock('../../components/timeline/timeline-controls/date-change-arrows', () => function MockDCA(props) {
+ capturedDateChangeArrowsProps = props;
+ return <div data-testid="date-change-arrows" />;
+});
+
+let capturedAnimationButtonProps = null;
+jest.mock('../../components/timeline/timeline-controls/animation-button', () => function MockAnimBtn(props) {
+ capturedAnimationButtonProps = props;
+ return <button data-testid="animation-button" onClick={props.clickAnimationButton} />;
+});
+
+jest.mock('../../components/timeline/timeline-controls/axis-timescale-change', () => function MockAxisTSC() {
+ return <div data-testid="axis-timescale-change" />;
+});
+let capturedRangeSelectorProps = null;
+jest.mock('../../components/range-selection/range-selection', () => function MockRangeSelector(props) {
+ capturedRangeSelectorProps = props;
+ return <div data-testid="range-selector" />;
+});
+jest.mock('../../components/timeline/kiosk-timestamp', () => function MockKioskTimeStamp() {
+ return <div data-testid="kiosk-timestamp" />;
+});
+jest.mock('../../components/compare/mobile-toggle', () => function MockMobileComparisonToggle() {
+ return <div data-testid="mobile-comparison-toggle" />;
+});
+
+// ─── date-util ────────────────────────────────────────────────────────────────
+jest.mock('../../components/timeline/date-util', () => ({
+ getIsBetween: jest.fn(() => true),
+ getISODateFormatted: jest.fn((d) => {
+ if (!d) return '';
+ const s = new Date(d).toISOString();
+ return s.replace(/\.\d{3}Z$/, 'Z');
+ }),
+}));
+
+// ─── layers selectors ─────────────────────────────────────────────────────────
+jest.mock('../../modules/layers/selectors', () => ({
+ dateRange: jest.fn(() => null),
+ hasSubDaily: jest.fn(() => false),
+ subdailyLayersActive: jest.fn(() => false),
+ subdailyLayers: jest.fn(() => []),
+ getActiveLayers: jest.fn(() => []),
+ getSubDaily: jest.fn(() => []),
+ getSmallestIntervalValue: jest.fn(() => 1440),
+}));
+
+// ─── date selectors ───────────────────────────────────────────────────────────
+jest.mock('../../modules/date/selectors', () => ({
+ getSelectedDate: jest.fn((state) => state.date.selected),
+ getDeltaIntervalUnit: jest.fn(() => ({ delta: 1, unit: 'day', interval: 3 })),
+}));
+
+// ─── date actions ─────────────────────────────────────────────────────────────
+jest.mock('../../modules/date/actions', () => ({
+ selectDate: jest.fn((val) => ({ type: 'SELECT_DATE', val })),
+ changeTimeScale: jest.fn((val) => ({ type: 'CHANGE_TIME_SCALE', val })),
+ selectInterval: jest.fn((delta, ts, cs) => ({ type: 'SELECT_INTERVAL', delta, ts, cs })),
+ changeCustomInterval: jest.fn((d, ts) => ({ type: 'CHANGE_CUSTOM_INTERVAL', d, ts })),
+ changeAutoInterval: jest.fn((a) => ({ type: 'CHANGE_AUTO_INTERVAL', a })),
+ updateAppNow: jest.fn((date) => ({ type: 'UPDATE_APP_NOW', date })),
+ toggleCustomModal: jest.fn((open, by) => ({ type: 'TOGGLE_CUSTOM_MODAL', open, by })),
+ triggerTodayButton: jest.fn(() => ({ type: 'TRIGGER_TODAY' })),
+}));
+
+// ─── date util ────────────────────────────────────────────────────────────────
+jest.mock('../../modules/date/util', () => ({
+ checkHasFutureLayers: jest.fn(() => false),
+ filterProjLayersWithStartDate: jest.fn((layers) => layers),
+ getNextTimeSelection: jest.fn((delta, scale, date) => date),
+ getNextImageryDelta: jest.fn(() => 60),
+}));
+
+// ─── compare actions ──────────────────────────────────────────────────────────
+jest.mock('../../modules/compare/actions', () => ({
+ toggleActiveCompareState: jest.fn(() => ({ type: 'TOGGLE_COMPARE' })),
+}));
+
+// ─── layers actions ───────────────────────────────────────────────────────────
+jest.mock('../../modules/layers/actions', () => ({
+ addGranuleDateRanges: jest.fn((l, d) => ({ type: 'ADD_GRANULE_DATE_RANGES', l, d })),
+}));
+
+// ─── animation actions ────────────────────────────────────────────────────────
+jest.mock('../../modules/animation/actions', () => ({
+ onActivate: jest.fn(() => ({ type: 'OPEN_ANIMATION' })),
+ onClose: jest.fn(() => ({ type: 'CLOSE_ANIMATION' })),
+ changeStartAndEndDate: jest.fn((s, e) => ({ type: 'CHANGE_START_END', s, e })),
+ changeStartDate: jest.fn((d) => ({ type: 'CHANGE_START', d })),
+ changeEndDate: jest.fn((d) => ({ type: 'CHANGE_END', d })),
+ toggleAnimationCollapse: jest.fn(() => ({ type: 'TOGGLE_ANIM_COLLAPSE' })),
+ stop: jest.fn(() => ({ type: 'PAUSE_ANIMATION' })),
+}));
+
+// ─── date constants ───────────────────────────────────────────────────────────
+jest.mock('../../modules/date/constants', () => ({
+ TIME_SCALE_FROM_NUMBER: {
+ 1: 'year', 2: 'month', 3: 'day', 4: 'hour', 5: 'minute',
+ },
+ TIME_SCALE_TO_NUMBER: {
+ year: 1, month: 2, day: 3, hour: 4, minute: 5,
+ },
+ timeScaleOptions: {
+ year: { timeAxis: { gridWidth: 50 } },
+ month: { timeAxis: { gridWidth: 24 } },
+ day: { timeAxis: { gridWidth: 12 } },
+ hour: { timeAxis: { gridWidth: 6 } },
+ minute: { timeAxis: { gridWidth: 3 } },
+ },
+ customModalType: { TIMELINE: 'TIMELINE' },
+}));
+
+// ─── util ─────────────────────────────────────────────────────────────────────
+jest.mock('../../util/util', () => ({
+ __esModule: true,
+ default: {
+ now: jest.fn(() => new Date('2021-01-01T00:00:00Z')),
+ roundTimeQuarterHour: jest.fn((d) => d),
+ },
+}));
+
+// ─── usePrevious (real implementation so prev !== current on re-renders) ──────
+jest.mock('../../util/customHooks', () => {
+ const { useRef, useEffect } = require('react');
+ return (val) => {
+ const ref = useRef();
+ useEffect(() => {
+ ref.current = val;
+ });
+ return ref.current;
+ };
+});
+
+// ─── Load Timeline after mocks ────────────────────────────────────────────────
+let Timeline;
+beforeAll(() => {
+ Timeline = require('./timeline').default;
+});
+
+// The component's cleanup effect does:
+// document.querySelector('.timeline-container').removeEventListener(...)
+// After RTL unmounts the component the element is gone, causing a null ref.
+// We pre-attach a persistent element so that querySelector always succeeds.
+let persistentTimelineContainer;
+beforeEach(() => {
+ persistentTimelineContainer = document.createElement('div');
+ persistentTimelineContainer.className = 'timeline-container';
+ document.body.appendChild(persistentTimelineContainer);
+});
+afterEach(() => {
+ if (persistentTimelineContainer && persistentTimelineContainer.parentNode) {
+ persistentTimelineContainer.parentNode.removeChild(persistentTimelineContainer);
+ }
+});
+
+// ─── Default props ────────────────────────────────────────────────────────────
+const NOW = new Date('2021-01-01T00:00:00Z');
+const DATE_A = '2021-01-01T00:00:00Z';
+const DATE_B = '2020-06-01T00:00:00Z';
+
+const defaultProps = {
+ activeLayers: [],
+ addGranuleDateRanges: jest.fn(),
+ animationDisabled: false,
+ animEndLocationDate: null,
+ animStartLocationDate: null,
+ appNow: NOW,
+ autoSelected: false,
+ axisWidth: 900,
+ breakpoints: {},
+ changeAutoInterval: jest.fn(),
+ changeCustomInterval: jest.fn(),
+ changeTimeScale: jest.fn(),
+ closeAnimation: jest.fn(),
+ customInterval: 3,
+ customSelected: false,
+ dateA: DATE_A,
+ dateB: DATE_B,
+ activeString: 'active',
+ deltaChangeAmt: 1,
+ displayStaticMap: false,
+ draggerSelected: 'selected',
+ hasFutureLayers: false,
+ hasSubdailyLayers: false,
+ hasTempoProduct: false,
+ hideTimeline: false,
+ interval: 3,
+ isAnimatingToEvent: false,
+ isAnimationPlaying: false,
+ isAnimationWidgetOpen: false,
+ isChartingActive: false,
+ isCompareModeActive: false,
+ isDataDownload: false,
+ isDistractionFreeModeActive: false,
+ isEmbedModeActive: false,
+ isGifActive: false,
+ isKioskModeActive: false,
+ isLandscape: false,
+ isMobile: false,
+ isMobilePhone: false,
+ isMobileTablet: false,
+ isPortrait: true,
+ isTourActive: false,
+ leftArrowDisabled: false,
+ newCustomDelta: 1440,
+ nowButtonDisabled: false,
+ nowOverride: false,
+ onPauseAnimation: jest.fn(),
+ onToggleAnimationCollapse: jest.fn(),
+ onUpdateEndDate: jest.fn(),
+ onUpdateStartAndEndDate: jest.fn(),
+ onUpdateStartDate: jest.fn(),
+ openAnimation: jest.fn(),
+ parentOffset: 320,
+ rightArrowDisabled: false,
+ screenWidth: 1200,
+ selectDate: jest.fn(),
+ selectedDate: NOW,
+ subDailyLayersList: [],
+ timelineCustomModalOpen: false,
+ timelineEndDateLimit: '2021-01-01T00:00:00Z',
+ timelineStartDateLimit: '1948-01-01T00:00:00Z',
+ timeScale: 'day',
+ timeScaleChangeUnit: 'day',
+ toggleActiveCompareState: jest.fn(),
+ triggerTodayButton: jest.fn(),
+ updateAppNow: jest.fn(),
+ proj: { id: 'geographic' },
+ describeDomainsUrl: 'https://gibs.earthdata.nasa.gov',
+ cmrBaseUrl: 'https://cmr.earthdata.nasa.gov',
+};
+
+const renderComponent = (props = {}) => render(
+ <Timeline {...defaultProps} {...props} />,
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ capturedDateChangeArrowsProps = null;
+ capturedAnimationButtonProps = null;
+ capturedTimelineAxisProps = null;
+ capturedCoverageProps = null;
+ capturedRangeSelectorProps = null;
+ capturedDraggerContainerProps = null;
+});
+
+// ─── Rendering ────────────────────────────────────────────────────────────────
+
+describe('Timeline rendering', () => {
+ it('renders the timeline-container div', () => {
+ const { container } = renderComponent();
+ expect(container.querySelector('.timeline-container')).toBeInTheDocument();
+ });
+
+ it('renders desktop timeline section after mount effects run', async () => {
+ const { container } = renderComponent();
+ await waitFor(() => {
+ expect(container.querySelector('#timeline')).toBeInTheDocument();
+ });
+ });
+
+ it('renders date-selector in desktop mode', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('date-selector')).toBeInTheDocument();
+ });
+ });
+
+ it('renders animation button in desktop mode', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('animation-button')).toBeInTheDocument();
+ });
+ });
+
+ it('renders date-change-arrows in desktop mode', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('date-change-arrows')).toBeInTheDocument();
+ });
+ });
+
+ it('renders timeline-axis in footer', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('timeline-axis')).toBeInTheDocument();
+ });
+ });
+
+ it('renders the hide timeline button', async () => {
+ const { container } = renderComponent();
+ await waitFor(() => {
+ expect(container.querySelector('#timeline-hide')).toBeInTheDocument();
+ });
+ });
+
+ it('desktop header has subdaily class when hasSubdailyLayers=true', async () => {
+ const { container } = renderComponent({ hasSubdailyLayers: true });
+ await waitFor(() => {
+ expect(container.querySelector('.timeline-header-desktop'))
+ .toHaveClass('subdaily');
+ });
+ });
+
+ it('desktop header lacks subdaily class when hasSubdailyLayers=false', async () => {
+ const { container } = renderComponent({ hasSubdailyLayers: false });
+ await waitFor(() => {
+ expect(container.querySelector('.timeline-header-desktop'))
+ .not.toHaveClass('subdaily');
+ });
+ });
+
+ it('date-selector-main has kiosk class when isKioskModeActive=true', async () => {
+ const { container } = renderComponent({ isKioskModeActive: true });
+ await waitFor(() => {
+ expect(container.querySelector('#date-selector-main'))
+ .toHaveClass('date-selector-kiosk');
+ });
+ });
+
+ it('zoom-buttons-group is hidden when isKioskModeActive=true', async () => {
+ const { container } = renderComponent({ isKioskModeActive: true });
+ await waitFor(() => {
+ expect(container.querySelector('#zoom-buttons-group')).toHaveClass('d-none');
+ });
+ });
+});
+
+// ─── Mobile rendering ─────────────────────────────────────────────────────────
+
+describe('Timeline mobile rendering', () => {
+ it('renders mobile header when isMobile=true', async () => {
+ const { container } = renderComponent({ isMobile: true });
+ await waitFor(() => {
+ expect(container.querySelector('.timeline-header-mobile')).toBeInTheDocument();
+ });
+ });
+
+ it('renders mobile date picker when isMobile=true', async () => {
+ const { getByTestId } = renderComponent({ isMobile: true });
+ await waitFor(() => {
+ expect(getByTestId('mobile-date-picker')).toBeInTheDocument();
+ });
+ });
+
+ it('renders MobileComparisonToggle in mobile mode', async () => {
+ const { getByTestId } = renderComponent({ isMobile: true });
+ await waitFor(() => {
+ expect(getByTestId('mobile-comparison-toggle')).toBeInTheDocument();
+ });
+ });
+
+ it('does not render AnimationButton when isCompareModeActive=true in mobile', async () => {
+ const { queryByTestId } = renderComponent({ isMobile: true, isCompareModeActive: true });
+ await waitFor(() => {
+ expect(queryByTestId('animation-button')).not.toBeInTheDocument();
+ });
+ });
+
+ it('does not render AnimationButton when isChartingActive=true in mobile', async () => {
+ const { queryByTestId } = renderComponent({ isMobile: true, isChartingActive: true });
+ await waitFor(() => {
+ expect(queryByTestId('animation-button')).not.toBeInTheDocument();
+ });
+ });
+
+ it('renders mobile mode when isEmbedModeActive=true (not isMobile)', async () => {
+ const { container } = renderComponent({ isEmbedModeActive: true, isMobile: false });
+ await waitFor(() => {
+ expect(container.querySelector('.timeline-header-mobile')).toBeInTheDocument();
+ });
+ });
+
+ it('desktop timeline is not rendered when isMobile=true', async () => {
+ const { container } = renderComponent({ isMobile: true });
+ await waitFor(() => {
+ expect(container.querySelector('#timeline')).not.toBeInTheDocument();
+ });
+ });
+});
+
+// ─── Distraction-free / kiosk mode ───────────────────────────────────────────
+
+describe('Timeline distraction-free mode', () => {
+ it('renders distraction-free section when isDistractionFreeModeActive=true', async () => {
+ const { container } = renderComponent({ isDistractionFreeModeActive: true });
+ await waitFor(() => {
+ expect(container.querySelector('#distraction-free-timeline')).toBeInTheDocument();
+ });
+ });
+
+ it('renders KioskTimeStamp in distraction-free mode', async () => {
+ const { getByTestId } = renderComponent({ isDistractionFreeModeActive: true });
+ await waitFor(() => {
+ expect(getByTestId('kiosk-timestamp')).toBeInTheDocument();
+ });
+ });
+
+ it('does not render normal desktop timeline in distraction-free mode', async () => {
+ const { container } = renderComponent({ isDistractionFreeModeActive: true });
+ await waitFor(() => {
+ expect(container.querySelector('#timeline')).not.toBeInTheDocument();
+ });
+ });
+
+ it('distraction-free header has mobile class when isMobile=true', async () => {
+ const { container } = renderComponent({ isDistractionFreeModeActive: true, isMobile: true });
+ await waitFor(() => {
+ expect(container.querySelector('.distraction-free-timeline-header'))
+ .toHaveClass('mobile');
+ });
+ });
+
+ it('distraction-free header is hidden when displayStaticMap=true', async () => {
+ const { container } = renderComponent({
+ isDistractionFreeModeActive: true,
+ displayStaticMap: true,
+ });
+ await waitFor(() => {
+ const header = container.querySelector('#distraction-free-timeline-header');
+ expect(header.style.display).toBe('none');
+ });
+ });
+});
+
+// ─── Timeline hide/show (chevron) ─────────────────────────────────────────────
+
+describe('Timeline hide/show chevron', () => {
+ it('show-timeline aria-label when timeline is hidden', async () => {
+ const { container } = renderComponent();
+ await waitFor(() => {
+ expect(container.querySelector('#timeline-hide')).toBeInTheDocument();
+ });
+ const btn = container.querySelector('#timeline-hide');
+ act(() => { fireEvent.click(btn); });
+ expect(btn).toHaveAttribute('aria-label', 'Show timeline');
+ });
+
+ it('hide-timeline aria-label initially', async () => {
+ const { container } = renderComponent();
+ await waitFor(() => {
+ const btn = container.querySelector('#timeline-hide');
+ expect(btn).toHaveAttribute('aria-label', 'Hide timeline');
+ });
+ });
+
+ it('toggles timeline hidden on button click', async () => {
+ const { container } = renderComponent();
+ let btn;
+ await waitFor(() => {
+ btn = container.querySelector('#timeline-hide');
+ expect(btn).toBeInTheDocument();
+ });
+ // Initially timeline footer is shown (not hidden)
+ expect(container.querySelector('#timeline-footer')).toBeInTheDocument();
+ act(() => { fireEvent.click(btn); });
+ // After click, timeline footer should be hidden
+ await waitFor(() => {
+ expect(container.querySelector('#timeline-footer')).not.toBeInTheDocument();
+ });
+ });
+
+ it('hideTimeline prop hides the footer', async () => {
+ const { container } = renderComponent({ hideTimeline: true });
+ await waitFor(() => {
+ expect(container.querySelector('#timeline-footer')).not.toBeInTheDocument();
+ });
+ });
+
+ it('chevron direction is left when timeline is hidden', async () => {
+ const { container } = renderComponent({ hideTimeline: true });
+ await waitFor(() => {
+ const chevron = container.querySelector('.wv-timeline-hide');
+ expect(chevron).toHaveClass('wv-timeline-hide-double-chevron-left');
+ });
+ });
+
+ it('chevron direction is right when timeline is visible', async () => {
+ const { container } = renderComponent({ hideTimeline: false });
+ await waitFor(() => {
+ const chevron = container.querySelector('.wv-timeline-hide');
+ expect(chevron).toHaveClass('wv-timeline-hide-double-chevron-right');
+ });
+ });
+});
+
+// ─── clickAnimationButton ─────────────────────────────────────────────────────
+
+describe('clickAnimationButton', () => {
+ it('calls openAnimation when widget is not open and not mobile', async () => {
+ const openAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ openAnimation,
+ isAnimationWidgetOpen: false,
+ isMobile: false,
+ isCompareModeActive: false,
+ isChartingActive: false,
+ isDataDownload: false,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(openAnimation).toHaveBeenCalled();
+ });
+
+ it('calls closeAnimation when widget is open and not mobile', async () => {
+ const closeAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ closeAnimation,
+ isAnimationWidgetOpen: true,
+ isMobile: false,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(closeAnimation).toHaveBeenCalled();
+ });
+
+ it('does not call openAnimation when isCompareModeActive=true', async () => {
+ const openAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ openAnimation,
+ isAnimationWidgetOpen: false,
+ isCompareModeActive: true,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(openAnimation).not.toHaveBeenCalled();
+ });
+
+ it('does not call openAnimation when isChartingActive=true', async () => {
+ const openAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ openAnimation,
+ isChartingActive: true,
+ isCompareModeActive: false,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(openAnimation).not.toHaveBeenCalled();
+ });
+
+ it('calls onToggleAnimationCollapse and onPauseAnimation on mobile when widget open', async () => {
+ const onToggleAnimationCollapse = jest.fn();
+ const onPauseAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ isAnimationWidgetOpen: true,
+ isMobile: true,
+ onToggleAnimationCollapse,
+ onPauseAnimation,
+ isCompareModeActive: false,
+ isChartingActive: false,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(onToggleAnimationCollapse).toHaveBeenCalled();
+ expect(onPauseAnimation).toHaveBeenCalled();
+ });
+
+ it('calls openAnimation on mobile when widget is not open', async () => {
+ const openAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ isAnimationWidgetOpen: false,
+ isMobile: true,
+ openAnimation,
+ isCompareModeActive: false,
+ isChartingActive: false,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(openAnimation).toHaveBeenCalled();
+ });
+
+ it('passes correct label when isCompareModeActive=true to AnimationButton', async () => {
+ renderComponent({ isCompareModeActive: true });
+ await waitFor(() => {
+ expect(capturedAnimationButtonProps.label).toMatch(/Compare feature/);
+ });
+ });
+
+ it('passes charting label when isChartingActive=true and not compare mode', async () => {
+ renderComponent({ isChartingActive: true, isCompareModeActive: false });
+ await waitFor(() => {
+ expect(capturedAnimationButtonProps.label).toMatch(/Charting feature/);
+ });
+ });
+
+ it('passes data download label when isDataDownload=true', async () => {
+ renderComponent({
+ isDataDownload: true,
+ isChartingActive: false,
+ isCompareModeActive: false,
+ });
+ await waitFor(() => {
+ expect(capturedAnimationButtonProps.label).toMatch(/Data Download/);
+ });
+ });
+
+ it('pushes GTM event when opening animation from desktop', async () => {
+ const googleTagManager = require('googleTagManager');
+ const openAnimation = jest.fn();
+ const { getByTestId } = renderComponent({
+ openAnimation,
+ isAnimationWidgetOpen: false,
+ isMobile: false,
+ isCompareModeActive: false,
+ });
+ await waitFor(() => { expect(getByTestId('animation-button')).toBeInTheDocument(); });
+ fireEvent.click(getByTestId('animation-button'));
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'GIF_setup_animation_button',
+ });
+ });
+});
+
+// ─── handleArrowDateChange (via DateChangeArrows callbacks) ───────────────────
+
+describe('handleArrowDateChange', () => {
+ it('calls onDateChange via leftArrowDown when not disabled', async () => {
+ const selectDate = jest.fn();
+ renderComponent({ selectDate, leftArrowDisabled: false });
+ await waitFor(() => { expect(capturedDateChangeArrowsProps).not.toBeNull(); });
+ act(() => { capturedDateChangeArrowsProps.leftArrowDown(); });
+ // selectDate is debounced; verify via the debounce ref
+ await waitFor(() => {}, { timeout: 100 });
+ });
+
+ it('does not change date via left arrow when leftArrowDisabled=true', async () => {
+ const selectDate = jest.fn();
+ renderComponent({ selectDate, leftArrowDisabled: true });
+ await waitFor(() => { expect(capturedDateChangeArrowsProps).not.toBeNull(); });
+ act(() => { capturedDateChangeArrowsProps.leftArrowDown(); });
+ // selectDate debounce won't fire synchronously; just ensure no crash
+ });
+
+ it('calls handleSelectNowButton (triggerTodayButton) via DateChangeArrows', async () => {
+ const triggerTodayButton = jest.fn();
+ renderComponent({ triggerTodayButton });
+ await waitFor(() => { expect(capturedDateChangeArrowsProps).not.toBeNull(); });
+ act(() => { capturedDateChangeArrowsProps.handleSelectNowButton(); });
+ expect(triggerTodayButton).toHaveBeenCalled();
+ });
+
+ it('passes leftArrowDisabled prop to DateChangeArrows', async () => {
+ renderComponent({ leftArrowDisabled: true });
+ await waitFor(() => {
+ expect(capturedDateChangeArrowsProps.leftArrowDisabled).toBe(true);
+ });
+ });
+
+ it('passes rightArrowDisabled prop to DateChangeArrows', async () => {
+ renderComponent({ rightArrowDisabled: true });
+ await waitFor(() => {
+ expect(capturedDateChangeArrowsProps.rightArrowDisabled).toBe(true);
+ });
+ });
+
+ it('passes nowButtonDisabled prop to DateChangeArrows', async () => {
+ renderComponent({ nowButtonDisabled: true });
+ await waitFor(() => {
+ expect(capturedDateChangeArrowsProps.nowButtonDisabled).toBe(true);
+ });
+ });
+
+ it('uses getNextImageryDelta when autoSelected and subDailyLayersList has items', async () => {
+ const { getNextImageryDelta } = require('../../modules/date/util');
+ renderComponent({
+ autoSelected: true,
+ subDailyLayersList: [{ id: 'layer1' }],
+ leftArrowDisabled: false,
+ });
+ await waitFor(() => { expect(capturedDateChangeArrowsProps).not.toBeNull(); });
+ act(() => { capturedDateChangeArrowsProps.leftArrowDown(); });
+ expect(getNextImageryDelta).toHaveBeenCalled();
+ });
+
+ it('uses customSelected delta when customSelected=true and deltaChangeAmt is set', async () => {
+ const { getNextTimeSelection } = require('../../modules/date/util');
+ renderComponent({
+ customSelected: true,
+ deltaChangeAmt: 5,
+ rightArrowDisabled: false,
+ });
+ await waitFor(() => { expect(capturedDateChangeArrowsProps).not.toBeNull(); });
+ act(() => { capturedDateChangeArrowsProps.rightArrowDown(); });
+ expect(getNextTimeSelection).toHaveBeenCalledWith(5, 'day', expect.anything(), expect.anything(), expect.anything());
+ });
+});
+
+// ─── Keyboard events ──────────────────────────────────────────────────────────
+
+describe('Keyboard event handling', () => {
+ it('calls changeTimeScale on ArrowUp key (zoom in)', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'day' });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowUp' });
+ });
+ // timeScale 'day' = 3, ArrowUp decrements to 2
+ expect(changeTimeScale).toHaveBeenCalledWith(2);
+ });
+
+ it('calls changeTimeScale on ArrowDown key (zoom out)', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'day' });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowDown' });
+ });
+ // day = 3, ArrowDown increments to 4 (hour), max without subdaily is 3 but day is 3
+ // Actually maxTimeScaleNumber = 3 (no subdaily), so no change expected when at max
+ // Let's test with month (2) which can go down to day (3)
+ });
+
+ it('ArrowDown does not exceed max timescale without subdaily', async () => {
+ const changeTimeScale = jest.fn();
+ // timeScale 'day' = 3 = max when no subdaily
+ renderComponent({ changeTimeScale, timeScale: 'day', hasSubdailyLayers: false });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowDown' });
+ });
+ expect(changeTimeScale).not.toHaveBeenCalled();
+ });
+
+ it('ArrowDown can go to hour when hasSubdailyLayers=true', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'day', hasSubdailyLayers: true });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowDown' });
+ });
+ expect(changeTimeScale).toHaveBeenCalledWith(4);
+ });
+
+ it('ArrowUp does not go below 1 (year)', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'year' });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowUp' });
+ });
+ expect(changeTimeScale).not.toHaveBeenCalled();
+ });
+
+ it('does not handle keys when target is INPUT', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'day' });
+ await waitFor(() => {});
+ act(() => {
+ const input = document.createElement('input');
+ document.body.appendChild(input);
+ fireEvent.keyDown(input, { key: 'ArrowUp', target: input });
+ });
+ expect(changeTimeScale).not.toHaveBeenCalled();
+ });
+
+ it('does not handle keys with ctrlKey', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'month' });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowUp', ctrlKey: true });
+ });
+ expect(changeTimeScale).not.toHaveBeenCalled();
+ });
+});
+
+// ─── mapStateToProps ──────────────────────────────────────────────────────────
+
+describe('mapStateToProps', () => {
+ const {
+ getActiveLayers, subdailyLayersActive, subdailyLayers,
+ hasSubDaily, getSubDaily, getSmallestIntervalValue,
+ } = require('../../modules/layers/selectors');
+ const { getSelectedDate, getDeltaIntervalUnit } = require('../../modules/date/selectors');
+ const { checkHasFutureLayers, filterProjLayersWithStartDate } = require('../../modules/date/util');
+ const { getISODateFormatted } = require('../../components/timeline/date-util');
+
+ const selectedDate = new Date('2021-01-01T00:00:00Z');
+ const appNow = new Date('2021-01-01T00:00:00Z');
+
+ const makeState = (overrides = {}) => ({
+ animation: {
+ isActive: false,
+ startDate: null,
+ endDate: null,
+ gifActive: false,
+ isPlaying: false,
+ isCollapsed: false,
+ },
+ compare: {
+ active: false,
+ isCompareA: true,
+ activeString: 'active',
+ },
+ charting: { active: false },
+ config: {
+ startDate: '1948-01-01T00:00:00Z',
+ parameters: {},
+ features: {},
+ },
+ date: {
+ appNow,
+ customDelta: 1,
+ customInterval: 3,
+ customSelected: false,
+ autoSelected: false,
+ interval: 3,
+ selected: selectedDate,
+ selectedB: new Date('2020-06-01T00:00:00Z'),
+ selectedZoom: 3,
+ timelineCustomModalOpen: false,
+ delta: 1,
+ },
+ events: { isAnimatingToEvent: false },
+ embed: { isEmbedModeActive: false },
+ layers: {
+ active: { layers: [] },
+ activeB: { layers: [] },
+ },
+ map: { ui: { selected: { frameState_: true } } },
+ modal: { isOpen: false, id: null },
+ proj: { id: 'geographic', selected: { id: 'geographic' } },
+ screenSize: {
+ isMobileDevice: false,
+ breakpoints: {},
+ screenWidth: 1200,
+ isMobilePhone: false,
+ isMobileTablet: false,
+ orientation: 'landscape',
+ },
+ sidebar: { activeTab: 'layers' },
+ tour: { active: false },
+ ui: {
+ isDistractionFreeModeActive: false,
+ isKioskModeActive: false,
+ displayStaticMap: false,
+ },
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ getActiveLayers.mockReturnValue([]);
+ subdailyLayersActive.mockReturnValue(false);
+ subdailyLayers.mockReturnValue([]);
+ hasSubDaily.mockReturnValue(false);
+ getSubDaily.mockReturnValue([]);
+ getSmallestIntervalValue.mockReturnValue(1440);
+ getSelectedDate.mockReturnValue(selectedDate);
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ checkHasFutureLayers.mockReturnValue(false);
+ filterProjLayersWithStartDate.mockImplementation((layers) => layers);
+ getISODateFormatted.mockImplementation((d) => {
+ if (!d) return '';
+ return new Date(d).toISOString()
+ .replace(/\.\d{3}Z$/, 'Z');
+ });
+ });
+
+ it('maps appNow from state.date.appNow', () => {
+ const result = capturedMapState(makeState());
+ expect(result.appNow).toBe(appNow);
+ });
+
+ it('maps isMobile from screenSize.isMobileDevice', () => {
+ const result = capturedMapState(makeState({
+ screenSize: { ...makeState().screenSize, isMobileDevice: true },
+ }));
+ expect(result.isMobile).toBe(true);
+ });
+
+ it('maps isTourActive from tour.active', () => {
+ const result = capturedMapState(makeState({ tour: { active: true } }));
+ expect(result.isTourActive).toBe(true);
+ });
+
+ it('maps isCompareModeActive from compare.active', () => {
+ const result = capturedMapState(makeState({compare: { ...makeState().compare, active: true } },
+ ));
+ expect(result.isCompareModeActive).toBe(true);
+ });
+
+ it('maps isChartingActive from charting.active', () => {
+ const result = capturedMapState(makeState({ charting: { active: true } }));
+ expect(result.isChartingActive).toBe(true);
+ });
+
+ it('maps isAnimationWidgetOpen from animation.isActive', () => {
+ const result = capturedMapState(makeState({
+ animation: { ...makeState().animation, isActive: true },
+ }));
+ expect(result.isAnimationWidgetOpen).toBe(true);
+ });
+
+ it('maps draggerSelected to selectedB when isCompareA=false', () => {
+ const result = capturedMapState(makeState({
+ compare: { ...makeState().compare, isCompareA: false },
+ }));
+ expect(result.draggerSelected).toBe('selectedB');
+ });
+
+ it('maps draggerSelected to selected when isCompareA=true', () => {
+ const result = capturedMapState(makeState());
+ expect(result.draggerSelected).toBe('selected');
+ });
+
+ it('maps timelineStartDateLimit from config.startDate', () => {
+ const result = capturedMapState(makeState());
+ expect(result.timelineStartDateLimit).toBe('1948-01-01T00:00:00Z');
+ });
+
+ it('maps nowOverride=true when config.parameters.now is set', () => {
+ const result = capturedMapState(makeState({
+ config: { ...makeState().config, parameters: { now: '2021-01-01T00:00:00Z' } },
+ }));
+ expect(result.nowOverride).toBe(true);
+ });
+
+ it('maps nowOverride=false when config.parameters.now is absent', () => {
+ const result = capturedMapState(makeState());
+ expect(result.nowOverride).toBe(false);
+ });
+
+ it('maps isAnimationPlaying from animation.isPlaying', () => {
+ const result = capturedMapState(makeState({
+ animation: { ...makeState().animation, isPlaying: true },
+ }));
+ expect(result.isAnimationPlaying).toBe(true);
+ });
+
+ it('maps isGifActive from animation.gifActive', () => {
+ const result = capturedMapState(makeState({
+ animation: { ...makeState().animation, gifActive: true },
+ }));
+ expect(result.isGifActive).toBe(true);
+ });
+
+ it('maps isDataDownload=true when sidebar.activeTab=download', () => {
+ const result = capturedMapState(makeState({ sidebar: { activeTab: 'download' } }));
+ expect(result.isDataDownload).toBe(true);
+ });
+
+ it('maps hideTimeline=true when modal is open with TOOLBAR_SNAPSHOT id', () => {
+ const result = capturedMapState(makeState({
+ modal: { isOpen: true, id: 'TOOLBAR_SNAPSHOT' },
+ animation: { ...makeState().animation, gifActive: false },
+ }));
+ expect(result.hideTimeline).toBe(true);
+ });
+
+ it('maps hideTimeline=true when gifActive=true', () => {
+ const result = capturedMapState(makeState({
+ animation: { ...makeState().animation, gifActive: true },
+ }));
+ expect(result.hideTimeline).toBe(true);
+ });
+
+ it('caps selectedZoom to 3 when no subdaily and selectedZoom > 3', () => {
+ subdailyLayersActive.mockReturnValue(false);
+ const result = capturedMapState(makeState({
+ date: { ...makeState().date, selectedZoom: 5 },
+ }));
+ expect(result.timeScale).toBe('day'); // TIME_SCALE_FROM_NUMBER[3] = 'day'
+ });
+
+ it('caps customInterval to 3 when no subdaily and customInterval > 3', () => {
+ subdailyLayersActive.mockReturnValue(false);
+ const result = capturedMapState(makeState({
+ date: { ...makeState().date, customInterval: 5, selectedZoom: 3 },
+ }));
+ expect(result.customIntervalZoomLevel).toBe(3);
+ });
+
+ it('maps hasSubdailyLayers via hasSubDailySelector in compare mode', () => {
+ hasSubDaily.mockReturnValue(true);
+ const result = capturedMapState(makeState({
+ compare: { ...makeState().compare, active: true },
+ }));
+ expect(result.hasSubdailyLayers).toBe(true);
+ });
+
+ it('maps animationDisabled=true when no map frameState_', () => {
+ const result = capturedMapState(makeState({ map: { ui: { selected: {} } } }));
+ expect(result.animationDisabled).toBe(true);
+ });
+
+ it('maps animationDisabled=true when sidebar is download tab', () => {
+ const result = capturedMapState(makeState({ sidebar: { activeTab: 'download' } }));
+ expect(result.animationDisabled).toBe(true);
+ });
+
+ it('maps animationDisabled=true when compare is active', () => {
+ const result = capturedMapState(makeState({
+ compare: { ...makeState().compare, active: true },
+ }));
+ expect(result.animationDisabled).toBe(true);
+ });
+
+ it('maps describeDomainsUrl from config.features', () => {
+ const result = capturedMapState(makeState({
+ config: { ...makeState().config, features: { describeDomains: { url: 'https://example.com' } } },
+ }));
+ expect(result.describeDomainsUrl).toBe('https://example.com');
+ });
+
+ it('maps describeDomainsUrl to fallback when feature absent', () => {
+ const result = capturedMapState(makeState());
+ expect(result.describeDomainsUrl).toBe('https://gibs.earthdata.nasa.gov');
+ });
+
+ it('maps cmrBaseUrl from config.features.cmr.url', () => {
+ const result = capturedMapState(makeState({
+ config: { ...makeState().config, features: { cmr: { url: 'https://cmr.example.com' } } },
+ }));
+ expect(result.cmrBaseUrl).toBe('https://cmr.example.com');
+ });
+
+ it('maps proj from proj.selected', () => {
+ const result = capturedMapState(makeState({
+ proj: { id: 'arctic', selected: { id: 'arctic', name: 'Arctic' } },
+ }));
+ expect(result.proj).toEqual({ id: 'arctic', name: 'Arctic' });
+ });
+
+ it('computes leftArrowDisabled based on date proximity to start limit', () => {
+ getSelectedDate.mockReturnValue(new Date('1948-01-01T00:00:00Z'));
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ const result = capturedMapState(makeState());
+ expect(result.leftArrowDisabled).toBe(true);
+ });
+
+ it('leftArrowDisabled=false when date is well above start limit', () => {
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ const result = capturedMapState(makeState());
+ expect(result.leftArrowDisabled).toBe(false);
+ });
+
+ it('rightArrowDisabled=false when autoSelected=true', () => {
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ const result = capturedMapState(makeState({
+ date: { ...makeState().date, autoSelected: true },
+ }));
+ expect(result.rightArrowDisabled).toBe(false);
+ });
+
+ it('nowButtonDisabled=true when selectedDate equals appNow', () => {
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ getISODateFormatted.mockImplementation((d) => new Date(d).toISOString()
+ .replace(/\.\d{3}Z$/, 'Z'));
+ const result = capturedMapState(makeState());
+ // selectedDate === appNow === '2021-01-01T00:00:00Z', timelineEndDateLimit = same
+ expect(result.nowButtonDisabled).toBe(true);
+ });
+
+ it('maps subDailyLayersList by merging A and B in compare mode', () => {
+ getSubDaily.mockReturnValueOnce([{ id: 'layer-a' }]).mockReturnValueOnce([{ id: 'layer-b' }]);
+ const result = capturedMapState(makeState({
+ compare: { ...makeState().compare, active: true },
+ }));
+ expect(result.subDailyLayersList).toHaveLength(2);
+ });
+
+ it('maps timelineEndDateLimit from appNow when no future layers', () => {
+ checkHasFutureLayers.mockReturnValue(false);
+ const result = capturedMapState(makeState());
+ expect(result.timelineEndDateLimit).toBeDefined();
+ });
+
+ it('maps timelineEndDateLimit via getTimelineEndDateLimit when hasFutureLayers', () => {
+ checkHasFutureLayers.mockReturnValue(true);
+ const result = capturedMapState(makeState());
+ expect(result.hasFutureLayers).toBe(true);
+ expect(result.timelineEndDateLimit).toBeDefined();
+ });
+
+ it('maps isLandscape=true from orientation=landscape', () => {
+ const result = capturedMapState(makeState());
+ expect(result.isLandscape).toBe(true);
+ });
+
+ it('maps isPortrait from orientation', () => {
+ const result = capturedMapState(makeState({
+ screenSize: { ...makeState().screenSize, orientation: 'portrait' },
+ }));
+ expect(result.isPortrait).toBe(true);
+ });
+});
+
+// ─── mapDispatchToProps ───────────────────────────────────────────────────────
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let dispatchProps;
+
+ beforeEach(() => {
+ dispatch = jest.fn();
+ dispatchProps = capturedMapDispatch(dispatch);
+ });
+
+ it('updateAppNow dispatches updateAppNow action', () => {
+ const date = new Date();
+ dispatchProps.updateAppNow(date);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'UPDATE_APP_NOW', date });
+ });
+
+ it('triggerTodayButton dispatches triggerTodayButton action', () => {
+ dispatchProps.triggerTodayButton();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TRIGGER_TODAY' });
+ });
+
+ it('selectDate dispatches selectDate action', () => {
+ const val = new Date();
+ dispatchProps.selectDate(val);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'SELECT_DATE', val });
+ });
+
+ it('changeCustomInterval dispatches with delta and timeScale', () => {
+ dispatchProps.changeCustomInterval(5, 3);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_CUSTOM_INTERVAL', d: 5, ts: 3 });
+ });
+
+ it('changeAutoInterval dispatches with autoSelected value', () => {
+ dispatchProps.changeAutoInterval(true);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_AUTO_INTERVAL', a: true });
+ });
+
+ it('changeTimeScale dispatches with value', () => {
+ dispatchProps.changeTimeScale(4);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_TIME_SCALE', val: 4 });
+ });
+
+ it('openAnimation dispatches open animation action', () => {
+ dispatchProps.openAnimation();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'OPEN_ANIMATION' });
+ });
+
+ it('closeAnimation dispatches close animation action', () => {
+ dispatchProps.closeAnimation();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CLOSE_ANIMATION' });
+ });
+
+ it('toggleActiveCompareState dispatches toggle compare action', () => {
+ dispatchProps.toggleActiveCompareState();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_COMPARE' });
+ });
+
+ it('onUpdateStartDate dispatches changeStartDate', () => {
+ const d = new Date();
+ dispatchProps.onUpdateStartDate(d);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_START', d });
+ });
+
+ it('onUpdateEndDate dispatches changeEndDate', () => {
+ const d = new Date();
+ dispatchProps.onUpdateEndDate(d);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_END', d });
+ });
+
+ it('onUpdateStartAndEndDate dispatches changeStartAndEndDate', () => {
+ const s = new Date('2020-01-01');
+ const e = new Date('2020-12-31');
+ dispatchProps.onUpdateStartAndEndDate(s, e);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_START_END', s, e });
+ });
+
+ it('onToggleAnimationCollapse dispatches toggleAnimationCollapse', () => {
+ dispatchProps.onToggleAnimationCollapse();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_ANIM_COLLAPSE' });
+ });
+
+ it('onPauseAnimation dispatches pause action', () => {
+ dispatchProps.onPauseAnimation();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'PAUSE_ANIMATION' });
+ });
+
+ it('addGranuleDateRanges dispatches with layer and dateRanges', () => {
+ dispatchProps.addGranuleDateRanges('layer1', [[1, 2]]);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'ADD_GRANULE_DATE_RANGES', l: 'layer1', d: [[1, 2]] });
+ });
+});
+
+// ─── getOffsetValues (via mapStateToProps) ────────────────────────────────────
+
+describe('getOffsetValues (via mapStateToProps)', () => {
+ const { getSelectedDate, getDeltaIntervalUnit } = require('../../modules/date/selectors');
+ const { checkHasFutureLayers, filterProjLayersWithStartDate } = require('../../modules/date/util');
+ const { getActiveLayers, subdailyLayersActive, subdailyLayers, getSubDaily, getSmallestIntervalValue } = require('../../modules/layers/selectors');
+ const { getISODateFormatted } = require('../../components/timeline/date-util');
+
+ beforeEach(() => {
+ getActiveLayers.mockReturnValue([]);
+ subdailyLayersActive.mockReturnValue(false);
+ subdailyLayers.mockReturnValue([]);
+ getSubDaily.mockReturnValue([]);
+ getSmallestIntervalValue.mockReturnValue(1440);
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ checkHasFutureLayers.mockReturnValue(false);
+ filterProjLayersWithStartDate.mockImplementation((l) => l);
+ getISODateFormatted.mockImplementation((d) => d
+ ? new Date(d).toISOString()
+ .replace(/\.\d{3}Z$/, 'Z')
+ : '');
+ });
+
+ const makeState = (screenWidth = 1200, hasSubdaily = false) => ({
+ animation: {
+ isActive: false,
+ startDate: null,
+ endDate: null,
+ gifActive: false,
+ isPlaying: false,
+ isCollapsed: false,
+ },
+ compare: { active: false, isCompareA: true, activeString: 'active' },
+ charting: { active: false },
+ config: { startDate: '1948-01-01T00:00:00Z', parameters: {}, features: {} },
+ date: {
+ appNow: new Date('2021-01-01T00:00:00Z'),
+ customDelta: 1,
+ customInterval: 3,
+ customSelected: false,
+ autoSelected: false,
+ interval: 3,
+ selected: new Date('2021-01-01T00:00:00Z'),
+ selectedB: new Date('2020-06-01T00:00:00Z'),
+ selectedZoom: 3,
+ timelineCustomModalOpen: false,
+ delta: 1,
+ },
+ events: { isAnimatingToEvent: false },
+ embed: { isEmbedModeActive: false },
+ layers: { active: { layers: [] }, activeB: { layers: [] } },
+ map: { ui: { selected: { frameState_: true } } },
+ modal: { isOpen: false, id: null },
+ proj: { id: 'geographic', selected: { id: 'geographic' } },
+ screenSize: {
+ isMobileDevice: false,
+ breakpoints: {},
+ screenWidth,
+ isMobilePhone: false,
+ isMobileTablet: false,
+ orientation: 'landscape',
+ },
+ sidebar: { activeTab: 'layers' },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: false, isKioskModeActive: false, displayStaticMap: false },
+ });
+
+ it('computes axisWidth = screenWidth - (310+10) - 88 when no subdaily', () => {
+ const result = capturedMapState(makeState(1200, false));
+ // parentOffset = 310+10 = 320, width = 1200 - 320 - 88 = 792
+ expect(result.axisWidth).toBe(792);
+ });
+
+ it('computes axisWidth with subdaily parentOffset (414+10)', () => {
+ subdailyLayersActive.mockReturnValue(true);
+ const result = capturedMapState(makeState(1200, true));
+ // parentOffset = 414+10 = 424, width = 1200 - 424 - 88 = 688
+ expect(result.axisWidth).toBe(688);
+ });
+
+ it('computes parentOffset=320 without subdaily', () => {
+ const result = capturedMapState(makeState(1200, false));
+ expect(result.parentOffset).toBe(320);
+ });
+
+ it('computes parentOffset=424 with subdaily', () => {
+ subdailyLayersActive.mockReturnValue(true);
+ const result = capturedMapState(makeState(1200, true));
+ expect(result.parentOffset).toBe(424);
+ });
+});
+
+// ─── checkLeftArrowDisabled / checkRightArrowDisabled / checkNowButtonDisabled
+
+describe('arrow and button disabled logic (via mapStateToProps)', () => {
+ const { getSelectedDate, getDeltaIntervalUnit } = require('../../modules/date/selectors');
+ const { checkHasFutureLayers, filterProjLayersWithStartDate } = require('../../modules/date/util');
+ const { getActiveLayers, subdailyLayersActive, subdailyLayers, getSubDaily, getSmallestIntervalValue } = require('../../modules/layers/selectors');
+ const { getISODateFormatted } = require('../../components/timeline/date-util');
+
+ const BASE_STATE = {
+ animation: {
+ isActive: false,
+ startDate: null,
+ endDate: null,
+ gifActive: false,
+ isPlaying: false,
+ isCollapsed: false,
+ },
+ compare: { active: false, isCompareA: true, activeString: 'active' },
+ charting: { active: false },
+ config: { startDate: '1948-01-01T00:00:00Z', parameters: {}, features: {} },
+ date: {
+ appNow: new Date('2021-01-01T00:00:00Z'),
+ customDelta: 1,
+ customInterval: 3,
+ customSelected: false,
+ autoSelected: false,
+ interval: 3,
+ selected: new Date('2021-06-15T00:00:00Z'),
+ selectedB: new Date('2020-06-01T00:00:00Z'),
+ selectedZoom: 3,
+ timelineCustomModalOpen: false,
+ delta: 1,
+ },
+ events: { isAnimatingToEvent: false },
+ embed: { isEmbedModeActive: false },
+ layers: { active: { layers: [] }, activeB: { layers: [] } },
+ map: { ui: { selected: { frameState_: true } } },
+ modal: { isOpen: false, id: null },
+ proj: { id: 'geographic', selected: { id: 'geographic' } },
+ screenSize: { isMobileDevice: false, breakpoints: {}, screenWidth: 1200, isMobilePhone: false, isMobileTablet: false, orientation: 'landscape' },
+ sidebar: { activeTab: 'layers' },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: false, isKioskModeActive: false, displayStaticMap: false },
+ };
+
+ beforeEach(() => {
+ getActiveLayers.mockReturnValue([]);
+ subdailyLayersActive.mockReturnValue(false);
+ subdailyLayers.mockReturnValue([]);
+ getSubDaily.mockReturnValue([]);
+ getSmallestIntervalValue.mockReturnValue(1440);
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ checkHasFutureLayers.mockReturnValue(false);
+ filterProjLayersWithStartDate.mockImplementation((l) => l);
+ getISODateFormatted.mockImplementation((d) => d
+ ? new Date(d).toISOString()
+ .replace(/\.\d{3}Z$/, 'Z')
+ : '');
+ });
+
+ it('rightArrowDisabled=false when autoSelected=true regardless of date', () => {
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ const result = capturedMapState({
+ ...BASE_STATE,
+ date: { ...BASE_STATE.date, autoSelected: true, selected: new Date('2021-01-01T00:00:00Z') },
+ });
+ expect(result.rightArrowDisabled).toBe(false);
+ });
+
+ it('rightArrowDisabled=true when next date would exceed timeline end', () => {
+ // selectedDate at end limit, delta=1 day
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ const result = capturedMapState({
+ ...BASE_STATE,
+ date: { ...BASE_STATE.date, autoSelected: false, selected: new Date('2021-01-01T00:00:00Z') },
+ });
+ expect(result.rightArrowDisabled).toBe(true);
+ });
+
+ it('nowButtonDisabled=false when selectedDate is before appNow', () => {
+ getSelectedDate.mockReturnValue(new Date('2020-06-01T00:00:00Z'));
+ const result = capturedMapState({
+ ...BASE_STATE,
+ date: { ...BASE_STATE.date, selected: new Date('2020-06-01T00:00:00Z') },
+ });
+ expect(result.nowButtonDisabled).toBe(false);
+ });
+});
+
+// ─── getMobileDateButtonStyle ─────────────────────────────────────────────────
+
+describe('getMobileDateButtonStyle (via rendered output)', () => {
+ it('uses default left=190 and bottom=20 in mobile mode', async () => {
+ const { container } = renderComponent({ isMobile: true });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn).toBeInTheDocument();
+ expect(btn.style.left).toBe('190px');
+ expect(btn.style.bottom).toBe('20px');
+ });
+ });
+
+ it('uses left=145 in embed+mobile mode', async () => {
+ const { container } = renderComponent({ isMobile: true, isEmbedModeActive: true });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('145px');
+ });
+ });
+
+ it('adjusts left when hasSubdailyLayers and screenWidth >= 484', async () => {
+ const { container } = renderComponent({
+ isMobile: true,
+ hasSubdailyLayers: true,
+ screenWidth: 500,
+ });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('287px');
+ });
+ });
+
+ it('uses left=10 and bottom=75 when screenWidth < 575 and not compare mode', async () => {
+ const { container } = renderComponent({
+ isMobile: true,
+ screenWidth: 400,
+ hasSubdailyLayers: false,
+ });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('10px');
+ expect(btn.style.bottom).toBe('75px');
+ });
+ });
+
+ it('uses left=112 when screenWidth < 575 and compare mode active', async () => {
+ const { container } = renderComponent({
+ isMobile: true,
+ screenWidth: 400,
+ hasSubdailyLayers: false,
+ isCompareModeActive: true,
+ });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('112px');
+ });
+ });
+});
+
+// ─── useEffect mount behavior ─────────────────────────────────────────────────
+
+describe('useEffect mount behavior', () => {
+ it('sets initialLoadComplete and renders content', async () => {
+ const { container } = renderComponent();
+ await waitFor(() => {
+ expect(container.querySelector('#timeline')).toBeInTheDocument();
+ });
+ });
+
+ it('does not set appNow interval when nowOverride=true', async () => {
+ jest.useFakeTimers();
+ const updateAppNow = jest.fn();
+ renderComponent({ nowOverride: true, updateAppNow });
+ jest.advanceTimersByTime(600001 * 10);
+ expect(updateAppNow).not.toHaveBeenCalled();
+ jest.useRealTimers();
+ });
+
+ it('does not render anything in timeline when isDistractionFreeModeActive and not yet mounted', () => {
+ // Before useEffect runs (first paint), nothing is shown;
+ // After, distraction-free section appears
+ const { container } = renderComponent({ isDistractionFreeModeActive: true });
+ // After mount effects, we should see the distraction-free section
+ waitFor(() => {
+ expect(container.querySelector('#distraction-free-timeline')).toBeInTheDocument();
+ });
+ });
+});
+
+// ─── Custom Interval Selector ─────────────────────────────────────────────────
+
+describe('CustomIntervalSelector', () => {
+ it('renders CustomIntervalSelector in desktop mode', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('custom-interval-selector')).toBeInTheDocument();
+ });
+ });
+
+ it('renders AxisTimeScaleChange in desktop mode', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('axis-timescale-change')).toBeInTheDocument();
+ });
+ });
+});
+
+// ─── AxisHoverLine / DateTooltip conditional rendering ────────────────────────
+
+describe('AxisHoverLine and DateTooltip', () => {
+ it('renders AxisHoverLine when timeline footer is visible', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('axis-hover-line')).toBeInTheDocument();
+ });
+ });
+
+ it('renders DateTooltip when timeline is not dragging', async () => {
+ const { getByTestId } = renderComponent();
+ await waitFor(() => {
+ expect(getByTestId('date-tooltip')).toBeInTheDocument();
+ });
+ });
+});
+
+// ─── TimelineAxis callback functions ─────────────────────────────────────────
+
+describe('TimelineAxis callback props', () => {
+ it('updatePositioning updates state without throwing', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updatePositioning({
+ isTimelineDragging: false,
+ position: 100,
+ transformX: 50,
+ frontDate: '2021-01-01T00:00:00Z',
+ backDate: '2021-02-01T00:00:00Z',
+ draggerPosition: 200,
+ draggerPositionB: 210,
+ draggerVisible: true,
+ draggerVisibleB: false,
+ animationStartLocation: 0,
+ animationEndLocation: 0,
+ });
+ });
+ });
+
+ it('updatePositioningOnSimpleDrag sets isTimelineDragging=true', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updatePositioningOnSimpleDrag({
+ position: 50,
+ draggerPosition: 100,
+ draggerPositionB: 110,
+ animationStartLocation: 0,
+ animationEndLocation: 0,
+ });
+ });
+ });
+
+ it('updatePositioningOnAxisStopDrag updates state', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updatePositioningOnAxisStopDrag({
+ isTimelineDragging: false,
+ position: 75,
+ transformX: 25,
+ });
+ });
+ });
+
+ it('updateTimelineMoveAndDrag sets dragging state', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updateTimelineMoveAndDrag(true);
+ });
+ });
+
+ it('showHoverOn sets showHoverLine to true', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.showHoverOn();
+ });
+ });
+
+ it('showHoverOff does not throw', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.showHoverOff();
+ });
+ });
+
+ it('showHover calls preventDefault and stopPropagation', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ const mockTarget = { getBoundingClientRect: () => ({ left: 0 }) };
+ const mockEvent = {
+ preventDefault: jest.fn(),
+ stopPropagation: jest.fn(),
+ persist: jest.fn(),
+ target: mockTarget,
+ clientX: 100,
+ };
+ act(() => {
+ capturedTimelineAxisProps.showHover(mockEvent, '2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z', 0);
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ expect(mockEvent.stopPropagation).toHaveBeenCalled();
+ });
+
+ it('onDateChange with selectedB sets draggerTimeStateB', async () => {
+ renderComponent({ draggerSelected: 'selectedB' });
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.onDateChange(new Date('2021-06-01T00:00:00Z'), 'selectedB');
+ });
+ });
+
+ it('updateDraggerDatePosition with selected dragger updates position', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updateDraggerDatePosition(
+ '2021-06-01T00:00:00Z', 'selected', 150, true, false,
+ );
+ });
+ });
+
+ it('updateDraggerDatePosition with selectedB dragger updates B position', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updateDraggerDatePosition(
+ '2021-06-01T00:00:00Z', 'selectedB', 160, true, false,
+ );
+ });
+ });
+
+ it('updateDraggerDatePosition with no newDate uses fallback', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ act(() => {
+ capturedTimelineAxisProps.updateDraggerDatePosition(null, 'selected', null, null, null);
+ });
+ });
+
+ it('debounceChangeTimeScaleWheel with deltaY>0 calls changeTimeScale down', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'month' });
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ jest.useFakeTimers();
+ act(() => {
+ capturedTimelineAxisProps.debounceChangeTimeScaleWheel({ deltaY: 10 });
+ });
+ jest.runAllTimers();
+ jest.useRealTimers();
+ expect(changeTimeScale).toHaveBeenCalledWith(1);
+ });
+
+ it('debounceChangeTimeScaleWheel with deltaY<0 calls changeTimeScale up', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'month' });
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ jest.useFakeTimers();
+ act(() => {
+ capturedTimelineAxisProps.debounceChangeTimeScaleWheel({ deltaY: -10 });
+ });
+ jest.runAllTimers();
+ jest.useRealTimers();
+ expect(changeTimeScale).toHaveBeenCalledWith(3);
+ });
+
+ it('debounceChangeTimeScaleWheel does not exceed min (year) on deltaY>0', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'year' });
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ jest.useFakeTimers();
+ act(() => {
+ capturedTimelineAxisProps.debounceChangeTimeScaleWheel({ deltaY: 10 });
+ });
+ jest.runAllTimers();
+ jest.useRealTimers();
+ expect(changeTimeScale).not.toHaveBeenCalled();
+ });
+
+ it('debounceChangeTimeScaleWheel does not exceed max (day=3) without subdaily on deltaY<0', async () => {
+ const changeTimeScale = jest.fn();
+ renderComponent({ changeTimeScale, timeScale: 'day', hasSubdailyLayers: false });
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ jest.useFakeTimers();
+ act(() => {
+ capturedTimelineAxisProps.debounceChangeTimeScaleWheel({ deltaY: -10 });
+ });
+ jest.runAllTimers();
+ jest.useRealTimers();
+ expect(changeTimeScale).not.toHaveBeenCalled();
+ });
+});
+
+// ─── DraggerContainer callback functions ──────────────────────────────────────
+
+// DraggerContainer only renders when frontDate is truthy. Call updatePositioning first.
+async function renderWithFrontDate(extraProps = {}) {
+ const result = renderComponent(extraProps);
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ await act(async () => {
+ capturedTimelineAxisProps.updatePositioning({
+ isTimelineDragging: false,
+ position: 0,
+ transformX: 0,
+ frontDate: '2021-01-01T00:00:00Z',
+ backDate: '2021-02-01T00:00:00Z',
+ draggerPosition: 100,
+ draggerPositionB: 110,
+ draggerVisible: true,
+ draggerVisibleB: false,
+ animationStartLocation: 0,
+ animationEndLocation: 0,
+ });
+ });
+ await waitFor(() => { expect(capturedDraggerContainerProps).not.toBeNull(); });
+ return result;
+}
+
+describe('DraggerContainer callback props', () => {
+ it('setDraggerVisibility updates dragger visibility', async () => {
+ await renderWithFrontDate();
+ act(() => { capturedDraggerContainerProps.setDraggerVisibility(true, false); });
+ });
+
+ it('toggleShowDraggerTime sets dragging state', async () => {
+ await renderWithFrontDate();
+ act(() => { capturedDraggerContainerProps.toggleShowDraggerTime(true); });
+ });
+});
+
+// ─── TimelineLayerCoveragePanel callback functions ───────────────────────────
+
+describe('TimelineLayerCoveragePanel setMatchingTimelineCoverage', () => {
+ it('setMatchingTimelineCoverage updates matching coverage state', async () => {
+ renderComponent();
+ await waitFor(() => { expect(capturedCoverageProps).not.toBeNull(); });
+ act(() => {
+ capturedCoverageProps.setMatchingTimelineCoverage([{ id: 'range1' }], true);
+ });
+ });
+
+ it('toggleLayerCoveragePanel opens panel and pushes GTM event', async () => {
+ const googleTagManager = require('googleTagManager');
+ renderComponent();
+ await waitFor(() => { expect(capturedCoverageProps).not.toBeNull(); });
+ act(() => {
+ capturedCoverageProps.toggleLayerCoveragePanel(true);
+ });
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'open_layer_coverage_panel' });
+ });
+
+ it('toggleLayerCoveragePanel closes panel without GTM event', async () => {
+ const googleTagManager = require('googleTagManager');
+ renderComponent();
+ await waitFor(() => { expect(capturedCoverageProps).not.toBeNull(); });
+ act(() => {
+ capturedCoverageProps.toggleLayerCoveragePanel(false);
+ });
+ expect(googleTagManager.pushEvent).not.toHaveBeenCalled();
+ });
+});
+
+// ─── TimelineRangeSelector updateAnimationDateAndLocation ────────────────────
+
+// RangeSelector renders only when isAnimationWidgetReady (requires non-zero locations).
+// Sequence: render → set frontDate via updatePositioning → rerender with animation props
+// → second useEffect fires and computes non-zero locations → RangeSelector renders.
+async function renderWithAnimationReady(extraProps = {}) {
+ const animStart = new Date('2020-01-01T00:00:00Z');
+ const animEnd = new Date('2020-12-31T00:00:00Z');
+ const { rerender, ...rest } = renderComponent();
+ await waitFor(() => { expect(capturedTimelineAxisProps).not.toBeNull(); });
+ // Set frontDate so animationDraggerDateUpdateLocal can compute real locations
+ await act(async () => {
+ capturedTimelineAxisProps.updatePositioning({
+ isTimelineDragging: false,
+ position: 0,
+ transformX: 0,
+ frontDate: '2021-01-01T00:00:00Z',
+ backDate: '2021-06-01T00:00:00Z',
+ draggerPosition: 0,
+ draggerPositionB: 0,
+ draggerVisible: true,
+ draggerVisibleB: false,
+ animationStartLocation: 0,
+ animationEndLocation: 0,
+ });
+ });
+ // Re-render with animation props → triggers second useEffect which sets locations
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ isAnimationWidgetOpen
+ animationDisabled={false}
+ animStartLocationDate={animStart}
+ animEndLocationDate={animEnd}
+ {...extraProps}
+ />,
+ );
+ });
+ return { rerender, ...rest, animStart, animEnd };
+}
+
+describe('TimelineRangeSelector updateAnimationDateAndLocation', () => {
+ it('renders TimelineRangeSelector when animation widget is ready', async () => {
+ const { getByTestId } = await renderWithAnimationReady();
+ await waitFor(() => {
+ expect(getByTestId('range-selector')).toBeInTheDocument();
+ });
+ });
+
+ it('updateAnimationDateAndLocation calls onUpdateStartAndEndDate when both dates change', async () => {
+ const onUpdateStartAndEndDate = jest.fn();
+ await renderWithAnimationReady({ onUpdateStartAndEndDate });
+ await waitFor(() => { expect(capturedRangeSelectorProps).not.toBeNull(); });
+ const newStart = new Date('2020-03-01T00:00:00Z');
+ const newEnd = new Date('2020-09-01T00:00:00Z');
+ await act(async () => {
+ capturedRangeSelectorProps.updateAnimationDateAndLocation(
+ newStart, newEnd, 100, 200, false,
+ );
+ });
+ });
+
+ it('updateAnimationDateAndLocation with no explicit locations falls back to current state', async () => {
+ await renderWithAnimationReady();
+ await waitFor(() => { expect(capturedRangeSelectorProps).not.toBeNull(); });
+ const { animStart, animEnd } = { animStart: new Date('2020-01-01T00:00:00Z'), animEnd: new Date('2020-12-31T00:00:00Z') };
+ act(() => {
+ capturedRangeSelectorProps
+ .updateAnimationDateAndLocation(animStart, animEnd, null, null, true);
+ });
+ });
+});
+
+// ─── Second useEffect — animation dates initialization ───────────────────────
+
+describe('second useEffect: animation dates init', () => {
+ it('sets animation start/end location when props first become available', async () => {
+ const animStart = new Date('2020-01-01T00:00:00Z');
+ const animEnd = new Date('2020-12-31T00:00:00Z');
+ const { container } = renderComponent({
+ animStartLocationDate: animStart,
+ animEndLocationDate: animEnd,
+ });
+ await waitFor(() => {
+ expect(container.querySelector('.timeline-container')).toBeInTheDocument();
+ });
+ });
+});
+
+// ─── componentDidUpdate-equivalent effect ────────────────────────────────────
+
+describe('componentDidUpdate effect', () => {
+ it('calls animationDraggerDateUpdateLocal when animation turns on', async () => {
+ const animStart = new Date('2020-01-01T00:00:00Z');
+ const animEnd = new Date('2020-12-31T00:00:00Z');
+ const { rerender } = renderComponent({
+ isAnimationPlaying: false,
+ animStartLocationDate: animStart,
+ animEndLocationDate: animEnd,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ isAnimationPlaying
+ animStartLocationDate={animStart}
+ animEndLocationDate={animEnd}
+ />,
+ );
+ });
+ });
+
+ it('calls animationDraggerDateUpdateLocal when gif turns on', async () => {
+ const animStart = new Date('2020-01-01T00:00:00Z');
+ const animEnd = new Date('2020-12-31T00:00:00Z');
+ const { rerender } = renderComponent({
+ isGifActive: false,
+ animStartLocationDate: animStart,
+ animEndLocationDate: animEnd,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ isGifActive
+ animStartLocationDate={animStart}
+ animEndLocationDate={animEnd}
+ />,
+ );
+ });
+ });
+
+ it('calls changeAutoInterval when tempo product is removed', async () => {
+ const changeAutoInterval = jest.fn();
+ const { rerender } = renderComponent({
+ hasTempoProduct: true,
+ changeAutoInterval,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ hasTempoProduct={false}
+ changeAutoInterval={changeAutoInterval}
+ />);
+ });
+ await waitFor(() => {
+ expect(changeAutoInterval).toHaveBeenCalled();
+ });
+ });
+
+ it('calls changeCustomInterval when subdaily removed with subdaily interval', async () => {
+ const changeCustomInterval = jest.fn();
+ const { rerender } = renderComponent({
+ hasSubdailyLayers: true,
+ customInterval: 4,
+ changeCustomInterval,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ hasSubdailyLayers={false}
+ customInterval={4}
+ changeCustomInterval={changeCustomInterval}
+ />,
+ );
+ });
+ await waitFor(() => {
+ expect(changeCustomInterval).toHaveBeenCalled();
+ });
+ });
+
+ it('calls changeTimeScale(4) when subdaily layers are added', async () => {
+ const changeTimeScale = jest.fn();
+ const { rerender } = renderComponent({ hasSubdailyLayers: false, changeTimeScale });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(<Timeline {...defaultProps} hasSubdailyLayers changeTimeScale={changeTimeScale} />);
+ });
+ await waitFor(() => {
+ expect(changeTimeScale).toHaveBeenCalledWith(4);
+ });
+ });
+
+ it('updates draggerTimeState when dateA changes', async () => {
+ const { rerender } = renderComponent({ dateA: '2021-01-01T00:00:00Z' });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(<Timeline {...defaultProps} dateA="2021-06-01T00:00:00Z" />);
+ });
+ });
+
+ it('updates draggerTimeStateB when dateB changes', async () => {
+ const { rerender } = renderComponent({ dateB: '2020-06-01T00:00:00Z' });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(<Timeline {...defaultProps} dateB="2020-12-01T00:00:00Z" />);
+ });
+ });
+
+ it('calls changeAutoInterval(true) when subdailyCount changes and hasTempoProduct', async () => {
+ const changeAutoInterval = jest.fn();
+ const { rerender } = renderComponent({
+ subDailyLayersList: [{ id: 'l1' }],
+ hasTempoProduct: true,
+ changeAutoInterval,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ subDailyLayersList={[{ id: 'l1' }, { id: 'l2' }]}
+ hasTempoProduct
+ changeAutoInterval={changeAutoInterval}
+ />,
+ );
+ });
+ await waitFor(() => {
+ expect(changeAutoInterval).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it('calls changeCustomInterval when subdailyCount changes and isSubDaily', async () => {
+ const changeCustomInterval = jest.fn();
+ const { rerender } = renderComponent({
+ subDailyLayersList: [{ id: 'l1' }],
+ newCustomDelta: 60,
+ hasTempoProduct: false,
+ changeCustomInterval,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ subDailyLayersList={[{ id: 'l1' }, { id: 'l2' }]}
+ newCustomDelta={60}
+ hasTempoProduct={false}
+ changeCustomInterval={changeCustomInterval}
+ />,
+ );
+ });
+ await waitFor(() => {
+ expect(changeCustomInterval).toHaveBeenCalledWith(60, 5);
+ });
+ });
+
+ it('updates animation dragger when widget is open and dates change', async () => {
+ const animStart = new Date('2020-01-01T00:00:00Z');
+ const animEnd = new Date('2020-12-31T00:00:00Z');
+ const animStart2 = new Date('2020-03-01T00:00:00Z');
+ const { rerender } = renderComponent({
+ isAnimationWidgetOpen: true,
+ animStartLocationDate: animStart,
+ animEndLocationDate: animEnd,
+ });
+ await waitFor(() => {});
+ await act(async () => {
+ rerender(
+ <Timeline
+ {...defaultProps}
+ isAnimationWidgetOpen
+ animStartLocationDate={animStart2}
+ animEndLocationDate={animEnd}
+ />,
+ );
+ });
+ });
+});
+
+// ─── Keyboard ArrowLeft / ArrowRight ─────────────────────────────────────────
+
+describe('Keyboard ArrowLeft and ArrowRight', () => {
+ it('ArrowLeft key calls handleArrowDateChange(-1)', async () => {
+ const selectDate = jest.fn();
+ const { getNextTimeSelection } = require('../../modules/date/util');
+ renderComponent({ selectDate, leftArrowDisabled: false });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowLeft' });
+ });
+ expect(getNextTimeSelection).toHaveBeenCalled();
+ });
+
+ it('ArrowRight key calls handleArrowDateChange(1)', async () => {
+ const selectDate = jest.fn();
+ const { getNextTimeSelection } = require('../../modules/date/util');
+ renderComponent({ selectDate, rightArrowDisabled: false });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowRight' });
+ });
+ expect(getNextTimeSelection).toHaveBeenCalled();
+ });
+
+ it('ArrowLeft does not act when leftArrowDisabled=true', async () => {
+ const { getNextTimeSelection } = require('../../modules/date/util');
+ renderComponent({ leftArrowDisabled: true });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowLeft' });
+ });
+ expect(getNextTimeSelection).not.toHaveBeenCalled();
+ });
+
+ it('ArrowLeft uses activeString=activeB dateB when not active', async () => {
+ const { getNextImageryDelta } = require('../../modules/date/util');
+ renderComponent({
+ autoSelected: true,
+ subDailyLayersList: [{ id: 'l1' }],
+ activeString: 'activeB',
+ leftArrowDisabled: false,
+ });
+ await waitFor(() => {});
+ act(() => {
+ fireEvent.keyDown(document, { key: 'ArrowLeft' });
+ });
+ expect(getNextImageryDelta).toHaveBeenCalled();
+ });
+});
+
+// ─── getMobileDateButtonStyle — missing branches ──────────────────────────────
+
+describe('getMobileDateButtonStyle — embed+subdaily and embed+small branches', () => {
+ it('uses left=220 when hasSubdailyLayers + isEmbedModeActive + screenWidth>=484', async () => {
+ const { container } = renderComponent({
+ isMobile: true,
+ hasSubdailyLayers: true,
+ isEmbedModeActive: true,
+ screenWidth: 600,
+ });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('220px');
+ });
+ });
+
+ it('uses left=10 and bottom=56 when screenWidth<575 + isEmbedModeActive + no compare', async () => {
+ const { container } = renderComponent({
+ isMobile: true,
+ screenWidth: 400,
+ isEmbedModeActive: true,
+ isCompareModeActive: false,
+ });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('10px');
+ expect(btn.style.bottom).toBe('56px');
+ });
+ });
+
+ it('uses left=90 when screenWidth<575 + isEmbedModeActive + compare active', async () => {
+ const { container } = renderComponent({
+ isMobile: true,
+ screenWidth: 400,
+ isEmbedModeActive: true,
+ isCompareModeActive: true,
+ });
+ await waitFor(() => {
+ const btn = container.querySelector('.mobile-date-change-arrows-btn');
+ expect(btn.style.left).toBe('90px');
+ });
+ });
+});
+
+// ─── mapDispatchToProps — missing entries ─────────────────────────────────────
+
+describe('mapDispatchToProps selectInterval and toggleCustomModal', () => {
+ it('selectInterval dispatches correct action', () => {
+ const dispatch = jest.fn();
+ const { selectInterval } = capturedMapDispatch(dispatch);
+ selectInterval(1, 3, false);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'SELECT_INTERVAL', delta: 1, ts: 3, cs: false });
+ });
+
+ it('toggleCustomModal dispatches correct action', () => {
+ const dispatch = jest.fn();
+ const { toggleCustomModal } = capturedMapDispatch(dispatch);
+ toggleCustomModal(true, 'TIMELINE');
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_CUSTOM_MODAL', open: true, by: 'TIMELINE' });
+ });
+});
+
+// ─── getTimelineEndDateLimit with future layers ───────────────────────────────
+
+describe('getTimelineEndDateLimit via mapStateToProps', () => {
+ const { getSelectedDate, getDeltaIntervalUnit } = require('../../modules/date/selectors');
+ const {
+ checkHasFutureLayers, filterProjLayersWithStartDate,
+ } = require('../../modules/date/util');
+ const {
+ getActiveLayers, subdailyLayersActive, subdailyLayers,
+ getSubDaily, getSmallestIntervalValue, dateRange: getDateRange,
+ } = require('../../modules/layers/selectors');
+ const { getISODateFormatted } = require('../../components/timeline/date-util');
+
+ const appNow = new Date('2021-01-01T00:00:00Z');
+
+ const makeFutureState = (overrides = {}) => ({
+ animation: {
+ isActive: false,
+ startDate: null,
+ endDate: null,
+ gifActive: false,
+ isPlaying: false,
+ isCollapsed: false,
+ },
+ compare: { active: false, isCompareA: true, activeString: 'active' },
+ charting: { active: false },
+ config: { startDate: '1948-01-01T00:00:00Z', parameters: {}, features: {} },
+ date: {
+ appNow,
+ customDelta: 1,
+ customInterval: 3,
+ customSelected: false,
+ autoSelected: false,
+ interval: 3,
+ selected: new Date('2021-01-01T00:00:00Z'),
+ selectedB: new Date('2020-06-01T00:00:00Z'),
+ selectedZoom: 3,
+ timelineCustomModalOpen: false,
+ delta: 1,
+ },
+ events: { isAnimatingToEvent: false },
+ embed: { isEmbedModeActive: false },
+ layers: { active: { layers: [] }, activeB: { layers: [] } },
+ map: { ui: { selected: { frameState_: true } } },
+ modal: { isOpen: false, id: null },
+ proj: { id: 'geographic', selected: {} },
+ screenSize: { isMobileDevice: false, breakpoints: {}, screenWidth: 1200, isMobilePhone: false, isMobileTablet: false, orientation: 'landscape' },
+ sidebar: { activeTab: 'layers' },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: false, isKioskModeActive: false, displayStaticMap: false },
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ getActiveLayers.mockReturnValue([]);
+ subdailyLayersActive.mockReturnValue(false);
+ subdailyLayers.mockReturnValue([]);
+ getSubDaily.mockReturnValue([]);
+ getSmallestIntervalValue.mockReturnValue(1440);
+ getSelectedDate.mockReturnValue(new Date('2021-01-01T00:00:00Z'));
+ getDeltaIntervalUnit.mockReturnValue({ delta: 1, unit: 'day', interval: 3 });
+ filterProjLayersWithStartDate.mockImplementation((l) => l);
+ getISODateFormatted.mockImplementation((d) => d
+ ? new Date(d).toISOString()
+ .replace(/\.\d{3}Z$/, 'Z')
+ : '');
+ });
+
+ it('uses compare layer ranges when compare is active', () => {
+ checkHasFutureLayers.mockReturnValue(true);
+ getDateRange.mockReturnValue(null);
+ const result = capturedMapState(makeFutureState({
+ compare: { active: true, isCompareA: true, activeString: 'active' },
+ }));
+ expect(result.timelineEndDateLimit).toBeDefined();
+ });
+
+ it('uses layerDateRange.end when it exceeds appNow', () => {
+ checkHasFutureLayers.mockReturnValue(true);
+ const futureDate = new Date('2022-01-01T00:00:00Z');
+ getDateRange.mockReturnValue({ end: futureDate });
+ const util = require('../../util/util').default;
+ util.roundTimeQuarterHour.mockImplementation((d) => d);
+ const result = capturedMapState(makeFutureState());
+ expect(result.timelineEndDateLimit).toBeDefined();
+ });
+});
+
+// ─── preventDefaultFunc (wheel on timeline-container) ────────────────────────
+
+describe('preventDefaultFunc on timeline-container wheel event', () => {
+ it('wheel event on .timeline-container calls preventDefault', async () => {
+ const { container } = renderComponent();
+ await waitFor(() => { expect(container.querySelector('.timeline-container')).toBeInTheDocument(); });
+ const wheelEvent = new Event('wheel');
+ const preventDefault = jest.fn();
+ wheelEvent.preventDefault = preventDefault;
+ // The mount effect attaches the listener via document.querySelector,
+ // which finds the persistent container (first matching element in DOM)
+ persistentTimelineContainer.dispatchEvent(wheelEvent);
+ // The handler calls e.preventDefault()
+ expect(preventDefault).toHaveBeenCalled();
+ });
+});
+
+// ─── checkAndUpdateAppNow via interval ───────────────────────────────────────
+
+describe('checkAndUpdateAppNow', () => {
+ it('calls updateAppNow after 10-minute interval fires', async () => {
+ jest.useFakeTimers();
+ const updateAppNow = jest.fn();
+ renderComponent({ nowOverride: false, updateAppNow });
+ // Trigger the 10-minute interval and flush the resulting Promise chain
+ await act(async () => {
+ jest.advanceTimersByTime(600001);
+ await Promise.resolve();
+ });
+ jest.useRealTimers();
+ await waitFor(() => {
+ expect(updateAppNow).toHaveBeenCalled();
+ });
+ });
});
diff --git a/web/js/containers/toolbar.test.js b/web/js/containers/toolbar.test.js
index 6fee39742..6d19e2a7b 100644
--- a/web/js/containers/toolbar.test.js
+++ b/web/js/containers/toolbar.test.js
@@ -1,3 +1,537 @@
-test('toolbar container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import {
+ render, fireEvent, act, waitFor,
+} from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: (props) => <i data-icon={String(props.icon)} />,
+}));
+
+jest.mock('./image-download', () => () => <div />);
+jest.mock('./projection', () => () => <div />);
+jest.mock('./info', () => () => <div />);
+jest.mock('./share', () => () => <div />);
+jest.mock('./error-boundary', () => ({ children }) => <div>{children}</div>);
+jest.mock('../components/util/hover-tooltip', () => () => <span data-testid="hover-tooltip" />);
+jest.mock('../components/image-download/notify', () => () => <div />);
+jest.mock('../components/location-search/location-search', () => () => <div />);
+jest.mock('../components/about/about', () => () => <div />);
+
+jest.mock('../modules/modal/actions', () => ({
+ openCustomContent: jest.fn((id, params) => ({ type: 'OPEN_CUSTOM_CONTENT', id, params })),
+ onToggle: jest.fn(() => ({ type: 'MODAL_TOGGLE' })),
+ toggleAboutModal: jest.fn((isOpen) => ({ type: 'TOGGLE_ABOUT_MODAL', isOpen })),
+}));
+
+jest.mock('../modules/ui/actions', () => ({
+ __esModule: true,
+ default: jest.fn(() => ({ type: 'TOGGLE_DISTRACTION_FREE' })),
+}));
+
+jest.mock('../modules/notifications/actions', () => ({
+ requestNotifications: jest.fn((location) => ({ type: 'REQUEST_NOTIFICATIONS', location })),
+ setNotifications: jest.fn((notifications) => ({ type: 'SET_NOTIFICATIONS', notifications })),
+}));
+
+jest.mock('../modules/palettes/actions', () => ({
+ clearCustomsSnapshot: jest.fn(() => ({ type: 'CLEAR_CUSTOMS_SNAPSHOT' })),
+ refreshPalettes: jest.fn((palettes) => ({ type: 'REFRESH_PALETTES', palettes })),
+}));
+
+jest.mock('../modules/map/actions', () => ({
+ clearRotate: jest.fn(() => ({ type: 'CLEAR_ROTATE' })),
+ refreshRotation: jest.fn((rotation) => ({ type: 'REFRESH_ROTATION', rotation })),
+}));
+
+jest.mock('../modules/layers/actions', () => ({
+ showLayers: jest.fn((layers) => ({ type: 'SHOW_LAYERS', layers })),
+ hideLayers: jest.fn((layers) => ({ type: 'HIDE_LAYERS', layers })),
+}));
+
+jest.mock('../modules/image-download/constants', () => ({
+ notificationWarnings: {
+ palette: 'palette-warning',
+ rotate: 'rotate-warning',
+ },
+}));
+
+jest.mock('../modules/palettes/util', () => ({
+ hasCustomPaletteInActiveProjection: jest.fn(() => false),
+}));
+
+jest.mock('../modules/location-search/actions', () => ({
+ toggleShowLocationSearch: jest.fn(() => ({ type: 'TOGGLE_SHOW_LOCATION_SEARCH' })),
+ toggleDialogVisible: jest.fn((visible) => ({ type: 'TOGGLE_DIALOG_VISIBLE', visible })),
+}));
+
+jest.mock('../modules/location-search/util', () => ({
+ isLocationSearchFeatureEnabled: jest.fn(() => true),
+}));
+
+jest.mock('../modules/layers/selectors', () => ({
+ getAllActiveLayers: jest.fn(() => []),
+}));
+
+jest.mock('../modules/image-download/util', () => ({
+ hasNonDownloadableVisibleLayer: jest.fn(() => false),
+ getNonDownloadableLayerWarning: jest.fn(() => 'non-downloadable-warning'),
+ getNonDownloadableLayers: jest.fn(() => [{ id: 'bad-layer' }]),
+}));
+
+const ToolbarContainer = require('./toolbar').default;
+const {
+ openCustomContent,
+ onToggle,
+ toggleAboutModal,
+} = require('../modules/modal/actions');
+const {
+ requestNotifications: requestNotificationsAction,
+ setNotifications,
+} = require('../modules/notifications/actions');
+const { clearCustomsSnapshot, refreshPalettes } = require('../modules/palettes/actions');
+const { clearRotate, refreshRotation } = require('../modules/map/actions');
+const { showLayers, hideLayers } = require('../modules/layers/actions');
+const { hasCustomPaletteInActiveProjection } = require('../modules/palettes/util');
+const { isLocationSearchFeatureEnabled } = require('../modules/location-search/util');
+const { getAllActiveLayers } = require('../modules/layers/selectors');
+const { hasNonDownloadableVisibleLayer, getNonDownloadableLayers } = require('../modules/image-download/util');
+
+const defaultProps = {
+ activePalettes: {},
+ config: { features: {}, parameters: {}, ui: { projections: {} } },
+ faSize: '1x',
+ hasCustomPalette: false,
+ hasNonDownloadableLayer: false,
+ isAboutOpen: false,
+ isCompareActive: false,
+ isChartingActive: false,
+ isDistractionFreeModeActive: false,
+ isKioskModeActive: false,
+ isLocationSearchExpanded: false,
+ isImageDownloadActive: true,
+ isProjectionSwitchActive: true,
+ isMobile: false,
+ isRotated: false,
+ modalIsOpen: false,
+ notificationContentNumber: 0,
+ notificationType: '',
+ notify: jest.fn(() => Promise.resolve()),
+ openModal: jest.fn(),
+ openAboutModal: jest.fn(),
+ refreshStateAfterImageDownload: jest.fn(),
+ requestNotifications: jest.fn(),
+ rotation: 0,
+ shouldBeCollapsed: false,
+ toggleDialogVisible: jest.fn(),
+ toggleDistractionFreeModeAction: jest.fn(),
+ toggleShowLocationSearch: jest.fn(),
+ visibleLayersForProj: [],
+};
+
+const renderComponent = (props = {}) => render(
+ <ToolbarContainer {...defaultProps} {...props} />,
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ isLocationSearchFeatureEnabled.mockReturnValue(true);
+});
+
+describe('toolbar buttons', () => {
+ it('renders all main buttons', () => {
+ const { container } = renderComponent();
+ expect(container.querySelector('#wv-share-button')).toBeInTheDocument();
+ expect(container.querySelector('#wv-proj-button')).toBeInTheDocument();
+ expect(container.querySelector('#wv-image-button')).toBeInTheDocument();
+ expect(container.querySelector('#wv-info-button')).toBeInTheDocument();
+ expect(container.querySelector('#wv-location-search-button')).toBeInTheDocument();
+ expect(container.querySelector('#wv-exit-distraction-free-mode-button')).toBeNull();
+ });
+
+ it('hides buttons and shows the exit button in distraction free mode', () => {
+ const { container } = renderComponent({ isDistractionFreeModeActive: true });
+ expect(container.querySelector('#wv-share-button')).toBeNull();
+ expect(container.querySelector('#wv-proj-button')).toBeNull();
+ expect(container.querySelector('#wv-exit-distraction-free-mode-button')).toBeInTheDocument();
+ });
+
+ it('hides the exit distraction free button in kiosk mode', () => {
+ const { container } = renderComponent({
+ isDistractionFreeModeActive: true,
+ isKioskModeActive: true,
+ });
+ expect(container.querySelector('#wv-exit-distraction-free-mode-button')).toBeNull();
+ });
+
+ it('exit distraction free button toggles distraction free mode', () => {
+ const toggleDistractionFreeModeAction = jest.fn();
+ const { container } = renderComponent({
+ isDistractionFreeModeActive: true,
+ toggleDistractionFreeModeAction,
+ });
+ fireEvent.click(container.querySelector('#wv-exit-distraction-free-mode-button'));
+ expect(toggleDistractionFreeModeAction).toHaveBeenCalled();
+ });
+
+ it('share button opens the share modal', () => {
+ const openModal = jest.fn();
+ const { container } = renderComponent({ openModal });
+ fireEvent.click(container.querySelector('#wv-share-button'));
+ expect(openModal).toHaveBeenCalledWith('TOOLBAR_SHARE', expect.objectContaining({
+ headerText: 'Share',
+ }));
+ });
+
+ it('projection button opens the projection modal', () => {
+ const openModal = jest.fn();
+ const { container } = renderComponent({ openModal });
+ fireEvent.click(container.querySelector('#wv-proj-button'));
+ expect(openModal).toHaveBeenCalledWith('TOOLBAR_PROJECTION', expect.anything());
+ });
+
+ it('projection button is hidden without config.ui.projections', () => {
+ const { container } = renderComponent({ config: { features: {}, parameters: {} } });
+ expect(container.querySelector('#wv-proj-button')).toBeNull();
+ });
+
+ it('projection button is disabled when projection switching is inactive', () => {
+ const { container } = renderComponent({ isProjectionSwitchActive: false });
+ expect(container.querySelector('#wv-proj-button')).toBeDisabled();
+ });
+
+ it('info button opens the info modal', () => {
+ const openModal = jest.fn();
+ const { container } = renderComponent({ openModal });
+ fireEvent.click(container.querySelector('#wv-info-button'));
+ expect(openModal).toHaveBeenCalledWith('TOOLBAR_INFO', expect.anything());
+ });
+
+ it('info button shows the notification status class', () => {
+ const { container } = renderComponent({ notificationType: 'alert', notificationContentNumber: 4 });
+ const btn = container.querySelector('#wv-info-button');
+ expect(btn.className).toContain('wv-status-alert');
+ expect(btn.getAttribute('data-content')).toBe('4');
+ });
+
+ it('snapshot button is disabled when image download is inactive', () => {
+ const { container } = renderComponent({ isImageDownloadActive: false });
+ expect(container.querySelector('#wv-image-button')).toBeDisabled();
+ });
+});
+
+describe('location search button', () => {
+ it('is not rendered when the feature is disabled', () => {
+ isLocationSearchFeatureEnabled.mockReturnValue(false);
+ const { container } = renderComponent();
+ expect(container.querySelector('#wv-location-search-button')).toBeNull();
+ });
+
+ it('toggles the search bar on desktop', () => {
+ const toggleShowLocationSearch = jest.fn();
+ const { container } = renderComponent({ toggleShowLocationSearch });
+ fireEvent.click(container.querySelector('#wv-location-search-button'));
+ expect(toggleShowLocationSearch).toHaveBeenCalled();
+ });
+
+ it('opens the mobile modal on mobile', () => {
+ const openModal = jest.fn();
+ const { container } = renderComponent({ isMobile: true, openModal });
+ fireEvent.click(container.querySelector('#wv-location-search-button'));
+ expect(openModal).toHaveBeenCalledWith('TOOLBAR_LOCATION_SEARCH_MOBILE', expect.anything());
+ });
+
+ it('is hidden on desktop when search is expanded and not collapsed', () => {
+ const { container } = renderComponent({ isLocationSearchExpanded: true });
+ expect(container.querySelector('#wv-location-search-button')).toBeNull();
+ });
+});
+
+describe('snapshot workflow (openImageDownload)', () => {
+ it('opens the snapshot modal directly with no special conditions', async () => {
+ const openModal = jest.fn();
+ const toggleDialogVisible = jest.fn();
+ const refreshStateAfterImageDownload = jest.fn();
+ const { container } = renderComponent({
+ openModal, toggleDialogVisible, refreshStateAfterImageDownload,
+ });
+ await act(async () => {
+ fireEvent.click(container.querySelector('#wv-image-button'));
+ });
+ expect(toggleDialogVisible).toHaveBeenCalledWith(false);
+ expect(openModal).toHaveBeenCalledWith('TOOLBAR_SNAPSHOT', expect.objectContaining({
+ headerText: 'Take a Snapshot',
+ onClose: expect.any(Function),
+ }));
+ const { onClose } = openModal.mock.calls.at(-1)[1];
+ onClose();
+ expect(refreshStateAfterImageDownload).toHaveBeenCalledWith(undefined, 0, null);
+ });
+
+ it('notifies before opening when palettes, rotation and layers need resets', async () => {
+ const notify = jest.fn(() => Promise.resolve());
+ const openModal = jest.fn();
+ const refreshStateAfterImageDownload = jest.fn();
+ const activePalettes = { layer: { id: 'p' } };
+ const { container } = renderComponent({
+ notify,
+ openModal,
+ refreshStateAfterImageDownload,
+ hasCustomPalette: true,
+ isRotated: true,
+ rotation: 45,
+ hasNonDownloadableLayer: true,
+ activePalettes,
+ visibleLayersForProj: [{ id: 'vl' }],
+ });
+ await act(async () => {
+ fireEvent.click(container.querySelector('#wv-image-button'));
+ });
+ expect(notify).toHaveBeenCalledTimes(3);
+ expect(notify).toHaveBeenCalledWith('palette', clearCustomsSnapshot, [{ id: 'vl' }]);
+ expect(notify).toHaveBeenCalledWith('rotate', clearRotate, [{ id: 'vl' }]);
+ expect(notify).toHaveBeenCalledWith('layers', hideLayers, [{ id: 'vl' }]);
+ const { onClose } = openModal.mock.calls.at(-1)[1];
+ onClose();
+ expect(refreshStateAfterImageDownload).toHaveBeenCalledWith(
+ activePalettes, 45, [{ id: 'bad-layer' }],
+ );
+ });
+});
+
+describe('notification requests', () => {
+ it('does not request notifications without the feature flag', () => {
+ const requestNotifications = jest.fn();
+ renderComponent({ requestNotifications });
+ expect(requestNotifications).not.toHaveBeenCalled();
+ });
+
+ it('requests UAT notifications on test domains', () => {
+ const requestNotifications = jest.fn();
+ renderComponent({
+ requestNotifications,
+ config: {
+ features: { notification: { url: 'https://status.nasa.gov' } },
+ parameters: {},
+ },
+ });
+ // jsdom origin is localhost, a test domain
+ expect(requestNotifications).toHaveBeenCalledWith('https://status.nasa.gov?client=Worldview%20(UAT)');
+ });
+
+ it('uses mock alerts parameter when configured', () => {
+ const requestNotifications = jest.fn();
+ renderComponent({
+ requestNotifications,
+ config: {
+ features: { notification: { url: 'https://status.nasa.gov' } },
+ parameters: { mockAlerts: 'all' },
+ },
+ });
+ expect(requestNotifications).toHaveBeenCalledWith('mock/notify_all.json');
+ });
+
+ it('uses notificationURL parameter when configured', () => {
+ const requestNotifications = jest.fn();
+ renderComponent({
+ requestNotifications,
+ config: {
+ features: { notification: { url: 'https://status.nasa.gov' } },
+ parameters: { notificationURL: 'custom.domain' },
+ },
+ });
+ expect(requestNotifications).toHaveBeenCalledWith('https://status.nasa.gov?domain=custom.domain');
+ });
+});
+
+describe('about modal lifecycle', () => {
+ it('opens the about modal on mount when isAboutOpen', () => {
+ const openAboutModal = jest.fn();
+ renderComponent({ isAboutOpen: true, openAboutModal });
+ expect(openAboutModal).toHaveBeenCalled();
+ });
+
+ it('re-opens the about modal when the modal open state changes', () => {
+ const openAboutModal = jest.fn();
+ const { rerender } = renderComponent({ isAboutOpen: true, openAboutModal });
+ openAboutModal.mockClear();
+ rerender(
+ <ToolbarContainer
+ {...defaultProps}
+ isAboutOpen
+ openAboutModal={openAboutModal}
+ modalIsOpen
+ />,
+ );
+ expect(openAboutModal).toHaveBeenCalled();
+ });
+});
+
+describe('mapStateToProps', () => {
+ const makeState = (overrides = {}) => ({
+ animation: { gifActive: false },
+ compare: { active: false, activeString: 'active' },
+ charting: { active: false },
+ events: { isAnimatingToEvent: false },
+ locationSearch: { isExpanded: false },
+ map: { rotation: 0, ui: { selected: {} } },
+ measure: { isActive: false },
+ modal: { isOpen: false, id: null },
+ modalAbout: { isOpen: false },
+ notifications: { numberUnseen: 2, type: 'alert' },
+ palettes: { active: { p: 1 } },
+ proj: { id: 'geographic' },
+ screenSize: { isMobileDevice: false },
+ sidebar: { activeTab: 'layers' },
+ ui: { isDistractionFreeModeActive: false, isKioskModeActive: false },
+ config: { features: {} },
+ ...overrides,
+ });
+
+ it('maps toolbar state for desktop', () => {
+ const result = capturedMapState(makeState());
+ expect(result.faSize).toBe('1x');
+ expect(result.isImageDownloadActive).toBe(true);
+ expect(result.isProjectionSwitchActive).toBe(true);
+ expect(result.isRotated).toBe(false);
+ expect(result.notificationType).toBe('alert');
+ expect(result.notificationContentNumber).toBe(2);
+ expect(result.shouldBeCollapsed).toBe(false);
+ expect(getAllActiveLayers).toHaveBeenCalled();
+ expect(hasNonDownloadableVisibleLayer).toHaveBeenCalled();
+ expect(hasCustomPaletteInActiveProjection).toHaveBeenCalled();
+ });
+
+ it('uses 2x icons on mobile', () => {
+ const result = capturedMapState(makeState({ screenSize: { isMobileDevice: true } }));
+ expect(result.faSize).toBe('2x');
+ });
+
+ it('disables image download in compare mode', () => {
+ const result = capturedMapState(makeState({ compare: { active: true, activeString: 'active' } }));
+ expect(result.isImageDownloadActive).toBe(false);
+ });
+
+ it('disables image download when the download tab is active', () => {
+ const result = capturedMapState(makeState({ sidebar: { activeTab: 'download' } }));
+ expect(result.isImageDownloadActive).toBe(false);
+ });
+
+ it('disables projection switching while animating to an event', () => {
+ const result = capturedMapState(makeState({ events: { isAnimatingToEvent: true } }));
+ expect(result.isProjectionSwitchActive).toBe(false);
+ });
+
+ it('collapses when the snapshot modal is open', () => {
+ const result = capturedMapState(makeState({ modal: { isOpen: true, id: 'TOOLBAR_SNAPSHOT' } }));
+ expect(result.shouldBeCollapsed).toBe(true);
+ });
+
+ it('detects rotation', () => {
+ const result = capturedMapState(makeState({ map: { rotation: 30, ui: { selected: {} } } }));
+ expect(result.isRotated).toBe(true);
+ expect(result.rotation).toBe(30);
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('toggleDistractionFreeModeAction dispatches the toggle', () => {
+ props.toggleDistractionFreeModeAction();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_DISTRACTION_FREE' });
+ });
+
+ it('toggleDialogVisible dispatches visibility', () => {
+ props.toggleDialogVisible(false);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_DIALOG_VISIBLE', visible: false });
+ });
+
+ it('toggleShowLocationSearch dispatches the toggle', () => {
+ props.toggleShowLocationSearch();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_SHOW_LOCATION_SEARCH' });
+ });
+
+ it('refreshStateAfterImageDownload restores palettes, rotation and layers', () => {
+ props.refreshStateAfterImageDownload({ p: 1 }, 99, [{ id: 'l' }]);
+ expect(refreshPalettes).toHaveBeenCalledWith({ p: 1 });
+ expect(refreshRotation).toHaveBeenCalledWith(99);
+ expect(showLayers).toHaveBeenCalledWith([{ id: 'l' }]);
+ expect(dispatch).toHaveBeenCalledTimes(3);
+ });
+
+ it('refreshStateAfterImageDownload skips falsy values', () => {
+ props.refreshStateAfterImageDownload(undefined, 0, null);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('openModal dispatches openCustomContent', () => {
+ props.openModal('SOME_KEY', { a: 1 });
+ expect(openCustomContent).toHaveBeenCalledWith('SOME_KEY', { a: 1 });
+ });
+
+ it('openAboutModal opens the about modal and toggles on close', () => {
+ props.openAboutModal();
+ expect(openCustomContent).toHaveBeenCalledWith('ABOUT_MODAL', expect.objectContaining({
+ headerText: 'About',
+ }));
+ const { onClose } = openCustomContent.mock.calls.at(-1)[1];
+ onClose();
+ expect(toggleAboutModal).toHaveBeenCalledWith(false);
+ });
+
+ it('notify opens a confirmation modal and resolves on accept', async () => {
+ const promise = props.notify('palette', clearCustomsSnapshot, []);
+ expect(openCustomContent).toHaveBeenCalledWith('image_download_notify_palette', expect.objectContaining({
+ headerText: 'Notify',
+ }));
+ const { bodyComponentProps } = openCustomContent.mock.calls.at(-1)[1];
+ expect(bodyComponentProps.bodyText).toBe('palette-warning');
+ bodyComponentProps.cancel();
+ expect(onToggle).toHaveBeenCalled();
+ bodyComponentProps.accept();
+ expect(clearCustomsSnapshot).toHaveBeenCalled();
+ await promise;
+ });
+
+ it('notify uses the non-downloadable layer warning for layer type', () => {
+ props.notify('layers', hideLayers, [{ id: 'vl' }]);
+ const { bodyComponentProps } = openCustomContent.mock.calls.at(-1)[1];
+ expect(getNonDownloadableLayers).toHaveBeenCalledWith([{ id: 'vl' }]);
+ expect(bodyComponentProps.bodyText).toBe('non-downloadable-warning');
+ bodyComponentProps.accept();
+ expect(hideLayers).toHaveBeenCalledWith([{ id: 'bad-layer' }]);
+ });
+
+ it('requestNotifications dispatches and stores returned notifications', async () => {
+ dispatch.mockReturnValueOnce(Promise.resolve('{"notifications": [{"id": 1}]}'));
+ props.requestNotifications('some/url');
+ expect(requestNotificationsAction).toHaveBeenCalledWith('some/url');
+ await waitFor(() => {
+ expect(setNotifications).toHaveBeenCalledWith([{ id: 1 }]);
+ });
+ });
+
+ it('requestNotifications ignores responses without notifications', async () => {
+ dispatch.mockReturnValueOnce(Promise.resolve('{}'));
+ props.requestNotifications('some/url');
+ await act(async () => {});
+ expect(setNotifications).not.toHaveBeenCalled();
+ });
});
diff --git a/web/js/containers/tour.test.js b/web/js/containers/tour.test.js
index d5d98ea16..a55772f5a 100644
--- a/web/js/containers/tour.test.js
+++ b/web/js/containers/tour.test.js
@@ -1,3 +1,650 @@
-test('tour container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import {
+ render, act, waitFor,
+} from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+let capturedMapDispatch;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ capturedMapDispatch = mapDispatch;
+ return (Component) => Component;
+ },
+}));
+
+let mockTourStartProps = null;
+jest.mock('../components/tour/modal-tour-start', () => (props) => {
+ mockTourStartProps = props;
+ return <div data-testid="tour-start" />;
+});
+
+let mockTourInProgressProps = null;
+jest.mock('../components/tour/modal-tour-in-progress', () => (props) => {
+ mockTourInProgressProps = props;
+ return <div data-testid="tour-in-progress" />;
+});
+
+let mockTourCompleteProps = null;
+jest.mock('../components/tour/modal-tour-complete', () => (props) => {
+ mockTourCompleteProps = props;
+ return <div data-testid="tour-complete" />;
+});
+
+jest.mock('../components/tour/joyride-wrapper', () => () => <div data-testid="joyride" />);
+
+let mockAlertProps = null;
+jest.mock('../components/util/alert', () => (props) => {
+ mockAlertProps = props;
+ return <div data-testid="alert" data-message={props.message} />;
+});
+
+jest.mock('./error-boundary', () => ({ children }) => <div>{children}</div>);
+
+jest.mock('googleTagManager', () => ({
+ __esModule: true,
+ default: { pushEvent: jest.fn() },
+}));
+
+jest.mock('../util/local-storage', () => ({
+ __esModule: true,
+ default: {
+ enabled: true,
+ keys: { HIDE_TOUR: 'hideTour', GROUP_OVERLAYS: 'groupOverlays' },
+ getItem: jest.fn(() => null),
+ setItem: jest.fn(),
+ removeItem: jest.fn(),
+ },
+}));
+
+jest.mock('../modules/palettes/util', () => ({
+ preloadPalettes: jest.fn(() => Promise.resolve({ rendered: { p: 1 } })),
+ hasCustomTypePalette: jest.fn(() => false),
+}));
+
+jest.mock('../modules/palettes/actions', () => ({
+ clearCustoms: jest.fn(() => ({ type: 'CLEAR_CUSTOMS' })),
+}));
+
+jest.mock('../modules/palettes/constants', () => ({
+ BULK_PALETTE_RENDERING_SUCCESS: 'BULK_PALETTE_RENDERING_SUCCESS',
+ BULK_PALETTE_PRELOADING_SUCCESS: 'BULK_PALETTE_PRELOADING_SUCCESS',
+}));
+
+jest.mock('../modules/animation/actions', () => ({
+ stop: jest.fn(() => ({ type: 'STOP_ANIMATION' })),
+}));
+
+jest.mock('../modules/modal/actions', () => ({
+ onClose: jest.fn(() => ({ type: 'MODAL_CLOSE' })),
+}));
+
+jest.mock('../redux-location-state-customs', () => ({
+ LOCATION_POP_ACTION: 'LOCATION_POP',
+}));
+
+jest.mock('../modules/layers/util', () => ({
+ layersParse12: jest.fn(() => [
+ { id: 'layer1', custom: false, disabled: false },
+ { id: 'layer2', custom: true, disabled: false },
+ ]),
+}));
+
+jest.mock('../modules/tour/actions', () => ({
+ startTour: jest.fn(() => ({ type: 'START_TOUR' })),
+ endTour: jest.fn(() => ({ type: 'END_TOUR' })),
+ selectStory: jest.fn((id) => ({ type: 'SELECT_STORY', id })),
+}));
+
+jest.mock('../modules/product-picker/actions', () => ({
+ resetProductPickerState: jest.fn(() => ({ type: 'RESET_PRODUCT_PICKER' })),
+}));
+
+jest.mock('../modules/sidebar/actions', () => ({
+ changeTab: jest.fn((str) => ({ type: 'CHANGE_TAB', str })),
+}));
+
+jest.mock('../modules/layers/actions', () => ({
+ toggleOverlayGroups: jest.fn(() => ({ type: 'TOGGLE_OVERLAY_GROUPS' })),
+}));
+
+jest.mock('../main', () => ({
+ __esModule: true,
+ default: { location: { search: '?x=1', pathname: '/' } },
+}));
+
+jest.mock('../util/util', () => ({
+ __esModule: true,
+ default: {
+ fromQueryString: jest.fn(() => ({})),
+ },
+}));
+
+jest.mock('../modules/map/util', () => ({
+ promiseImageryForTour: jest.fn(() => Promise.resolve('imagery')),
+}));
+
+const Tour = require('./tour').default;
+const googleTagManager = require('googleTagManager').default;
+const safeLocalStorage = require('../util/local-storage').default;
+const util = require('../util/util').default;
+const { preloadPalettes, hasCustomTypePalette } = require('../modules/palettes/util');
+const { clearCustoms } = require('../modules/palettes/actions');
+const { layersParse12 } = require('../modules/layers/util');
+const { promiseImageryForTour: promiseImageryForTourUtil } = require('../modules/map/util');
+
+const stories = {
+ story1: {
+ id: 'story1',
+ steps: [{ stepLink: 'l=x&t=1', description: 'd1.html' }],
+ },
+ story2: {
+ id: 'story2',
+ steps: [
+ {
+ stepLink: 'l=a',
+ description: 'd1.html',
+ transition: { element: 'animation', action: 'play' },
+ },
+ { stepLink: 'l=b', description: 'd2.html' },
+ ],
+ },
+};
+const storyOrder = ['story1', 'story2'];
+
+const defaultProps = {
+ isActive: true,
+ stories,
+ storyOrder,
+ currentStoryId: '',
+ config: { features: {}, parameters: {} },
+ map: { ui: { selected: null } },
+ screenHeight: 800,
+ screenWidth: 1200,
+ renderedPalettes: {},
+ activeTab: 'layers',
+ isKioskModeActive: false,
+ isEmbedModeActive: false,
+ groupOverlays: true,
+ selectTour: jest.fn(),
+ endTour: jest.fn(),
+ startTour: jest.fn(),
+ processStepLink: jest.fn(),
+ preProcessStepLink: jest.fn(),
+ promiseImageryForTour: jest.fn(),
+ resetProductPicker: jest.fn(),
+ changeTab: jest.fn(),
+ toggleOverlayGroups: jest.fn(),
+};
+
+const renderComponent = (props = {}) => render(<Tour {...defaultProps} {...props} />);
+
+// helper: select story2 from the start modal and wait for in-progress modal
+async function selectStory2(extraProps = {}) {
+ const result = renderComponent(extraProps);
+ await act(async () => {
+ mockTourStartProps.selectTour({ preventDefault: jest.fn() }, stories.story2, 1, 'story2');
+ });
+ await waitFor(() => expect(mockTourInProgressProps).not.toBeNull());
+ return result;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockTourStartProps = null;
+ mockTourInProgressProps = null;
+ mockTourCompleteProps = null;
+ mockAlertProps = null;
+ safeLocalStorage.getItem.mockReturnValue(null);
+ util.fromQueryString.mockReturnValue({});
+ global.fetch = jest.fn(() => Promise.resolve({
+ ok: true,
+ text: () => Promise.resolve('plain description'),
+ }));
+});
+
+describe('initial rendering', () => {
+ it('renders the start modal when no story is selected', () => {
+ const { getByTestId } = renderComponent();
+ expect(getByTestId('tour-start')).toBeInTheDocument();
+ expect(mockTourStartProps.modalStart).toBe(true);
+ expect(mockTourStartProps.checked).toBe(false);
+ });
+
+ it('renders nothing when there are no stories and the tour is inactive', () => {
+ const { container } = renderComponent({
+ stories: null,
+ storyOrder: null,
+ isActive: false,
+ });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('shows the support alert for an unknown story id', () => {
+ const endTour = jest.fn();
+ const { getByTestId } = renderComponent({ currentStoryId: 'unknown-story', endTour });
+ expect(getByTestId('alert')).toHaveAttribute(
+ 'data-message',
+ 'Sorry, this tour is no longer supported.',
+ );
+ mockAlertProps.onDismiss();
+ expect(endTour).toHaveBeenCalled();
+ });
+
+ it('restarts the linked story when mounted with a valid story id', async () => {
+ const selectTour = jest.fn();
+ const processStepLink = jest.fn();
+ renderComponent({ currentStoryId: 'story2', selectTour, processStepLink });
+ await waitFor(() => {
+ expect(selectTour).toHaveBeenCalledWith('story2');
+ expect(processStepLink).toHaveBeenCalled();
+ });
+ });
+});
+
+describe('selectTour', () => {
+ it('starts the story, processes step links and fetches metadata', async () => {
+ const selectTour = jest.fn();
+ const processStepLink = jest.fn();
+ const preProcessStepLink = jest.fn();
+ await selectStory2({ selectTour, processStepLink, preProcessStepLink });
+ expect(selectTour).toHaveBeenCalledWith('story2');
+ expect(processStepLink).toHaveBeenCalledWith(
+ 'story2',
+ 1,
+ 2,
+ 'l=a&tr=story2&playanim=true&em=false',
+ defaultProps.config,
+ {},
+ );
+ expect(preProcessStepLink).toHaveBeenCalledWith(
+ 'l=b&tr=story2&playanim=true&em=false',
+ defaultProps.config,
+ defaultProps.promiseImageryForTour,
+ );
+ expect(global.fetch).toHaveBeenCalledWith('config/metadata/stories/story2/d1.html');
+ await waitFor(() => {
+ expect(mockTourInProgressProps.description).toBe('plain description');
+ expect(mockTourInProgressProps.metaLoaded).toBe(true);
+ });
+ });
+
+ it('appends the kiosk param and skips preprocessing single-step stories', async () => {
+ const processStepLink = jest.fn();
+ const preProcessStepLink = jest.fn();
+ renderComponent({ isKioskModeActive: true, processStepLink, preProcessStepLink });
+ await act(async () => {
+ mockTourStartProps.selectTour({ preventDefault: jest.fn() }, stories.story1, 0, 'story1');
+ });
+ expect(processStepLink).toHaveBeenCalledWith(
+ 'story1',
+ 1,
+ 1,
+ 'l=x&t=1&tr=story1&kiosk=true&em=false',
+ defaultProps.config,
+ {},
+ );
+ expect(preProcessStepLink).not.toHaveBeenCalled();
+ });
+
+ it('uses the error message when metadata is a full html page', async () => {
+ global.fetch = jest.fn(() => Promise.resolve({
+ ok: true,
+ text: () => Promise.resolve('<html><body>nope</body></html>'),
+ }));
+ await selectStory2();
+ await waitFor(() => {
+ expect(mockTourInProgressProps.description)
+ .toBe('<p>There was an error loading this description.</p>');
+ });
+ });
+
+ it('uses the error message when the fetch response is not ok', async () => {
+ global.fetch = jest.fn(() => Promise.resolve({
+ ok: false,
+ text: () => Promise.resolve('ignored'),
+ }));
+ await selectStory2();
+ await waitFor(() => {
+ expect(mockTourInProgressProps.description)
+ .toBe('<p>There was an error loading this description.</p>');
+ });
+ });
+
+ it('stores the fetch error when the request rejects', async () => {
+ const fetchError = new Error('network');
+ global.fetch = jest.fn(() => Promise.reject(fetchError));
+ await selectStory2();
+ await waitFor(() => {
+ expect(mockTourInProgressProps.description).toBe(fetchError);
+ expect(mockTourInProgressProps.isLoadingMeta).toBe(false);
+ });
+ });
+});
+
+describe('step navigation', () => {
+ it('increments through steps and completes the tour', async () => {
+ const processStepLink = jest.fn();
+ const changeTab = jest.fn();
+ await selectStory2({ processStepLink, changeTab, activeTab: 'events' });
+ expect(mockTourInProgressProps.currentStep).toBe(1);
+
+ await act(async () => {
+ mockTourInProgressProps.incrementStep({ preventDefault: jest.fn() });
+ });
+ expect(changeTab).toHaveBeenCalledWith('layers');
+ expect(mockTourInProgressProps.currentStep).toBe(2);
+ expect(processStepLink).toHaveBeenLastCalledWith(
+ 'story2',
+ 2,
+ 2,
+ 'l=b&tr=story2&em=false',
+ defaultProps.config,
+ {},
+ );
+
+ await act(async () => {
+ mockTourInProgressProps.incrementStep({ preventDefault: jest.fn() });
+ });
+ await waitFor(() => {
+ expect(mockTourCompleteProps).not.toBeNull();
+ expect(mockTourCompleteProps.modalComplete).toBe(true);
+ });
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'tour_completed',
+ story: { id: 'story2' },
+ });
+ });
+
+ it('decrements steps and returns to the start modal from step one', async () => {
+ const processStepLink = jest.fn();
+ await selectStory2({ processStepLink });
+ await act(async () => {
+ mockTourInProgressProps.incrementStep({ preventDefault: jest.fn() });
+ });
+ expect(mockTourInProgressProps.currentStep).toBe(2);
+ await act(async () => {
+ mockTourInProgressProps.decreaseStep({ preventDefault: jest.fn() });
+ });
+ expect(mockTourInProgressProps.currentStep).toBe(1);
+ expect(processStepLink).toHaveBeenLastCalledWith(
+ 'story2',
+ 1,
+ 2,
+ 'l=a&tr=story2&playanim=true&em=false',
+ defaultProps.config,
+ {},
+ );
+ await act(async () => {
+ mockTourInProgressProps.decreaseStep({ preventDefault: jest.fn() });
+ });
+ expect(mockTourStartProps.modalStart).toBe(true);
+ });
+});
+
+describe('start modal interactions', () => {
+ it('toggleModalStart closing the modal ends the tour', async () => {
+ const endTour = jest.fn();
+ renderComponent({ endTour });
+ await act(async () => {
+ mockTourStartProps.toggleModalStart({ preventDefault: jest.fn() });
+ });
+ expect(endTour).toHaveBeenCalled();
+ });
+
+ it('hideTour stores the preference and shows the disabled alert on end', async () => {
+ const endTour = jest.fn();
+ const { getByTestId } = renderComponent({ endTour });
+ await act(async () => {
+ mockTourStartProps.hideTour();
+ });
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'tour_hide_checked' });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('hideTour', expect.any(Date));
+ await act(async () => {
+ mockTourStartProps.endTour({ preventDefault: jest.fn() });
+ });
+ expect(endTour).not.toHaveBeenCalled();
+ expect(getByTestId('alert')).toHaveAttribute(
+ 'data-message',
+ expect.stringContaining('To view these tours again'),
+ );
+ });
+
+ it('hideTour does not re-store the preference when already hidden', async () => {
+ safeLocalStorage.getItem.mockReturnValue('2020-01-01');
+ renderComponent();
+ await act(async () => {
+ mockTourStartProps.hideTour();
+ });
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ it('showTour removes the stored preference', async () => {
+ safeLocalStorage.getItem.mockReturnValue('2020-01-01');
+ renderComponent();
+ await act(async () => {
+ mockTourStartProps.showTour();
+ });
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'tour_hide_unchecked' });
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith('hideTour');
+ });
+
+ it('showTour does nothing when no preference is stored', async () => {
+ renderComponent();
+ await act(async () => {
+ mockTourStartProps.showTour();
+ });
+ expect(safeLocalStorage.removeItem).not.toHaveBeenCalled();
+ });
+
+ it('endTour calls the endTour prop when no disabled alert is shown', async () => {
+ const endTour = jest.fn();
+ renderComponent({ endTour });
+ await act(async () => {
+ mockTourStartProps.endTour({ preventDefault: jest.fn() });
+ });
+ expect(endTour).toHaveBeenCalled();
+ });
+});
+
+describe('tour completion and reset', () => {
+ it('resetTour returns to the start modal and records the event', async () => {
+ const startTour = jest.fn();
+ await selectStory2({ startTour });
+ await act(async () => {
+ mockTourInProgressProps.incrementStep({ preventDefault: jest.fn() });
+ });
+ await act(async () => {
+ mockTourInProgressProps.incrementStep({ preventDefault: jest.fn() });
+ });
+ await waitFor(() => expect(mockTourCompleteProps).not.toBeNull());
+ await act(async () => {
+ mockTourCompleteProps.resetTour({ preventDefault: jest.fn() });
+ });
+ expect(startTour).toHaveBeenCalled();
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'tour_more_stories_button' });
+ expect(mockTourStartProps.modalStart).toBe(true);
+ });
+});
+
+describe('group overlays preference', () => {
+ it('restores the preference when the tour ends', async () => {
+ const toggleOverlayGroups = jest.fn();
+ const { rerender } = renderComponent({
+ isActive: false,
+ groupOverlays: false,
+ toggleOverlayGroups,
+ });
+ act(() => {
+ rerender(
+ <Tour
+ {...defaultProps}
+ isActive
+ groupOverlays={false}
+ toggleOverlayGroups={toggleOverlayGroups}
+ />,
+ );
+ });
+ act(() => {
+ rerender(
+ <Tour
+ {...defaultProps}
+ isActive={false}
+ groupOverlays={false}
+ toggleOverlayGroups={toggleOverlayGroups}
+ />,
+ );
+ });
+ // snapshot was true (storage not 'disabled'), groupOverlays false → restore
+ expect(toggleOverlayGroups).toHaveBeenCalled();
+ });
+
+ it('does not toggle when the preference matches', async () => {
+ const toggleOverlayGroups = jest.fn();
+ const { rerender } = renderComponent({
+ isActive: false,
+ groupOverlays: true,
+ toggleOverlayGroups,
+ });
+ act(() => {
+ rerender(
+ <Tour {...defaultProps} isActive groupOverlays toggleOverlayGroups={toggleOverlayGroups} />,
+ );
+ });
+ act(() => {
+ rerender(
+ <Tour
+ {...defaultProps}
+ isActive={false}
+ groupOverlays
+ toggleOverlayGroups={toggleOverlayGroups}
+ />,
+ );
+ });
+ expect(toggleOverlayGroups).not.toHaveBeenCalled();
+ });
+
+ it('restores the preference on unmount while active', () => {
+ const toggleOverlayGroups = jest.fn();
+ const { unmount } = renderComponent({
+ isActive: true,
+ groupOverlays: false,
+ toggleOverlayGroups,
+ });
+ unmount();
+ expect(toggleOverlayGroups).toHaveBeenCalled();
+ });
+});
+
+describe('mapStateToProps', () => {
+ it('maps tour state', () => {
+ const state = {
+ screenSize: { screenWidth: 1300, screenHeight: 700 },
+ config: { stories, storyOrder },
+ tour: { active: true, selected: 'story1' },
+ palettes: { rendered: { r: 1 } },
+ models: {},
+ compare: { activeString: 'active' },
+ map: { ui: {} },
+ sidebar: { activeTab: 'events' },
+ ui: { isKioskModeActive: true },
+ embed: { isEmbedModeActive: false },
+ layers: { active: { groupOverlays: true } },
+ };
+ const result = capturedMapState(state);
+ expect(result.isActive).toBe(true);
+ expect(result.currentStoryId).toBe('story1');
+ expect(result.stories).toBe(stories);
+ expect(result.storyOrder).toBe(storyOrder);
+ expect(result.isKioskModeActive).toBe(true);
+ expect(result.screenWidth).toBe(1300);
+ expect(result.renderedPalettes).toEqual({ r: 1 });
+ expect(result.activeTab).toBe('events');
+ expect(result.groupOverlays).toBe(true);
+ result.promiseImageryForTour(['l'], '2020-01-01', 'active');
+ expect(promiseImageryForTourUtil).toHaveBeenCalledWith(state, ['l'], '2020-01-01', 'active');
+ });
+});
+
+describe('mapDispatchToProps', () => {
+ let dispatch;
+ let props;
+ beforeEach(() => {
+ dispatch = jest.fn();
+ props = capturedMapDispatch(dispatch);
+ });
+
+ it('dispatches the simple actions', () => {
+ props.startTour();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'START_TOUR' });
+ props.endTour();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'END_TOUR' });
+ props.selectTour('story1');
+ expect(dispatch).toHaveBeenCalledWith({ type: 'SELECT_STORY', id: 'story1' });
+ props.resetProductPicker();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'RESET_PRODUCT_PICKER' });
+ props.changeTab('layers');
+ expect(dispatch).toHaveBeenCalledWith({ type: 'CHANGE_TAB', str: 'layers' });
+ props.toggleOverlayGroups();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'TOGGLE_OVERLAY_GROUPS' });
+ });
+
+ it('processStepLink dispatches stop, close and location pop without palettes', () => {
+ props.processStepLink('story1', 1, 2, 'l=a&tr=story1', { config: true }, {});
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'tour_selected_story',
+ story: { id: 'story1', selectedStep: 1, totalSteps: 2 },
+ });
+ expect(dispatch).toHaveBeenCalledWith({ type: 'STOP_ANIMATION' });
+ expect(dispatch).toHaveBeenCalledWith({ type: 'MODAL_CLOSE' });
+ expect(clearCustoms).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: 'LOCATION_POP',
+ payload: expect.objectContaining({ search: 'l=a&tr=story1' }),
+ });
+ });
+
+ it('processStepLink clears customs when palettes are rendered', () => {
+ props.processStepLink('story1', 1, 2, 'l=a', { config: true }, { rendered: 1 });
+ expect(clearCustoms).toHaveBeenCalled();
+ });
+
+ it('processStepLink preloads palettes for custom palette layers', async () => {
+ util.fromQueryString.mockReturnValue({ l: 'layers(custom)', l1: 'layersB(custom)' });
+ hasCustomTypePalette.mockReturnValue(true);
+ props.processStepLink('story1', 1, 2, 'l=layers(custom)', { config: true }, {});
+ expect(layersParse12).toHaveBeenCalled();
+ expect(preloadPalettes).toHaveBeenCalled();
+ await waitFor(() => {
+ expect(dispatch).toHaveBeenCalledWith({
+ type: 'BULK_PALETTE_RENDERING_SUCCESS',
+ rendered: { p: 1 },
+ });
+ expect(dispatch).toHaveBeenCalledWith({
+ type: 'LOCATION_POP',
+ payload: expect.anything(),
+ });
+ });
+ });
+
+ it('preProcessStepLink preloads palettes and promises imagery for both layer sets', async () => {
+ util.fromQueryString.mockReturnValue({
+ l: 'layersA', t: '2020-01-01', l1: 'layersB', t1: '2020-01-02',
+ });
+ const promiseImageryForTour = jest.fn(() => Promise.resolve());
+ await props.preProcessStepLink('l=layersA', { config: true }, promiseImageryForTour);
+ expect(preloadPalettes).toHaveBeenCalled();
+ await waitFor(() => {
+ expect(dispatch).toHaveBeenCalledWith({
+ type: 'BULK_PALETTE_PRELOADING_SUCCESS',
+ tourStoryPalettes: { p: 1 },
+ });
+ expect(promiseImageryForTour).toHaveBeenCalledTimes(2);
+ expect(promiseImageryForTour).toHaveBeenCalledWith(
+ expect.any(Array), '2020-01-02', 'activeB',
+ );
+ });
+ });
});
diff --git a/web/js/containers/vector-dialog.test.js b/web/js/containers/vector-dialog.test.js
index 43e3d0030..c4d147204 100644
--- a/web/js/containers/vector-dialog.test.js
+++ b/web/js/containers/vector-dialog.test.js
@@ -1,3 +1,152 @@
-test('vector-dialog container test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+let capturedMapState;
+jest.mock('react-redux', () => ({
+ connect: (mapState, mapDispatch) => {
+ capturedMapState = mapState;
+ return (Component) => Component;
+ },
+}));
+
+jest.mock('../components/util/scrollbar', () => (props) => (
+ <div data-testid="scrollbars">{props.children}</div>
+));
+
+let capturedTableProps;
+jest.mock('../components/vector-metadata/table', () => (props) => {
+ capturedTableProps = props;
+ return <div data-testid="vector-meta-table" />;
+});
+
+const VectorDialog = require('./vector-dialog').default;
+
+const vectorMetaObject = {
+ layerA: [
+ { id: 'vector_layer_a', title: 'Layer A', subTitle: 'Sub A' },
+ { id: 'vector_layer_a2', title: 'Layer A', subTitle: 'Sub A' },
+ ],
+ layerB: [
+ { id: 'vector_layer_b', title: 'A very long layer title that exceeds limits' },
+ ],
+};
+
+const defaultProps = {
+ vectorMetaObject,
+ modalHeight: 500,
+ dialogKey: 1,
+ toggleWithClose: jest.fn(),
+};
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ capturedTableProps = null;
+});
+
+describe('VectorDialog (non-AERONET)', () => {
+ it('renders nav items for each vector meta key with counts', () => {
+ const { container } = render(<VectorDialog {...defaultProps} />);
+ const navItems = container.querySelectorAll('.vector-meta-nav-item');
+ expect(navItems).toHaveLength(2);
+ expect(navItems[0].textContent).toContain('Layer A [2]');
+ });
+
+ it('truncates long titles to 20 characters with ellipsis', () => {
+ const { container } = render(<VectorDialog {...defaultProps} />);
+ const navItems = container.querySelectorAll('.vector-meta-nav-item');
+ expect(navItems[1].textContent).toContain('A very long layer ti... [1]');
+ });
+
+ it('passes the active meta array to VectorMetaTable', () => {
+ render(<VectorDialog {...defaultProps} />);
+ expect(capturedTableProps.metaArray).toBe(vectorMetaObject.layerA);
+ expect(capturedTableProps.title).toBe('layerA');
+ expect(capturedTableProps.id).toBe(1);
+ });
+
+ it('switches tabs when a nav link is clicked', () => {
+ const { container } = render(<VectorDialog {...defaultProps} />);
+ const navLinks = container.querySelectorAll('.nav-link');
+ fireEvent.click(navLinks[1]);
+ expect(capturedTableProps.metaArray).toBe(vectorMetaObject.layerB);
+ expect(capturedTableProps.title).toBe('layerB');
+ });
+
+ it('does not update state when clicking the already-active tab', () => {
+ const { container } = render(<VectorDialog {...defaultProps} />);
+ const navLinks = container.querySelectorAll('.nav-link');
+ fireEvent.click(navLinks[0]);
+ expect(capturedTableProps.metaArray).toBe(vectorMetaObject.layerA);
+ });
+
+ it('invokes toggleWithClose from the close button', () => {
+ const toggleWithClose = jest.fn();
+ const { container } = render(
+ <VectorDialog {...defaultProps} toggleWithClose={toggleWithClose} />,
+ );
+ fireEvent.click(container.querySelector('.vector-close-btn'));
+ expect(toggleWithClose).toHaveBeenCalled();
+ });
+});
+
+describe('VectorDialog (AERONET)', () => {
+ const aeronetActive = {
+ site: [{
+ id: 'AERONET_SITE_AOD',
+ title: 'Aeronet Site',
+ features: {
+ name: 'Test_Site',
+ coordinates: [10.5, -20.25],
+ active: true,
+ value: 0.5,
+ date: new Date('2021-06-01T12:00:00Z'),
+ },
+ }],
+ };
+
+ it('renders site info with recent reading when active', () => {
+ const { container, getByText } = render(
+ <VectorDialog {...defaultProps} vectorMetaObject={aeronetActive} />,
+ );
+ expect(getByText('Test_Site')).toBeInTheDocument();
+ expect(getByText('Site is online')).toBeInTheDocument();
+ expect(getByText('Most recent reading: 0.5')).toBeInTheDocument();
+ expect(getByText('View More Data')).toBeInTheDocument();
+ expect(container.textContent).toContain('(10.5, -20.25)');
+ });
+
+ it('renders offline message without readings when inactive', () => {
+ const aeronetInactive = {
+ site: [{
+ ...aeronetActive.site[0],
+ features: { ...aeronetActive.site[0].features, active: false },
+ }],
+ };
+ const { getByText, queryByText } = render(
+ <VectorDialog {...defaultProps} vectorMetaObject={aeronetInactive} />,
+ );
+ expect(getByText('Site is currently offline')).toBeInTheDocument();
+ expect(queryByText(/Most recent reading/)).toBeNull();
+ });
+
+ it('closes via the AERONET close button', () => {
+ const toggleWithClose = jest.fn();
+ const { container } = render(
+ <VectorDialog
+ {...defaultProps}
+ vectorMetaObject={aeronetActive}
+ toggleWithClose={toggleWithClose}
+ />,
+ );
+ fireEvent.click(container.querySelector('.vector-close-btn'));
+ expect(toggleWithClose).toHaveBeenCalled();
+ });
+});
+
+describe('mapStateToProps', () => {
+ it('returns an empty object', () => {
+ expect(capturedMapState({ anything: true })).toEqual({});
+ });
});