Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Checking in first pass of components dir unit tests.

Jason Hurleyafe31f6298ab
diff --git a/web/js/components/about/about-section.js b/web/js/components/about/about-section.js
index 805b262ea..be73458e9 100644
--- a/web/js/components/about/about-section.js
+++ b/web/js/components/about/about-section.js
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
export default function AboutSection(props) {
@@ -29,7 +29,10 @@ export default function AboutSection(props) {
return controller ? controller.abort() : null;
};
- fetchHTML();
+ useEffect(() => {
+ return fetchHTML();
+ }, [section]);
+
return (
<div dangerouslySetInnerHTML={{ __html: sectionDescription }} />
);
diff --git a/web/js/components/about/about-section.test.js b/web/js/components/about/about-section.test.js
index 96be1bff4..bf6c0831d 100644
--- a/web/js/components/about/about-section.test.js
+++ b/web/js/components/about/about-section.test.js
@@ -1,3 +1,123 @@
-test('about-section component test', () => {
+import { render, waitFor } from '@testing-library/react';
+import AboutSection from './about-section';
+global.fetch = jest.fn();
+
+const mockAbortController = {
+ abort: jest.fn(),
+ signal: { aborted: false },
+};
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ global.AbortController = jest.fn(() => mockAbortController);
+});
+
+describe('AboutSection', () => {
+ test('renders a div when fetch is successful', async () => {
+ fetch.mockResolvedValueOnce({
+ ok: true,
+ text: jest.fn().mockResolvedValueOnce('Hello'),
+ });
+
+ const { container } = render(<AboutSection section="test" />);
+
+ await waitFor(() => {
+ expect(container.querySelector('div').textContent).toBe('Hello');
+ });
+ });
+
+ test('displays HTML text content when fetch is successful and ok is true', async () => {
+ fetch.mockResolvedValueOnce({
+ ok: true,
+ text: jest.fn().mockResolvedValueOnce('About Content'),
+ });
+
+ const { container } = render(<AboutSection section="overview" />);
+
+ await waitFor(() => {
+ expect(container.querySelector('div').textContent).toBe('About Content');
+ });
+ });
+
+ test('displays empty text when fetch response is not ok', async () => {
+ fetch.mockResolvedValueOnce({
+ ok: false,
+ text: jest.fn().mockResolvedValueOnce('Error Content'),
+ });
+
+ const { container } = render(<AboutSection section="overview" />);
+
+ await waitFor(() => {
+ expect(container.querySelector('div').textContent).toBe('');
+ });
+ });
+
+ test('calls fetch with the correct URL based on section prop', async () => {
+ fetch.mockResolvedValueOnce({
+ ok: true,
+ text: jest.fn().mockResolvedValueOnce('Mission Content'),
+ });
+
+ const { container } = render(<AboutSection section="mission" />);
+
+ await waitFor(() => {
+ expect(fetch).toHaveBeenCalledWith('brand/about/mission.html');
+ expect(container.querySelector('div').textContent).toBe('Mission Content');
+ });
+ });
+
+ test('displays "no section name provided" when section is an empty string', async () => {
+ const { container } = render(<AboutSection section="" />);
+
+ await waitFor(() => {
+ expect(fetch).not.toHaveBeenCalled();
+ expect(container.querySelector('div').textContent).toBe('no section name provided');
+ });
+ });
+
+ test('displays "could not load metadata" when fetch throws and signal is not aborted', async () => {
+ fetch.mockRejectedValueOnce(new Error('Network Error'));
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ const { container } = render(<AboutSection section="overview" />);
+
+ await waitFor(() => {
+ expect(container.querySelector('div').textContent).toBe('could not load metadata');
+ expect(consoleErrorSpy).toHaveBeenCalled();
+ });
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ test('displays empty text and does not log error when fetch throws and signal is aborted', async () => {
+ fetch.mockRejectedValueOnce(new Error('Aborted'));
+
+ const abortedController = {
+ abort: jest.fn(),
+ signal: { aborted: true },
+ };
+ global.AbortController = jest.fn(() => abortedController);
+
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ const { container } = render(<AboutSection section="overview" />);
+
+ await waitFor(() => {
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
+ expect(container.querySelector('div').textContent).toBe('');
+ });
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ test('calls controller.abort() when controller is not null', async () => {
+ fetch.mockImplementationOnce(() => new Promise(() => {}));
+
+ render(<AboutSection section="overview" />);
+
+ await waitFor(() => {
+ expect(mockAbortController.abort).toHaveBeenCalled();
+ });
+ });
});
diff --git a/web/js/components/about/about.test.js b/web/js/components/about/about.test.js
index c7f9cdcd6..35d628c35 100644
--- a/web/js/components/about/about.test.js
+++ b/web/js/components/about/about.test.js
@@ -1,3 +1,29 @@
-test('about component test', () => {
+/* eslint-disable react/prop-types */
+import { render } from '@testing-library/react';
+import AboutModal from './about';
+jest.mock('../util/scrollbar', () => ({ children, style }) => (
+ <div data-testid="scrollbar" style={style}>
+ {children}
+ </div>
+));
+
+jest.mock('./about-section', () => ({ section }) => (
+ <div data-testid={`about-section-${section}`}>{section}</div>
+));
+
+describe('AboutModal', () => {
+ test('renders sections in the correct order', () => {
+ const { container } = render(<AboutModal />);
+ const sectionDivs = container.querySelectorAll('[data-testid^="about-section-"]');
+ const sectionNames = Array.from(sectionDivs).map((el) => el.textContent);
+ expect(sectionNames).toEqual([
+ 'welcome',
+ 'keyboard',
+ 'imagery',
+ 'acknowledgements',
+ 'disclaimer',
+ 'license',
+ ]);
+ });
});
diff --git a/web/js/components/animation-widget/gif-button.test.js b/web/js/components/animation-widget/gif-button.test.js
index d6e2ccd19..029ecea51 100644
--- a/web/js/components/animation-widget/gif-button.test.js
+++ b/web/js/components/animation-widget/gif-button.test.js
@@ -1,3 +1,195 @@
-test('gif-button component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import '@testing-library/jest-dom';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import configureStore from 'redux-mock-store';
+import GifButton from './gif-button';
+import googleTagManager from 'googleTagManager';
+import { hasCustomPaletteInActiveProjection } from '../../modules/palettes/util';
+import { hasNonDownloadableVisibleLayer, getNonDownloadableLayers } from '../../modules/image-download/util';
+import { openCustomContent, onToggle } from '../../modules/modal/actions';
+// Mock external dependencies
+jest.mock('googleTagManager', () => ({
+ pushEvent: jest.fn(),
+}));
+
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: () => <svg data-testid="fa-icon" />,
+}));
+
+jest.mock('reactstrap', () => ({
+ UncontrolledTooltip: ({ children }) => <div data-testid="tooltip">{children}</div>,
+}));
+
+jest.mock('../../containers/gif', () => ({ onClose }) => (
+ <div data-testid="gif-container">
+ <button data-testid="close-gif-btn" onClick={onClose}>Close GIF</button>
+ </div>
+));
+
+// Mock Redux Actions
+jest.mock('../../modules/animation/actions', () => ({
+ toggleComponentGifActive: jest.fn(() => ({ type: 'TOGGLE_GIF' })),
+ changeStartAndEndDate: jest.fn(() => ({ type: 'CHANGE_DATES' })),
+}));
+
+jest.mock('../../modules/palettes/actions', () => ({
+ clearCustoms: jest.fn(() => ({ type: 'CLEAR_CUSTOMS' })),
+ refreshPalettes: jest.fn(() => ({ type: 'REFRESH_PALETTES' })),
+}));
+
+jest.mock('../../modules/map/actions', () => ({
+ clearRotate: jest.fn(() => ({ type: 'CLEAR_ROTATE' })),
+ refreshRotation: jest.fn(() => ({ type: 'REFRESH_ROTATION' })),
+}));
+
+jest.mock('../../modules/layers/actions', () => ({
+ hideLayers: jest.fn(() => ({ type: 'HIDE_LAYERS' })),
+ showLayers: jest.fn(() => ({ type: 'SHOW_LAYERS' })),
+}));
+
+jest.mock('../../modules/modal/actions', () => ({
+ onToggle: jest.fn(() => ({ type: 'ON_TOGGLE' })),
+ openCustomContent: jest.fn((id, payload) => ({ type: 'OPEN_CUSTOM_CONTENT', payload })),
+}));
+
+jest.mock('../../modules/palettes/util', () => ({
+ hasCustomPaletteInActiveProjection: jest.fn(),
+}));
+
+jest.mock('../../modules/image-download/util', () => ({
+ getNonDownloadableLayers: jest.fn(() => ['layer-1']),
+ getNonDownloadableLayerWarning: jest.fn(() => 'Warning'),
+ hasNonDownloadableVisibleLayer: jest.fn(),
+}));
+
+const mockStore = configureStore();
+
+describe('GifButton Component', () => {
+ let store;
+ let initialState;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ hasCustomPaletteInActiveProjection.mockReturnValue(false);
+ hasNonDownloadableVisibleLayer.mockReturnValue(false);
+ initialState = {
+ animation: { gifActive: false },
+ palettes: { active: { 'layer-1': 'custom-palette' } },
+ compare: { activeString: 'active' },
+ map: { rotation: 0 },
+ proj: {},
+ layers: {
+ active: {
+ 'layer-1': { id: 'layer-1', visible: true, type: 'wmts' },
+ },
+ },
+ };
+ });
+
+ const renderComponent = (customProps = {}, customState = {}) => {
+ store = mockStore({ ...initialState, ...customState });
+ store.dispatch = jest.fn((action) => action);
+
+ const defaultProps = {
+ zeroDates: jest.fn(() => ({ startDate: '2023-01-01', endDate: '2023-01-02' })),
+ onToggle: jest.fn(),
+ numberOfFrames: 10,
+ ...customProps,
+ };
+
+ return render(
+ <Provider store={store}>
+ <GifButton {...defaultProps} />
+ </Provider>,
+ );
+ };
+
+ it('renders the button correctly with default props', () => {
+ renderComponent();
+ const button = screen.getByRole('button');
+ expect(button).toBeInTheDocument();
+ expect(button).not.toHaveClass('disabled');
+ expect(screen.getByTestId('tooltip')).toHaveTextContent('Create an animated GIF');
+ });
+
+ it('disables the button if numberOfFrames >= 40', () => {
+ renderComponent({ numberOfFrames: 40 });
+ const button = screen.getByRole('button');
+ expect(button).toHaveClass('disabled');
+ });
+
+ it('does not dispatch events when button is disabled and clicked', async () => {
+ renderComponent({ numberOfFrames: 45 });
+ const button = screen.getByRole('button');
+ fireEvent.click(button);
+ expect(googleTagManager.pushEvent).not.toHaveBeenCalled();
+ });
+
+ it('opens GIF flow and triggers tracking events on click', async () => {
+ renderComponent({ numberOfFrames: 20 });
+ const button = screen.getByRole('button');
+
+ fireEvent.click(button);
+
+ await waitFor(() => {
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'GIF_create_animated_button',
+ });
+ });
+
+ expect(store.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'CHANGE_DATES' }),
+ );
+ expect(store.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'TOGGLE_GIF' }),
+ );
+ });
+
+ it('triggers notify for custom palettes and handles accept/cancel callbacks', async () => {
+ hasCustomPaletteInActiveProjection.mockReturnValue(true);
+
+ renderComponent();
+ const button = screen.getByRole('button');
+
+ fireEvent.click(button);
+
+ await waitFor(() => {
+ expect(openCustomContent).toHaveBeenCalled();
+ });
+
+ const callArgs = openCustomContent.mock.calls[0];
+ const { bodyComponentProps } = callArgs[1];
+
+ // Test cancel callback
+ bodyComponentProps.cancel();
+ expect(onToggle).toHaveBeenCalled();
+
+ // Test accept callback
+ bodyComponentProps.accept();
+ expect(store.dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: 'CLEAR_CUSTOMS' }));
+ // onToggle is called again during accept
+ expect(onToggle).toHaveBeenCalledTimes(2);
+ });
+
+ it('triggers notify for non-downloadable layers, using getNonDownloadableLayers logic', async () => {
+ hasNonDownloadableVisibleLayer.mockReturnValue(true);
+
+ renderComponent({}, { map: { rotation: 0 } });
+ const button = screen.getByRole('button');
+
+ fireEvent.click(button);
+
+ await waitFor(() => {
+ // The openCustomContent should be called with image_download_notify_layers
+ expect(openCustomContent).toHaveBeenCalledWith(
+ 'image_download_notify_layers',
+ expect.any(Object),
+ );
+ });
+
+ expect(getNonDownloadableLayers).toHaveBeenCalled();
+ });
});
diff --git a/web/js/components/animation-widget/gif-panel-grid.test.js b/web/js/components/animation-widget/gif-panel-grid.test.js
index e2f448602..1eecea3bf 100644
--- a/web/js/components/animation-widget/gif-panel-grid.test.js
+++ b/web/js/components/animation-widget/gif-panel-grid.test.js
@@ -1,3 +1,84 @@
-test('gif-panel-gride component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import GifPanelGrid from './gif-panel-grid'; // adjust the import path if necessary
+// Mock the child components to isolate the testing to GifPanelGrid
+jest.mock('../util/monospace-date', () => {
+ return function MockMonospaceDate({ date }) {
+ return <span data-testid="monospace-date">{date}</span>;
+ };
+});
+
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: () => <svg data-testid="fa-icon" />,
+}));
+
+describe('GifPanelGrid Component', () => {
+ const defaultProps = {
+ startDate: '2026-05-01',
+ endDate: '2026-05-20',
+ speed: 10,
+ increment: '1 Day',
+ valid: true,
+ height: 1080,
+ width: 1920,
+ maxImageDimensionSize: 4096,
+ maxGifSize: 250,
+ requestSize: 125.556,
+ };
+
+ it('renders correctly with valid props', () => {
+ render(<GifPanelGrid {...defaultProps} />);
+
+ // Check basic text rendering
+ expect(screen.getByText('Start Date:')).toBeInTheDocument();
+ expect(screen.getByText('End Date:')).toBeInTheDocument();
+ expect(screen.getByText('10 Frames Per Second')).toBeInTheDocument();
+ expect(screen.getByText('1 Day')).toBeInTheDocument();
+ expect(screen.getByText('4096px')).toBeInTheDocument();
+ expect(screen.getByText('1920px x 1080px')).toBeInTheDocument();
+
+ // Check mocked MonospaceDate components
+ const dates = screen.getAllByTestId('monospace-date');
+ expect(dates[0]).toHaveTextContent('2026-05-01');
+ expect(dates[1]).toHaveTextContent('2026-05-20');
+
+ // Check renderImageSize output for valid state
+ expect(screen.getByText('250 MB / ~125.56 MB')).toBeInTheDocument();
+
+ // Ensure the invalid icon is NOT rendered
+ expect(screen.queryByTestId('fa-icon')).not.toBeInTheDocument();
+
+ // Ensure the dimension container does NOT have the invalid class
+ const dimensionContainer = screen.getByText('4096px').parentElement;
+ expect(dimensionContainer).toHaveClass('grid-child gif-max-size');
+ expect(dimensionContainer).not.toHaveClass('gif-size-invalid');
+ });
+
+ it('renders correctly with invalid props (exceeds size/dimensions)', () => {
+ const invalidProps = {
+ ...defaultProps,
+ valid: false,
+ requestSize: 300.123, // Larger than maxGifSize
+ };
+
+ render(<GifPanelGrid {...invalidProps} />);
+
+ // Check renderImageSize output for invalid state
+ // Note the tilde string differences: "~300.12 MB" vs "/ ~125.56 MB"
+ expect(screen.getByText('250 MB ~300.12 MB')).toBeInTheDocument();
+
+ // The 'times' icon should now be rendered
+ expect(screen.getByTestId('fa-icon')).toBeInTheDocument();
+
+ // The size container should have the invalid class
+ const sizeContainer = screen.getByText('250 MB ~300.12 MB').parentElement;
+ expect(sizeContainer).toHaveClass('gif-size-invalid');
+
+ // Ensure the max dimension container has the invalid class
+ const dimensionContainer = screen.getByText('4096px').parentElement;
+ expect(dimensionContainer).toHaveClass('gif-size-invalid');
+ });
});
diff --git a/web/js/components/animation-widget/gif-panel.test.js b/web/js/components/animation-widget/gif-panel.test.js
index fa902e228..90c6a33ae 100644
--- a/web/js/components/animation-widget/gif-panel.test.js
+++ b/web/js/components/animation-widget/gif-panel.test.js
@@ -1,3 +1,163 @@
-test('gif-panel component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import GifPanel from './gif-panel';
+import { getDimensions } from '../../modules/image-download/util';
+jest.mock('../../modules/image-download/util', () => ({
+ getDimensions: jest.fn(),
+}));
+
+jest.mock('../util/selector', () => {
+ return function MockSelectionList(props) {
+ return (
+ <select
+ data-testid="selection-list"
+ value={props.value}
+ onChange={(e) => props.onChange(props.optionName, e.target.value)}
+ >
+ <option value="1km">1km</option>
+ <option value="2km">2km</option>
+ </select>
+ );
+ };
+});
+
+jest.mock('./gif-panel-grid', () => {
+ return function MockGifPanelGrid(props) {
+ return (
+ <div data-testid="gif-panel-grid">
+ <span data-testid="grid-valid">{props.valid.toString()}</span>
+ <span data-testid="grid-request-size">{props.requestSize}</span>
+ <button data-testid="grid-download-click" onClick={props.onClick}>Grid Download</button>
+ </div>
+ );
+ };
+});
+
+jest.mock('../util/button', () => {
+ return function MockButton(props) {
+ return (
+ <button
+ data-testid={props.text ? `button-${props.text.replace(/\s+/g, '-')}` : 'button-default'}
+ onClick={props.onClick}
+ disabled={props.valid === false}
+ >
+ {props.text || 'Default Button'}
+ </button>
+ );
+ };
+});
+
+jest.mock('../util/checkbox', () => {
+ return function MockCheckbox(props) {
+ return (
+ <input
+ type="checkbox"
+ data-testid="checkbox-dates"
+ checked={props.checked}
+ onChange={props.onCheck}
+ />
+ );
+ };
+});
+
+describe('GifPanel Component', () => {
+ let defaultProps;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ defaultProps = {
+ projId: 'geographic',
+ lonlats: [0, 0, 10, 10],
+ startDate: '2026-05-01',
+ endDate: '2026-05-20',
+ onCheck: jest.fn(),
+ showDates: true,
+ numberOfFrames: 10,
+ firstLabel: 'Resolution (per pixel):',
+ onClick: jest.fn(),
+ onDownloadClick: jest.fn(),
+ speed: 5,
+ resolutions: { '1km': '1km', '2km': '2km' },
+ resolution: '1km',
+ increment: '1 Day',
+ };
+
+ getDimensions.mockReturnValue({ width: 1000, height: 1000 });
+ });
+
+ it('renders correctly with valid dimensions and calculates request size', () => {
+ render(<GifPanel {...defaultProps} />);
+
+ expect(screen.getByText('Resolution (per pixel):')).toBeInTheDocument();
+
+ expect(screen.getByTestId('grid-request-size')).toHaveTextContent('28.59');
+ expect(screen.getByTestId('grid-valid')).toHaveTextContent('true');
+ });
+
+ it('handles resolution change which updates state', () => {
+ render(<GifPanel {...defaultProps} />);
+
+ const selector = screen.getByTestId('selection-list');
+ fireEvent.change(selector, { target: { value: '2km' } });
+
+ expect(getDimensions).toHaveBeenLastCalledWith('geographic', [0, 0, 10, 10], '2km');
+ });
+
+ it('triggers onClick handler with width and height for Create GIF button', () => {
+ render(<GifPanel {...defaultProps} />);
+
+ const createBtn = screen.getByTestId('button-Create-GIF');
+ fireEvent.click(createBtn);
+
+ expect(defaultProps.onClick).toHaveBeenCalledWith(1000, 1000);
+ });
+
+ it('triggers onCheck handler for checkbox', () => {
+ render(<GifPanel {...defaultProps} />);
+
+ const checkbox = screen.getByTestId('checkbox-dates');
+ fireEvent.click(checkbox);
+
+ expect(defaultProps.onCheck).toHaveBeenCalled();
+ });
+
+ it('evaluates valid=false if request size exceeds MAX_GIF_SIZE', () => {
+ getDimensions.mockReturnValue({ width: 8000, height: 8000 });
+
+ render(<GifPanel {...defaultProps} />);
+
+ expect(screen.getByTestId('grid-valid')).toHaveTextContent('false');
+ });
+
+ it('evaluates valid=false if width or height is 0', () => {
+ getDimensions.mockReturnValue({ width: 0, height: 1000 });
+ render(<GifPanel {...defaultProps} />);
+ expect(screen.getByTestId('grid-valid')).toHaveTextContent('false');
+
+ getDimensions.mockReturnValue({ width: 1000, height: 0 });
+ render(<GifPanel {...defaultProps} />);
+ expect(screen.getAllByTestId('grid-valid')[1]).toHaveTextContent('false');
+ });
+
+ it('evaluates valid=false if width or height exceeds MAX_IMAGE_DIMENSION_SIZE (8200)', () => {
+ getDimensions.mockReturnValue({ width: 8201, height: 100 });
+ render(<GifPanel {...defaultProps} numberOfFrames={1} />);
+ expect(screen.getByTestId('grid-valid')).toHaveTextContent('false');
+
+ getDimensions.mockReturnValue({ width: 100, height: 8201 });
+ render(<GifPanel {...defaultProps} numberOfFrames={1} />);
+ expect(screen.getAllByTestId('grid-valid')[1]).toHaveTextContent('false');
+ });
+
+ it('passes onDownloadClick to GifPanelGrid', () => {
+ render(<GifPanel {...defaultProps} />);
+ const gridDownloadBtn = screen.getByTestId('grid-download-click');
+ fireEvent.click(gridDownloadBtn);
+
+ expect(defaultProps.onDownloadClick).toHaveBeenCalled();
+ });
});
diff --git a/web/js/components/animation-widget/gif-post-creation.test.js b/web/js/components/animation-widget/gif-post-creation.test.js
index cfb890530..27396e0f9 100644
--- a/web/js/components/animation-widget/gif-post-creation.test.js
+++ b/web/js/components/animation-widget/gif-post-creation.test.js
@@ -1,3 +1,157 @@
-test('gif-post-creation component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import GifResults from './gif-post-creation';
+import FileSaver from 'file-saver';
+import googleTagManager from 'googleTagManager';
+jest.mock('file-saver', () => ({
+ saveAs: jest.fn(),
+}));
+
+jest.mock('googleTagManager', () => ({
+ pushEvent: jest.fn(),
+}));
+
+jest.mock('util', () => ({
+ format: jest.fn().mockImplementation((fmt, start, end) => `nasa-worldview-${start}-to-${end}.gif`),
+}));
+
+jest.mock('lodash/capitalize', () => jest.fn((str) => str.charAt(0).toUpperCase() + str.slice(1)));
+
+jest.mock('../util/monospace-date', () => {
+ return function MockMonospaceDate({ date }) {
+ return <span data-testid={`date-${date}`}>{date}</span>;
+ };
+});
+
+jest.mock('../util/button', () => {
+ return function MockButton({ text, onClick }) {
+ return (
+ <button data-testid="download-button" onClick={onClick}>
+ {text}
+ </button>
+ );
+ };
+});
+
+jest.mock('reactstrap', () => ({
+ Modal: ({ children, style, className }) => <div data-testid="modal" className={className} style={style}>{children}</div>,
+ ModalHeader: ({ children }) => <div data-testid="modal-header">{children}</div>,
+ ModalBody: ({ children }) => <div data-testid="modal-body">{children}</div>,
+}));
+
+describe('GifResults Component', () => {
+ let defaultProps;
+
+ beforeAll(() => {
+ global.URL.createObjectURL = jest.fn(() => 'mock-blob-url');
+ });
+
+ afterAll(() => {
+ global.URL.createObjectURL.mockRestore();
+ });
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ defaultProps = {
+ speed: 10,
+ startDate: '2026-05-01',
+ endDate: '2026-05-20',
+ increment: 'days',
+ gifObject: { blob: new Blob(['mock-data'], { type: 'image/gif' }), size: 15 },
+ boundaries: { x: 0, y: 0, x2: 1000, y2: 800 },
+ screenWidth: 1920,
+ screenHeight: 1080,
+ onClose: jest.fn(),
+ closeBtn: <button>Close</button>,
+ };
+ });
+
+ it('renders correctly with calculated styles and dimensions', () => {
+ const { container } = render(<GifResults {...defaultProps} />);
+
+ expect(screen.getByTestId('modal')).toBeInTheDocument();
+ expect(screen.getByTestId('modal-header')).toBeInTheDocument();
+
+ const img = container.querySelector('img');
+ expect(img).toHaveAttribute('src', 'mock-blob-url');
+ expect(img).toHaveAttribute('width', '1000');
+ expect(img).toHaveAttribute('height', '800');
+
+ expect(screen.getByText('15 MB')).toBeInTheDocument();
+ expect(screen.getByText('10 fps')).toBeInTheDocument();
+ expect(screen.getByText('Days')).toBeInTheDocument();
+
+ expect(screen.getByTestId('date-2026-05-01')).toBeInTheDocument();
+ expect(screen.getByTestId('date-2026-05-20')).toBeInTheDocument();
+ });
+
+ it('restricts image dimensions based on screen size', () => {
+ const smallScreenProps = {
+ ...defaultProps,
+ screenWidth: 1000,
+ screenHeight: 800,
+ };
+
+ const { container } = render(<GifResults {...smallScreenProps} />);
+
+ const img = container.querySelector('img');
+ expect(img).toHaveAttribute('width', '802');
+ expect(img).toHaveAttribute('height', '680');
+ });
+
+ it('triggers download and pushes googleTagManager event for medium size', () => {
+ render(<GifResults {...defaultProps} />);
+
+ const downloadBtn = screen.getByTestId('download-button');
+ fireEvent.click(downloadBtn);
+
+ expect(FileSaver.saveAs).toHaveBeenCalledWith(defaultProps.gifObject.blob, 'nasa-worldview-2026-05-01-to-2026-05-20.gif');
+
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'GIF_download',
+ GIF: {
+ downloadSize: '5MB-25MB',
+ increments: 'days',
+ frameSpeed: 10,
+ },
+ });
+ });
+
+ it('pushes googleTagManager event with size range <5MB', () => {
+ const smallGifProps = {
+ ...defaultProps,
+ gifObject: { blob: new Blob(), size: 3 },
+ };
+
+ render(<GifResults {...smallGifProps} />);
+
+ fireEvent.click(screen.getByTestId('download-button'));
+
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ GIF: expect.objectContaining({ downloadSize: '<5MB' }),
+ }),
+ );
+ });
+
+ it('pushes googleTagManager event with size range >25MB', () => {
+ const largeGifProps = {
+ ...defaultProps,
+ gifObject: { blob: new Blob(), size: 30 },
+ };
+
+ render(<GifResults {...largeGifProps} />);
+
+ fireEvent.click(screen.getByTestId('download-button'));
+
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ GIF: expect.objectContaining({ downloadSize: '>25MB' }),
+ }),
+ );
+ });
});
diff --git a/web/js/components/animation-widget/loading-indicator.test.js b/web/js/components/animation-widget/loading-indicator.test.js
index 7141b24e2..bd57799de 100644
--- a/web/js/components/animation-widget/loading-indicator.test.js
+++ b/web/js/components/animation-widget/loading-indicator.test.js
@@ -1,3 +1,80 @@
-test('loading-indicator component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import LoadingIndicator from './loading-indicator';
+jest.mock('reactstrap', () => ({
+ Modal: ({ children, isOpen }) => (isOpen ? <div data-testid="modal">{children}</div> : null),
+ ModalHeader: ({ children, close }) => (
+ <div data-testid="modal-header">
+ {children}
+ {close}
+ </div>
+ ),
+ ModalBody: ({ children }) => <div data-testid="modal-body">{children}</div>,
+ Progress: ({ value }) => <div data-testid="progress-bar" data-value={value} />,
+}));
+
+describe('LoadingIndicator Component', () => {
+ let defaultProps;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ defaultProps = {
+ onClose: jest.fn(),
+ title: 'Loading Data',
+ bodyMsg: 'Please wait while we load your data...',
+ loadedItems: 25,
+ totalItems: 100,
+ isKioskModeActive: false,
+ };
+ });
+
+ it('renders correctly with title, body message, and calculates progress', () => {
+ render(<LoadingIndicator {...defaultProps} />);
+
+ expect(screen.getByTestId('modal')).toBeInTheDocument();
+ expect(screen.getByText('Loading Data')).toBeInTheDocument();
+ expect(screen.getByText('Please wait while we load your data...')).toBeInTheDocument();
+
+ const progressBar = screen.getByTestId('progress-bar');
+ expect(progressBar).toBeInTheDocument();
+ expect(progressBar).toHaveAttribute('data-value', '25');
+ });
+
+ it('calculates complex progress values correctly', () => {
+ render(<LoadingIndicator {...defaultProps} loadedItems={3} totalItems={7} />);
+
+ const progressBar = screen.getByTestId('progress-bar');
+ expect(progressBar).toHaveAttribute('data-value', '43');
+ });
+
+ it('does not render if isKioskModeActive is true', () => {
+ const { container } = render(<LoadingIndicator {...defaultProps} isKioskModeActive />);
+
+ expect(screen.queryByTestId('modal')).not.toBeInTheDocument();
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('calls onClose when the close button is clicked', () => {
+ render(<LoadingIndicator {...defaultProps} />);
+
+ const closeBtn = screen.getByRole('button');
+ fireEvent.click(closeBtn);
+
+ expect(defaultProps.onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not render the body message if bodyMsg is not provided', () => {
+ render(<LoadingIndicator {...defaultProps} bodyMsg={undefined} />);
+
+ expect(screen.queryByText('Please wait while we load your data...')).not.toBeInTheDocument();
+ });
+
+ it('does not render the progress bar if totalItems is not provided', () => {
+ render(<LoadingIndicator {...defaultProps} totalItems={undefined} />);
+
+ expect(screen.queryByTestId('progress-bar')).not.toBeInTheDocument();
+ });
});
diff --git a/web/js/components/animation-widget/loop-button.test.js b/web/js/components/animation-widget/loop-button.test.js
index eca1cf37a..9cc0fc27a 100644
--- a/web/js/components/animation-widget/loop-button.test.js
+++ b/web/js/components/animation-widget/loop-button.test.js
@@ -1,3 +1,64 @@
-test('loop-button component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import LoopButton from './loop-button';
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: () => <svg data-testid="fa-icon" />,
+}));
+
+jest.mock('reactstrap', () => ({
+ UncontrolledTooltip: ({ children, target }) => (
+ <div data-testid="tooltip" data-target={target}>{children}</div>
+ ),
+}));
+
+describe('LoopButton Component', () => {
+ let defaultProps;
+
+ beforeEach(() => {
+ defaultProps = {
+ looping: false,
+ onLoop: jest.fn(),
+ isMobile: false,
+ };
+ });
+
+ it('renders correctly in desktop mode when not looping', () => {
+ render(<LoopButton {...defaultProps} />);
+
+ const button = screen.getByRole('button', { name: 'Enable animation loop' });
+ expect(button).toBeInTheDocument();
+ expect(button).toHaveClass('wv-loop-icon-case wv-icon-case no-drag');
+ expect(button).not.toHaveClass('active');
+
+ expect(screen.getByTestId('tooltip')).toHaveTextContent('Enable animation loop');
+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-target', 'loop-button');
+ expect(screen.getByTestId('fa-icon')).toBeInTheDocument();
+ });
+
+ it('renders correctly when looping is true', () => {
+ render(<LoopButton {...defaultProps} looping />);
+
+ const button = screen.getByRole('button', { name: 'Disable animation loop' });
+ expect(button).toHaveClass('wv-loop-icon-case wv-icon-case no-drag active');
+
+ expect(screen.getByTestId('tooltip')).toHaveTextContent('Disable animation loop');
+ });
+
+ it('does not render tooltip when in mobile mode', () => {
+ render(<LoopButton {...defaultProps} isMobile />);
+
+ expect(screen.queryByTestId('tooltip')).not.toBeInTheDocument();
+ });
+
+ it('calls onLoop when button is clicked', () => {
+ render(<LoopButton {...defaultProps} />);
+
+ const button = screen.getByRole('button');
+ fireEvent.click(button);
+
+ expect(defaultProps.onLoop).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/web/js/components/animation-widget/play-button.test.js b/web/js/components/animation-widget/play-button.test.js
index 633e1d4ed..5c632089a 100644
--- a/web/js/components/animation-widget/play-button.test.js
+++ b/web/js/components/animation-widget/play-button.test.js
@@ -1,3 +1,79 @@
-test('play-button component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import PlayButton from './play-button';
+jest.mock('@fortawesome/react-fontawesome', () => ({
+ FontAwesomeIcon: ({ icon }) => <svg data-testid={`fa-icon-${icon}`} />,
+}));
+
+jest.mock('reactstrap', () => ({
+ UncontrolledTooltip: ({ children, target }) => (
+ <div data-testid="tooltip" data-target={target}>{children}</div>
+ ),
+}));
+
+describe('PlayButton Component', () => {
+ let defaultProps;
+
+ beforeEach(() => {
+ defaultProps = {
+ playing: false,
+ pause: jest.fn(),
+ play: jest.fn(),
+ isDisabled: false,
+ isMobile: false,
+ };
+ });
+
+ it('renders correctly when not playing and not disabled', () => {
+ render(<PlayButton {...defaultProps} />);
+
+ const button = screen.getByRole('button', { name: 'Play animation' });
+ expect(button).toBeInTheDocument();
+ expect(button).toHaveClass('wv-anim-play-case wv-icon-case no-drag');
+ expect(button).not.toHaveClass('disabled');
+
+ expect(screen.getByTestId('tooltip')).toHaveTextContent('Play animation');
+ expect(screen.getByTestId('fa-icon-play')).toBeInTheDocument();
+
+ fireEvent.click(button);
+ expect(defaultProps.play).toHaveBeenCalledTimes(1);
+ expect(defaultProps.pause).not.toHaveBeenCalled();
+ });
+
+ it('renders correctly when playing is true', () => {
+ render(<PlayButton {...defaultProps} playing />);
+
+ const button = screen.getByRole('button', { name: 'Pause animation' });
+ expect(button).toBeInTheDocument();
+
+ expect(screen.getByTestId('tooltip')).toHaveTextContent('Pause animation');
+ expect(screen.getByTestId('fa-icon-pause')).toBeInTheDocument();
+
+ fireEvent.click(button);
+ expect(defaultProps.pause).toHaveBeenCalledTimes(1);
+ expect(defaultProps.play).not.toHaveBeenCalled();
+ });
+
+ it('renders correctly when disabled is true', () => {
+ render(<PlayButton {...defaultProps} isDisabled />);
+
+ const expectedLabel = 'Too many animation frames. Reduce time range or increase increment size.';
+ const button = screen.getByRole('button', { name: expectedLabel });
+
+ expect(button).toHaveClass('disabled');
+ expect(screen.getByTestId('tooltip')).toHaveTextContent(expectedLabel);
+
+ fireEvent.click(button);
+ expect(defaultProps.play).not.toHaveBeenCalled();
+ expect(defaultProps.pause).not.toHaveBeenCalled();
+ });
+
+ it('does not render tooltip when isMobile is true', () => {
+ render(<PlayButton {...defaultProps} isMobile />);
+
+ expect(screen.queryByTestId('tooltip')).not.toBeInTheDocument();
+ });
});
diff --git a/web/js/components/animation-widget/play-queue.js b/web/js/components/animation-widget/play-queue.js
index 2cddc550e..ec8f76d17 100644
--- a/web/js/components/animation-widget/play-queue.js
+++ b/web/js/components/animation-widget/play-queue.js
@@ -347,7 +347,9 @@ function PlayQueue(props) {
}
function stopPlaying() {
- abortController.abort();
+ if (abortController) {
+ abortController.abort();
+ }
setIsAnimating(false);
hasPlayStarted = false;
}
diff --git a/web/js/components/animation-widget/play-queue.test.js b/web/js/components/animation-widget/play-queue.test.js
index 78708adcc..51a1e6d91 100644
--- a/web/js/components/animation-widget/play-queue.test.js
+++ b/web/js/components/animation-widget/play-queue.test.js
@@ -1,3 +1,283 @@
-test('play-queue component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, cleanup, act, waitFor, screen } from '@testing-library/react';
+import '@testing-library/jest-dom';
+jest.mock('./loading-indicator', () => {
+ return function MockLoadingIndicator() {
+ return <div data-testid="loading-indicator">Loading...</div>;
+ };
+});
+
+jest.mock('reactstrap', () => ({
+ Progress: ({ value }) => <div data-testid="progress-bar" data-value={String(value)} />,
+}));
+
+jest.mock('p-queue', () => {
+ class MockPQueue {
+ constructor() {
+ this.size = 0;
+ this.pending = 0;
+ }
+
+ add(fn) {
+ return fn();
+ }
+
+ clear() {}
+ onEmpty() {
+ return Promise.resolve();
+ }
+ }
+
+ const Timeout = class TimeoutError extends Error {};
+
+ return {
+ __esModule: true,
+ default: MockPQueue,
+ TimeoutError: Timeout,
+ };
+});
+
+jest.mock('../../util/util', () => {
+ const mocked = {
+ dateAdd: jest.fn((date, interval, delta) => new Date(date.getTime() + 86400000)),
+ objectLength: jest.fn((obj) => Object.keys(obj || {}).length),
+ toISOStringSeconds: jest.fn((date) => (date ? date.toISOString() : '')),
+ parseDateUTC: jest.fn((str) => new Date(str)),
+ };
+
+ return {
+ __esModule: true,
+ default: mocked,
+ ...mocked,
+ };
+});
+
+jest.mock('../../modules/date/util', () => ({
+ getNextImageryDelta: jest.fn(() => new Date('2026-05-01T00:00:00Z')),
+}));
+
+const PlayQueue = require('./play-queue').default;
+const { TimeoutError } = require('p-queue');
+const { getNextImageryDelta } = jest.requireMock('../../modules/date/util');
+
+describe('PlayQueue Component', () => {
+ let defaultProps;
+ let rafCallbacks;
+ let nextRafId;
+ let currentTime;
+ let viewHandlers;
+ let view;
+ let selected;
+
+ const flushRaf = (timestamp = currentTime) => {
+ const callbacks = Array.from(rafCallbacks.values());
+ rafCallbacks.clear();
+ callbacks.forEach((cb) => cb(timestamp));
+ };
+
+ beforeAll(() => {
+ rafCallbacks = new Map();
+ nextRafId = 1;
+
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
+ const id = nextRafId++;
+ rafCallbacks.set(id, cb);
+ return id;
+ });
+
+ jest.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => {
+ rafCallbacks.delete(id);
+ });
+
+ if (!document.timeline) {
+ document.timeline = { currentTime: 1000 };
+ }
+ });
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ currentTime = 1000;
+ jest.spyOn(performance, 'now').mockImplementation(() => currentTime);
+
+ viewHandlers = {};
+ view = {
+ on: jest.fn((name, cb) => {
+ viewHandlers[name] = cb;
+ }),
+ un: jest.fn(),
+ };
+ selected = {
+ getView: jest.fn(() => view),
+ on: jest.fn((name, cb) => {
+ viewHandlers[name] = cb;
+ }),
+ un: jest.fn(),
+ };
+
+ defaultProps = {
+ endDate: new Date('2026-05-10T00:00:00Z'),
+ isMobile: false,
+ isPlaying: true,
+ promiseImageryForTime: jest.fn(() => Promise.resolve()),
+ selectDate: jest.fn(),
+ speed: 10,
+ startDate: new Date('2026-05-01T00:00:00Z'),
+ togglePlaying: jest.fn(),
+ currentDate: new Date('2026-05-01T00:00:00Z'),
+ delta: 1,
+ interval: 'day',
+ isLoopActive: true,
+ onClose: jest.fn(),
+ numberOfFrames: 10,
+ snappedCurrentDate: new Date('2026-05-01T00:00:00Z'),
+ isKioskModeActive: false,
+ map: {
+ ui: {
+ selected,
+ },
+ },
+ autoSelected: false,
+ layers: [],
+ };
+ });
+
+ afterEach(() => {
+ cleanup();
+ jest.clearAllMocks();
+ jest.clearAllTimers();
+ // Fully drain RAF callbacks with a safety limit to prevent infinite loops
+ let attempts = 0;
+ while (rafCallbacks.size > 0 && attempts < 10) {
+ flushRaf();
+ attempts++;
+ }
+ rafCallbacks.clear();
+ jest.useRealTimers();
+ });
+
+ afterAll(() => {
+ // Reset state for subsequent test runs
+ rafCallbacks.clear();
+ nextRafId = 1;
+ currentTime = 1000;
+ jest.restoreAllMocks();
+ });
+
+ const advanceAnimation = async (ms) => {
+ currentTime += ms;
+ await act(async () => {
+ jest.advanceTimersByTime(ms);
+ flushRaf(currentTime);
+ await Promise.resolve();
+ });
+ };
+
+ const renderPlayQueue = async (props = {}) => {
+ let result;
+
+ await act(async () => {
+ result = render(<PlayQueue {...defaultProps} {...props} />);
+ await Promise.resolve();
+ });
+
+ return result;
+ };
+
+ it('renders the loading indicator while buffering frames when there is only one frame', async () => {
+ await act(async () => {
+ render(<PlayQueue {...defaultProps} isPlaying={false} numberOfFrames={1} />);
+ await Promise.resolve();
+ });
+
+ expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
+ });
+
+ it('updates the loop active ref on prop change without throwing', async () => {
+ const { rerender } = await renderPlayQueue({ isLoopActive: false });
+ rerender(<PlayQueue {...defaultProps} isLoopActive />);
+ expect(defaultProps.togglePlaying).not.toHaveBeenCalled();
+ });
+
+ it('handles speed changes and buffer size calculations on rerender', async () => {
+ const { rerender } = await renderPlayQueue({ speed: 0.5 });
+ rerender(<PlayQueue {...defaultProps} speed={2} />);
+ expect(defaultProps.promiseImageryForTime).toHaveBeenCalled();
+ });
+
+ it('cleans up registered event listeners on unmount', async () => {
+ const { unmount } = await renderPlayQueue({ isPlaying: false });
+ unmount();
+
+ expect(selected.getView).toHaveBeenCalled();
+ expect(view.un).toHaveBeenCalledWith('propertychange', expect.any(Function));
+ expect(selected.un).toHaveBeenCalledWith('moveend', expect.any(Function));
+ });
+
+ it('handles TimeoutError during imagery preload', async () => {
+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
+ defaultProps.promiseImageryForTime.mockRejectedValue(new TimeoutError('Loading timed out'));
+
+ await act(async () => {
+ render(<PlayQueue {...defaultProps} />);
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Imagery loading timed out'));
+ });
+
+ consoleSpy.mockRestore();
+ });
+
+ it('executes the animation loop and advances frames', async () => {
+ await renderPlayQueue();
+
+ await advanceAnimation(5000);
+ await advanceAnimation(5000);
+
+ expect(defaultProps.selectDate).toHaveBeenCalled();
+ });
+
+ it('renders progress bar on mobile when animation starts', async () => {
+ await renderPlayQueue({ isMobile: true, speed: 2 });
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('progress-bar')).toBeInTheDocument();
+ });
+
+ expect(screen.getByTestId('progress-bar')).toHaveAttribute('data-value');
+ });
+
+ it('uses autoSelected date calculation when enabled', async () => {
+ await renderPlayQueue({ autoSelected: true, layers: [{}] });
+ expect(getNextImageryDelta).toHaveBeenCalled();
+ });
+
+ it('selects the startDate immediately when there is only one frame', async () => {
+ await renderPlayQueue({ numberOfFrames: 1 });
+
+ expect(defaultProps.selectDate).toHaveBeenCalledWith(defaultProps.startDate);
+ expect(defaultProps.togglePlaying).toHaveBeenCalled();
+ });
+
+ it('stops playing and toggles off when loop is disabled and endDate is reached', async () => {
+ await renderPlayQueue({ isLoopActive: false, snappedCurrentDate: defaultProps.endDate });
+
+ await advanceAnimation(5000);
+ await advanceAnimation(5000);
+
+ expect(defaultProps.togglePlaying).toHaveBeenCalled();
+ });
+
+ it('loops back to startDate when reaching endDate with loop active', async () => {
+ await renderPlayQueue({ isLoopActive: true, snappedCurrentDate: defaultProps.endDate });
+
+ await advanceAnimation(5000);
+ await advanceAnimation(5000);
+
+ expect(defaultProps.togglePlaying).not.toHaveBeenCalled();
+ expect(defaultProps.selectDate).toHaveBeenCalledWith(defaultProps.startDate);
+ });
});
diff --git a/web/js/components/charting/chart-component.js b/web/js/components/charting/chart-component.js
index 8bfe105d2..82624f424 100644
--- a/web/js/components/charting/chart-component.js
+++ b/web/js/components/charting/chart-component.js
@@ -27,7 +27,7 @@ import {
import util from '../../util/util';
// Gets the indices of the tick positions so that they are evenly spaced
-function getTickPositions(dataLength) {
+export function getTickPositions(dataLength) {
// If dataLength is too small, just show first and last tick
if (dataLength < 8) return [0, dataLength - 1];
@@ -66,7 +66,7 @@ function getTickPositions(dataLength) {
return tickPosArr;
}
-function CustomXAxisTick(props) {
+export function CustomXAxisTick(props) {
const {
x, y, fill, textAnchor, visibleTicksCount, index, payload, data,
} = props;
@@ -90,7 +90,7 @@ function CustomXAxisTick(props) {
);
}
-function formatToThreeDigits(str) {
+export function formatToThreeDigits(str) {
if (parseFloat(str).toFixed(3)
.split('.')[0].length > 4) {
return Number(parseFloat(str).toFixed(3)).toPrecision(3);
@@ -98,7 +98,7 @@ function formatToThreeDigits(str) {
return parseFloat(str).toFixed(3);
}
-function CustomTooltip({
+export function CustomTooltip({
active, payload, label, unit, setHoveredDate,
}) {
setHoveredDate(label);
diff --git a/web/js/components/charting/chart-component.test.js b/web/js/components/charting/chart-component.test.js
index 0faf9deb6..e1a515aae 100644
--- a/web/js/components/charting/chart-component.test.js
+++ b/web/js/components/charting/chart-component.test.js
@@ -1,3 +1,228 @@
-test('chart-component component test', () => {
+/* eslint-disable react/jsx-props-no-spreading */
+/* eslint-disable react/prop-types */
+import { render, fireEvent } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import configureStore from 'redux-mock-store';
+import ChartComponent, { getTickPositions, CustomXAxisTick, CustomTooltip } from './chart-component';
+// A more robust mock to handle both default and named imports depending on how util is imported
+jest.mock('../../util/util', () => {
+ const utilMock = {
+ formatCoordinate: jest.fn(() => '10.00, 10.00'),
+ getCoordinateFormat: jest.fn(() => (coord) => coord),
+ };
+ return {
+ __esModule: true,
+ default: utilMock,
+ ...utilMock,
+ };
+});
+
+jest.mock('recharts', () => {
+ const OriginalRecharts = jest.requireActual('recharts');
+ return {
+ ...OriginalRecharts,
+ ResponsiveContainer: ({ children }) => <div>{children}</div>,
+ LineChart: ({ children }) => <div>{children}</div>,
+ Line: () => <div data-testid="recharts-line" />,
+ };
+});
+
+const mockStore = configureStore([]);
+
+describe('getTickPositions', () => {
+ it('handles small arrays (< 8)', () => {
+ const result = getTickPositions(5);
+ expect(result).toEqual([0, 4]); // Whatever the expected array is
+ });
+
+ it('handles medium arrays (< 15)', () => {
+ const result = getTickPositions(12);
+ expect(result.length).toBeGreaterThan(2);
+ });
+});
+
+it('renders CustomXAxisTick correctly for labeled positions', () => {
+ const mockProps = {
+ x: 10,
+ y: 10,
+ fill: 'black',
+ textAnchor: 'middle',
+ visibleTicksCount: 5,
+ index: 0,
+ payload: { value: '2023-01-01' },
+ data: new Array(10).fill({}),
+ };
+
+ const { getByText } = render(
+ <svg>
+ <CustomXAxisTick {...mockProps} />
+ </svg>,
+ );
+
+ expect(getByText('2023-01-01')).toBeTruthy();
+});
+
+describe('CustomTooltip', () => {
+ it('renders tooltip content when active with valid payload', () => {
+ const mockProps = {
+ active: true,
+ payload: [{ name: 10 }],
+ label: '2023-01-01',
+ unit: 'K',
+ setHoveredDate: jest.fn(),
+ };
+
+ const { getByText } = render(<CustomTooltip {...mockProps} />);
+ expect(getByText('2023-01-01')).toBeTruthy();
+ expect(getByText('10 (K):')).toBeTruthy();
+ expect(mockProps.setHoveredDate).toHaveBeenCalledWith('2023-01-01');
+ });
+
+ it('renders nothing when not active', () => {
+ const mockProps = {
+ active: false,
+ payload: [{ name: 10 }],
+ label: '2023-01-01',
+ unit: 'K',
+ setHoveredDate: jest.fn(),
+ };
+
+ const { container } = render(<CustomTooltip {...mockProps} />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('renders nothing when payload is empty', () => {
+ const mockProps = {
+ active: true,
+ payload: [],
+ label: '2023-01-01',
+ unit: 'K',
+ setHoveredDate: jest.fn(),
+ };
+
+ const { container } = render(<CustomTooltip {...mockProps} />);
+ expect(container.firstChild).toBeNull();
+ });
+});
+
+describe('ChartComponent', () => {
+ let store;
+ let defaultState;
+ let defaultProps;
+
+ beforeEach(() => {
+ defaultState = {
+ map: {
+ ui: {
+ selected: {
+ getView: jest.fn(() => ({ zoom: 1 })),
+ },
+ createLayer: jest.fn(),
+ },
+ },
+ layers: {
+ layerConfig: {
+ Coastlines_15m: { id: 'Coastlines_15m' },
+ },
+ },
+ };
+
+ defaultProps = {
+ liveData: {
+ data: [
+ { mean: 10, min: 2, max: 20, median: 9, stddev: 1.5, name: '2023-01-01' },
+ { mean: 12, min: 3, max: 22, median: 11, stddev: 1.2, name: '2023-01-02' },
+ ],
+ unit: 'K',
+ startDate: '2023-01-01',
+ endDate: '2023-01-10',
+ numRangeDays: 10,
+ isTruncated: false,
+ title: 'Test Chart',
+ numPoints: 2,
+ coordinates: [0, 0, 10, 10],
+ errors: {
+ error_count: 2,
+ error_days: ['2023-01-05T00:00:00Z', { date: '2023-01-06T00:00:00Z' }],
+ },
+ layerId: 'test-layer',
+ },
+ toggleErrorDaysExpanded: jest.fn(),
+ };
+
+ store = mockStore(defaultState);
+ });
+
+ const renderComponent = (props = defaultProps) => {
+ return render(
+ <Provider store={store}>
+ <ChartComponent {...props} />
+ </Provider>,
+ );
+ };
+
+ it('renders without crashing when provided valid data', () => {
+ const { container } = renderComponent();
+ expect(container).toBeTruthy();
+ });
+
+ it('renders the truncation disclaimer when isTruncated is true', () => {
+ const truncatedProps = {
+ ...defaultProps, liveData: { ...defaultProps.liveData, isTruncated: true },
+ };
+ const { getByText } = renderComponent(truncatedProps);
+ expect(getByText(/As part of this beta feature release/)).toBeTruthy();
+ });
+
+ it('handles NaN values in data gracefully without crashing', () => {
+ const nanProps = {
+ ...defaultProps,
+ liveData: {
+ ...defaultProps.liveData,
+ data: [
+ { mean: NaN, min: NaN, max: NaN, median: NaN, stddev: NaN, name: '2023-01-01' },
+ { mean: 12, min: 3, max: 22, median: 11, stddev: 1.2, name: '2023-01-02' },
+ ],
+ },
+ };
+ const { container } = renderComponent(nanProps);
+ expect(container).toBeTruthy();
+ });
+
+ it('processes and displays error dates correctly', () => {
+ const { getByText, container } = renderComponent();
+ fireEvent.click(container.querySelector('.error-expand-button-inner'));
+ expect(getByText(/2023-01-05,.*2023-01-06/)).toBeTruthy();
+ });
+
+ it('handles empty error dates gracefully', () => {
+ const noErrorsProps = {
+ ...defaultProps,
+ liveData: {
+ ...defaultProps.liveData,
+ errors: { error_days: [] },
+ },
+ };
+ const { container } = renderComponent(noErrorsProps);
+ expect(container).toBeTruthy();
+ });
+
+ it('toggles error collapsed state', () => {
+ const { queryByTestId } = renderComponent();
+
+ const toggleButton = queryByTestId('error-toggle-button');
+ if (toggleButton) {
+ fireEvent.click(toggleButton);
+ expect(defaultProps.toggleErrorDaysExpanded).toHaveBeenCalledWith(false);
+
+ fireEvent.click(toggleButton);
+ expect(defaultProps.toggleErrorDaysExpanded).toHaveBeenCalledWith(true);
+ }
+ });
+
+ it('renders standard chart units', () => {
+ const { getByText } = renderComponent();
+ expect(getByText(/\(K\)/)).toBeTruthy();
+ });
});
diff --git a/web/js/components/charting/charting-area-of-interest-style.test.js b/web/js/components/charting/charting-area-of-interest-style.test.js
index 7e3f1f7e5..3f72f2e93 100644
--- a/web/js/components/charting/charting-area-of-interest-style.test.js
+++ b/web/js/components/charting/charting-area-of-interest-style.test.js
@@ -1,3 +1,35 @@
-test('charting-area-of-interest-style component test', () => {
+import {
+ areaBgFill,
+ solidBlackLineStroke,
+ drawStyles,
+ vectorStyles,
+} from './charting-area-of-interest-style';
+import { Fill, Stroke, Style } from 'ol/style';
+describe('charting-area-of-interest-style', () => {
+ it('should export areaBgFill as an instance of Fill', () => {
+ expect(areaBgFill).toBeDefined();
+ expect(areaBgFill).toBeInstanceOf(Fill);
+ });
+
+ it('should export solidBlackLineStroke as an instance of Stroke', () => {
+ expect(solidBlackLineStroke).toBeDefined();
+ expect(solidBlackLineStroke).toBeInstanceOf(Stroke);
+ });
+
+ it('should export drawStyles array with correct styles', () => {
+ expect(drawStyles).toBeDefined();
+ expect(Array.isArray(drawStyles)).toBe(true);
+ expect(drawStyles.length).toBe(2);
+ expect(drawStyles[0]).toBeInstanceOf(Style);
+ expect(drawStyles[1]).toBeInstanceOf(Style);
+ });
+
+ it('should export vectorStyles array with correct styles', () => {
+ expect(vectorStyles).toBeDefined();
+ expect(Array.isArray(vectorStyles)).toBe(true);
+ expect(vectorStyles.length).toBe(2);
+ expect(vectorStyles[0]).toBeInstanceOf(Style);
+ expect(vectorStyles[1]).toBeInstanceOf(Style);
+ });
});
diff --git a/web/js/components/charting/charting-date-selector.test.js b/web/js/components/charting/charting-date-selector.test.js
index e59788cf9..c14f05f9f 100644
--- a/web/js/components/charting/charting-date-selector.test.js
+++ b/web/js/components/charting/charting-date-selector.test.js
@@ -1,3 +1,122 @@
-test('charting-date-selector component test', () => {
+/* eslint-disable react/prop-types */
+/* eslint-disable react/jsx-props-no-spreading */
+import { render, fireEvent } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import configureStore from 'redux-mock-store';
+import ChartingDateSelector from './charting-date-selector';
+import {
+ changeChartingStartDate,
+ changeChartingEndDate,
+} from '../../modules/charting/actions';
+jest.mock('../date-selector/date-range-selector', () => (props) => (
+ <button
+ data-testid="date-range-selector"
+ onClick={() => props.setDateRange(['2023-05-02', '2023-05-10'])}
+ >
+ DateRangeSelector
+ </button>
+));
+
+jest.mock('../date-selector/date-selector', () => (props) => (
+ <button
+ data-testid="date-selector"
+ onClick={() => props.onDateChange('2023-05-02')}
+ >
+ DateSelector
+ </button>
+));
+
+jest.mock('../../modules/charting/actions', () => ({
+ changeChartingStartDate: jest.fn(() => ({ type: 'CHANGE_START' })),
+ changeChartingEndDate: jest.fn(() => ({ type: 'CHANGE_END' })),
+}));
+
+const mockStore = configureStore([]);
+
+describe('ChartingDateSelector', () => {
+ let store;
+ let baseState;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ baseState = {
+ date: {
+ selected: '2023-05-01',
+ selectedB: '2023-05-05',
+ },
+ charting: {
+ timeSpanStartDate: null,
+ timeSpanEndDate: null,
+ },
+ };
+ });
+
+ const renderComponent = (props = {}, state = baseState) => {
+ store = mockStore(state);
+ store.dispatch = jest.fn();
+
+ return render(
+ <Provider store={store}>
+ <ChartingDateSelector
+ layerStartDate="2023-01-01"
+ layerEndDate="2023-12-31"
+ {...props}
+ />
+ </Provider>,
+ );
+ };
+
+ it('renders DateSelector when timeSpanSelection is "date"', () => {
+ const { getByTestId, queryByTestId } = renderComponent({ timeSpanSelection: 'date' });
+ expect(getByTestId('date-selector')).toBeTruthy();
+ expect(queryByTestId('date-range-selector')).toBeNull();
+ });
+
+ it('renders DateRangeSelector when timeSpanSelection is not "date"', () => {
+ const { getByTestId, queryByTestId } = renderComponent({ timeSpanSelection: 'range' });
+ expect(getByTestId('date-range-selector')).toBeTruthy();
+ expect(queryByTestId('date-selector')).toBeNull();
+ });
+
+ it('dispatches changeChartingStartDate when single date changes', () => {
+ const { getByTestId } = renderComponent({ timeSpanSelection: 'date' });
+
+ fireEvent.click(getByTestId('date-selector'));
+
+ expect(changeChartingStartDate).toHaveBeenCalledWith('2023-05-02');
+ expect(store.dispatch).toHaveBeenCalledWith({ type: 'CHANGE_START' });
+ });
+
+ it('dispatches start and end date changes when date range changes', () => {
+ const { getByTestId } = renderComponent({ timeSpanSelection: 'range' });
+
+ fireEvent.click(getByTestId('date-range-selector'));
+
+ expect(changeChartingStartDate).toHaveBeenCalledWith('2023-05-02');
+ expect(changeChartingEndDate).toHaveBeenCalledWith('2023-05-10');
+ expect(store.dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not dispatch if new dates match existing timeSpan dates', () => {
+ const stateWithSameDates = {
+ ...baseState,
+ charting: {
+ timeSpanStartDate: '2023-05-02',
+ timeSpanEndDate: '2023-05-10',
+ },
+ };
+
+ const { getByTestId } = renderComponent({ timeSpanSelection: 'range' }, stateWithSameDates);
+
+ fireEvent.click(getByTestId('date-range-selector'));
+
+ expect(changeChartingStartDate).not.toHaveBeenCalled();
+ expect(changeChartingEndDate).not.toHaveBeenCalled();
+ });
+
+ it('uses selected and selectedB from date state when timeSpan dates are null', () => {
+ const { getByTestId } = renderComponent({ timeSpanSelection: 'range' });
+ expect(getByTestId('date-range-selector')).toBeTruthy();
+ });
});
diff --git a/web/js/components/charting/charting-error.test.js b/web/js/components/charting/charting-error.test.js
index 3596fcd38..16312b9a0 100644
--- a/web/js/components/charting/charting-error.test.js
+++ b/web/js/components/charting/charting-error.test.js
@@ -1,3 +1,16 @@
-test('charting-error component test', () => {
+import { render } from '@testing-library/react';
+import ChartingError from './charting-error';
+describe('ChartingError', () => {
+ it('renders without crashing when no props are provided', () => {
+ const { container } = render(<ChartingError />);
+ expect(container.querySelector('.charting-error-container')).toBeTruthy();
+ expect(container.querySelector('.charting-error-text')).toBeTruthy();
+ });
+
+ it('renders the provided msg prop correctly', () => {
+ const testMessage = 'An unexpected error occurred during charting.';
+ const { getByText } = render(<ChartingError msg={testMessage} />);
+ expect(getByText(testMessage)).toBeTruthy();
+ });
});
diff --git a/web/js/components/charting/charting-info.test.js b/web/js/components/charting/charting-info.test.js
index 95dc2f0dc..87bdff0f2 100644
--- a/web/js/components/charting/charting-info.test.js
+++ b/web/js/components/charting/charting-info.test.js
@@ -1,3 +1,85 @@
-test('charting-info component test', () => {
+import { render, fireEvent } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import configureStore from 'redux-mock-store';
+import ChartingInfo from './charting-info';
+import onClickFeedback from '../../modules/feedback/util';
+import initFeedback from '../../modules/feedback/actions';
+jest.mock('../../modules/feedback/util', () => jest.fn());
+jest.mock('../../modules/feedback/actions', () => jest.fn(() => ({ type: 'INIT_FEEDBACK' })));
+
+const mockStore = configureStore([]);
+
+describe('ChartingInfo', () => {
+ let store;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ store = mockStore({
+ feedback: { isInitiated: false },
+ screenSize: { isMobileDevice: true },
+ });
+ store.dispatch = jest.fn();
+ });
+
+ const renderComponent = (customStore) => {
+ return render(
+ <Provider store={customStore || store}>
+ <ChartingInfo />
+ </Provider>,
+ );
+ };
+
+ it('renders the charting info text', () => {
+ const { container, getByText } = renderComponent();
+ expect(container.querySelector('.charting-info-container')).toBeTruthy();
+ expect(getByText(/The charting feature is available for beta testing/i)).toBeTruthy();
+ });
+
+ it('calls onClickFeedback and dispatches initFeedback when feedback span is clicked', () => {
+ const { getByText } = renderComponent();
+ const feedbackSpan = getByText('Please send comments and feedback to us.');
+
+ fireEvent.click(feedbackSpan);
+
+ expect(onClickFeedback).toHaveBeenCalledWith(false, true);
+ expect(initFeedback).toHaveBeenCalled();
+ expect(store.dispatch).toHaveBeenCalledWith({ type: 'INIT_FEEDBACK' });
+ });
+
+ it('calls onClickFeedback but does not dispatch initFeedback when feedback is already initiated', () => {
+ const customStore = mockStore({
+ feedback: { isInitiated: true },
+ screenSize: { isMobileDevice: false },
+ });
+ customStore.dispatch = jest.fn();
+
+ const { getByText } = renderComponent(customStore);
+ const feedbackSpan = getByText('Please send comments and feedback to us.');
+
+ fireEvent.click(feedbackSpan);
+
+ expect(onClickFeedback).toHaveBeenCalledWith(true, false);
+ expect(initFeedback).not.toHaveBeenCalled();
+ expect(customStore.dispatch).not.toHaveBeenCalled();
+ });
+
+ it('triggers feedback on Enter keydown', () => {
+ const { getByText } = renderComponent();
+ const feedbackSpan = getByText('Please send comments and feedback to us.');
+
+ fireEvent.keyDown(feedbackSpan, { key: 'Enter', code: 'Enter' });
+
+ expect(initFeedback).toHaveBeenCalled();
+ });
+
+ it('does not trigger feedback on other keydown events', () => {
+ const { getByText } = renderComponent();
+ const feedbackSpan = getByText('Please send comments and feedback to us.');
+
+ fireEvent.keyDown(feedbackSpan, { key: 'Space', code: 'Space' });
+
+ expect(onClickFeedback).not.toHaveBeenCalled();
+ expect(initFeedback).not.toHaveBeenCalled();
+ });
});
diff --git a/web/js/components/charting/simple-statistics.test.js b/web/js/components/charting/simple-statistics.test.js
index 948bb29d8..8345f7522 100644
--- a/web/js/components/charting/simple-statistics.test.js
+++ b/web/js/components/charting/simple-statistics.test.js
@@ -1,3 +1,56 @@
-test('simple-statistics component test', () => {
+import { render } from '@testing-library/react';
+import SimpleStatistics from './simple-statistics';
+describe('SimpleStatistics', () => {
+ const standardData = {
+ date: '2023-01-01',
+ statData: {
+ median: '10.1234',
+ mean: 15.5678,
+ min: '1.2',
+ max: 100.999,
+ stdev: '2.3456',
+ },
+ };
+
+ const largeNumberData = {
+ date: '2023-01-02',
+ statData: {
+ median: '12345.67',
+ mean: '98765.43',
+ min: 0,
+ max: '1000000',
+ stdev: 1234.5,
+ },
+ };
+
+ it('renders dates and labels correctly', () => {
+ const { getByText } = render(<SimpleStatistics data={standardData} />);
+
+ expect(getByText('Date: 2023-01-01')).toBeTruthy();
+ expect(getByText('Median:')).toBeTruthy();
+ expect(getByText('Mean:')).toBeTruthy();
+ expect(getByText('Min:')).toBeTruthy();
+ expect(getByText('Max:')).toBeTruthy();
+ expect(getByText('Stdev:')).toBeTruthy();
+ expect(getByText(/Numerical analyses performed on imagery should/i)).toBeTruthy();
+ });
+
+ it('formats standard numbers to three decimal places', () => {
+ const { getByText } = render(<SimpleStatistics data={standardData} />);
+
+ expect(getByText('10.123')).toBeTruthy();
+ expect(getByText('15.568')).toBeTruthy();
+ expect(getByText('1.200')).toBeTruthy();
+ expect(getByText('2.346')).toBeTruthy();
+ });
+
+ it('formats large numbers using scientific notation precision when digits before decimal are greater than 4', () => {
+ const { getByText } = render(<SimpleStatistics data={largeNumberData} />);
+
+ expect(getByText('1.23e+4')).toBeTruthy();
+ expect(getByText('9.88e+4')).toBeTruthy();
+ expect(getByText('1.00e+6')).toBeTruthy();
+ expect(getByText('1234.500')).toBeTruthy();
+ });
});